Skip to content

Commit 918692f

Browse files
authored
Tiny pro sever egg (#57)
* feat: egg API getUserInfo * feat: egg API login register * fix: fix err code * fix: fix PR suggestion * fix: fix database name
1 parent 4475335 commit 918692f

File tree

13 files changed

+299
-9
lines changed

13 files changed

+299
-9
lines changed
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import { Controller } from 'egg';
2+
import BcryptUtils from '../utils/bcrypt-utils';
3+
4+
export default class UserController extends Controller {
5+
// 注册用户
6+
public async registerUser() {
7+
const { ctx, app } = this;
8+
const payload = ctx.request.body || {};
9+
const transaction = await ctx.model.transaction();
10+
try {
11+
this.logger.info('[ controller | user ] registerUser : 进入registerUser方法');
12+
// 校验参数
13+
const registerUserRule = {
14+
user_name: { type: 'email' },
15+
password: {
16+
type: 'string',
17+
format: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/,
18+
},
19+
};
20+
const err = app.validator.validate(registerUserRule, payload);
21+
if (err?.length) {
22+
ctx.helper.commonJson(ctx, {}, 500, 'InvalidParameter');
23+
return;
24+
}
25+
const { user_name, password } = payload;
26+
// 判断用户是否已经存在
27+
const user = await ctx.service.user.getUserByName(user_name);
28+
if (user) {
29+
ctx.helper.commonJson(ctx, {}, 500, 'UserAlreadyExist');
30+
return;
31+
}
32+
const hash = BcryptUtils.genHash(password);
33+
// 创建用户
34+
const { id } = await ctx.service.user.createUser({ user_name, password: hash }, { transaction });
35+
const userInfo = await ctx.service.user.createUserInfo({ user_name, user_id: id }, { transaction });
36+
await transaction.commit();
37+
ctx.helper.commonJson(ctx, userInfo, 200);
38+
} catch (error) {
39+
await transaction.rollback();
40+
ctx.helper.commonJson(ctx, {}, 500, 'InterError');
41+
}
42+
}
43+
44+
// 获取用户信息
45+
public async getUserInfo() {
46+
const { ctx } = this;
47+
const { id } = ctx.params;
48+
49+
try {
50+
this.logger.info('[ controller | user ] getUserInfo : 进入getUserInfo方法');
51+
const userInfo = await ctx.service.user.getUserInfoById(id);
52+
if (!userInfo) {
53+
ctx.helper.commonJson(ctx, {}, 500, 'UserNotFound');
54+
return;
55+
}
56+
ctx.helper.commonJson(ctx, userInfo, 200);
57+
} catch (error) {
58+
ctx.helper.commonJson(ctx, {}, 500, 'InterError');
59+
}
60+
}
61+
62+
// 登录
63+
public async login() {
64+
const { ctx, app } = this;
65+
const payload = ctx.request.body || {};
66+
try {
67+
this.logger.info('[ controller | user ] login : 进入login方法');
68+
// 校验参数格式
69+
const err = app.validator.validate(
70+
{
71+
user_name: { type: 'email' },
72+
password: { type: 'string' },
73+
},
74+
payload,
75+
);
76+
if (err?.length) {
77+
ctx.helper.commonJson(ctx, {}, 500, 'InvalidParameter');
78+
return;
79+
}
80+
81+
// 用户是否存在
82+
const user = await ctx.service.user.getUserByName(payload.user_name);
83+
if (!user) {
84+
ctx.helper.commonJson(ctx, {}, 500, 'UserNotFound');
85+
return;
86+
}
87+
88+
// 密码是否正确
89+
const match = BcryptUtils.compare(payload.password, user.password);
90+
if (!match) {
91+
ctx.helper.commonJson(ctx, {}, 500, 'ErrorPassword');
92+
return;
93+
}
94+
95+
// 生成Token
96+
const { secret, sign } = this.app.config.jwt;
97+
const userInfo = await ctx.service.user.getUserInfoById(user.id);
98+
const token = this.app.jwt.sign(userInfo, secret, sign);
99+
ctx.helper.commonJson(ctx, { token }, 200);
100+
} catch (error) {
101+
ctx.helper.commonJson(ctx, {}, 500, 'InterError');
102+
}
103+
}
104+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/* indent size: 4 */
2+
3+
module.exports = (app: any) => {
4+
const DataTypes = app.Sequelize;
5+
6+
const RegisterUser = app.model.define(
7+
'RegisterUser',
8+
{
9+
id: {
10+
type: DataTypes.INTEGER(20).UNSIGNED,
11+
allowNull: false,
12+
primaryKey: true,
13+
autoIncrement: true,
14+
},
15+
user_name: {
16+
type: DataTypes.STRING(32),
17+
allowNull: false,
18+
},
19+
password: {
20+
type: DataTypes.STRING(60),
21+
allowNull: false,
22+
},
23+
register_type: {
24+
type: DataTypes.ENUM('email'),
25+
allowNull: false,
26+
defaultValue: 'email',
27+
},
28+
},
29+
{
30+
tableName: 'registeruser',
31+
underscored: false,
32+
freezeTableName: true,
33+
omitNull: false,
34+
timestamps: false,
35+
paranoid: false,
36+
},
37+
);
38+
39+
return RegisterUser;
40+
};
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/* indent size: 4 */
2+
3+
module.exports = (app: any) => {
4+
const DataTypes = app.Sequelize;
5+
6+
const UserInfo = app.model.define(
7+
'UserInfo',
8+
{
9+
id: {
10+
type: DataTypes.INTEGER(20).UNSIGNED,
11+
allowNull: false,
12+
primaryKey: true,
13+
autoIncrement: true,
14+
},
15+
user_name: {
16+
type: DataTypes.STRING(32),
17+
allowNull: false,
18+
},
19+
user_id: {
20+
type: DataTypes.INTEGER(20),
21+
allowNull: false,
22+
},
23+
department: {
24+
type: DataTypes.STRING(32),
25+
allowNull: false,
26+
defaultValue: '',
27+
},
28+
employee_type: {
29+
type: DataTypes.STRING(32),
30+
defaultValue: null,
31+
},
32+
roles: {
33+
type: DataTypes.STRING(32),
34+
defaultValue: null,
35+
},
36+
probation_start: {
37+
type: DataTypes.DATE,
38+
defaultValue: null,
39+
},
40+
probation_end: {
41+
type: DataTypes.DATE,
42+
defaultValue: null,
43+
},
44+
probation_duration: {
45+
type: DataTypes.INTEGER(11).UNSIGNED,
46+
defaultValue: null,
47+
},
48+
protocol_start: {
49+
type: DataTypes.DATE,
50+
defaultValue: null,
51+
},
52+
protocol_end: {
53+
type: DataTypes.DATE,
54+
defaultValue: null,
55+
},
56+
address: {
57+
type: DataTypes.STRING(32),
58+
defaultValue: null,
59+
},
60+
status: {
61+
type: DataTypes.STRING(32),
62+
defaultValue: null,
63+
},
64+
},
65+
{
66+
tableName: 'userinfo',
67+
underscored: false,
68+
freezeTableName: true,
69+
omitNull: false,
70+
timestamps: false,
71+
paranoid: false,
72+
},
73+
);
74+
75+
return UserInfo;
76+
};

packages/toolkits/pro/template/server/eggJs/app/router.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,9 @@ export default (app: Application) => {
1111

1212
router.post('/v1/employee/getEmployee', controller.employee.getEmployee);
1313

14+
router.post('/v1/user/register', controller.user.registerUser);
15+
16+
router.get('/v1/user/userInfo/:id', controller.user.getUserInfo);
17+
18+
router.post('/v1/user/login', controller.user.login);
1419
};
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { Service } from 'egg';
2+
3+
export default class User extends Service {
4+
public async getUserInfoById(user_id: string): Promise<any> {
5+
return this.ctx.model.UserInfo.findOne({ where: { user_id }, raw: true });
6+
}
7+
8+
public async getUserByName(user_name: string): Promise<any> {
9+
return this.ctx.model.RegisterUser.findOne({ where: { user_name } });
10+
}
11+
12+
public async createUser(params: { user_name: string; password: string }, options?): Promise<any> {
13+
return this.ctx.model.RegisterUser.create(params, options);
14+
}
15+
16+
public async createUserInfo(info, options?): Promise<any> {
17+
return this.ctx.model.UserInfo.create(info, options);
18+
}
19+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import * as bcrypt from 'bcrypt';
2+
3+
export default class BcryptUtils {
4+
private static saltRounds = 10;
5+
public static genHash(password: string): string {
6+
return bcrypt.hashSync(password, this.saltRounds);
7+
}
8+
public static compare(password: string, encrypted: string): boolean {
9+
return bcrypt.compareSync(password, encrypted);
10+
}
11+
}

packages/toolkits/pro/template/server/eggJs/config/config.default.ts

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,26 @@ export default (appInfo: EggAppInfo) => {
1717
username: 'root',
1818
password: '123456',
1919
define: {
20-
timestamps: true,
21-
freezeTableName: true,
22-
underscored: false,
23-
createdAt: 'created_at',
24-
updatedAt: 'updated_at',
20+
timestamps: true,
21+
freezeTableName: true,
22+
underscored: false,
23+
createdAt: 'created_at',
24+
updatedAt: 'updated_at',
2525
},
2626
timezone: '+08:00',
27-
database: 'tiny_server_test'
27+
database: 'tiny_pro_server',
2828
};
2929

30+
config.jwt = {
31+
enable: true,
32+
ignore: /user\/(login|register)/,
33+
secret: 'tiny_pro_server',
34+
sign: {
35+
expiresIn: 60 * 60 * 24,
36+
},
37+
};
3038
// the return config will combines to EggAppConfig
3139
return {
32-
...config
40+
...config,
3341
};
3442
};

packages/toolkits/pro/template/server/eggJs/config/plugin.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,14 @@ const plugin: EggPlugin = {
55
enable: true,
66
package: 'egg-sequelize',
77
},
8+
validate: {
9+
enable: true,
10+
package: 'egg-validate',
11+
},
12+
jwt: {
13+
enable: true,
14+
package: 'egg-jwt',
15+
},
816
};
917

1018
export default plugin;

packages/toolkits/pro/template/server/eggJs/package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,12 @@
2121
"clean": "ets clean"
2222
},
2323
"dependencies": {
24+
"bcrypt": "^5.1.0",
2425
"egg": "^2.6.1",
26+
"egg-jwt": "^3.1.7",
2527
"egg-scripts": "^2.6.0",
2628
"egg-sequelize": "^5.2.2",
29+
"egg-validate": "^2.0.2",
2730
"mysql2": "^2.1.0"
2831
},
2932
"devDependencies": {

packages/toolkits/pro/template/server/eggJs/typings/app/controller/index.d.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,14 @@
33
/* eslint-disable */
44

55
import 'egg';
6+
import ExportCsrf from '../../../app/controller/csrf';
67
import ExportEmployee from '../../../app/controller/employee';
8+
import ExportUser from '../../../app/controller/user';
79

810
declare module 'egg' {
911
interface IController {
12+
csrf: ExportCsrf;
1013
employee: ExportEmployee;
14+
user: ExportUser;
1115
}
1216
}

0 commit comments

Comments
 (0)