Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 103 additions & 0 deletions packages/toolkits/pro/template/server/eggJs/app/controller/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { Controller } from 'egg';
import BcryptUtils from '../utils/bcrypt-utils';

export default class UserController extends Controller {
// 注册用户
public async registerUser() {
const { ctx, app } = this;
const payload = ctx.request.body || {};
const transaction = await ctx.model.transaction();
try {
this.logger.info('[ controller | user ] registerUser : 进入registerUser方法');
// 校验参数
const registerUserRule = {
username: { type: 'email' },
password: {
type: 'string',
format: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/,
},
};
const err = app.validator.validate(registerUserRule, payload);
if (err?.length) {
ctx.helper.commonJson(ctx, {}, 500, 'InvalidParameter');
return;
}
const { username, password } = payload;
// 判断用户是否已经存在
const user = await ctx.service.user.getUserByName(username);
if (user) {
ctx.helper.commonJson(ctx, {}, 500, 'UserAlreadyExist');
return;
}
const hash = BcryptUtils.genHash(password);
// 创建用户
const { id } = await ctx.service.user.createUser({ username, password: hash }, { transaction });
const userInfo = await ctx.service.user.createUserInfo({ username, id }, { transaction });
await transaction.commit();
ctx.helper.commonJson(ctx, userInfo, 200);
} catch (error) {
await transaction.rollback();
ctx.helper.commonJson(ctx, {}, 500, 'InterError');
}
}
// 获取用户信息
public async getUserInfo() {
const { ctx } = this;
const { id } = ctx.params;

try {
this.logger.info('[ controller | user ] getUserInfo : 进入getUserInfo方法');
const userInfo = await ctx.service.user.getUserInfoById(id);
if (!userInfo) {
ctx.helper.commonJson(ctx, {}, 500, 'UserNotFound');
return;
}
ctx.helper.commonJson(ctx, userInfo, 200);
} catch (error) {
ctx.helper.commonJson(ctx, {}, 500, 'InterError');
}
}

// 登录
public async login() {
const { ctx, app } = this;
const payload = ctx.request.body || {};
try {
this.logger.info('[ controller | user ] login : 进入login方法');
// 校验参数格式
const err = app.validator.validate(
{
username: { type: 'email' },
password: { type: 'string' },
},
payload,
);
if (err?.length) {
ctx.helper.commonJson(ctx, {}, 500, 'InvalidParameter');
return;
}

// 用户是否存在
const user = await ctx.service.user.getUserByName(payload.username);
if (!user) {
ctx.helper.commonJson(ctx, {}, 500, 'UserNotFound');
return;
}

// 密码是否正确
const match = BcryptUtils.compare(payload.password, user.password);
if (!match) {
ctx.helper.commonJson(ctx, {}, 500, 'ErrorPassword');
return;
}

// 生成Token
const { secret, sign } = this.app.config.jwt;
const userInfo = await ctx.service.user.getUserInfoById(user.id);
const token = this.app.jwt.sign(userInfo.dataValues, secret, sign);
ctx.helper.commonJson(ctx, { token }, 200);
} catch (error) {
ctx.helper.commonJson(ctx, {}, 500, 'InterError');
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/* indent size: 4 */

module.exports = (app: any) => {
const DataTypes = app.Sequelize;

const RegisterUser = app.model.define(
'RegisterUser',
{
id: {
type: DataTypes.INTEGER(20).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
username: {
type: DataTypes.STRING(32),
allowNull: false,
},
password: {
type: DataTypes.STRING(60),
allowNull: false,
},
loginType: {
type: DataTypes.ENUM('account', 'email'),
allowNull: false,
defaultValue: 'email',
},
},
{
tableName: 'registeruser',
underscored: false,
freezeTableName: true,
omitNull: false,
timestamps: false,
paranoid: false,
},
);

return RegisterUser;
};
71 changes: 71 additions & 0 deletions packages/toolkits/pro/template/server/eggJs/app/model/userInfo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/* indent size: 4 */

module.exports = (app: any) => {
const DataTypes = app.Sequelize;

const UserInfo = app.model.define(
'UserInfo',
{
id: {
type: DataTypes.INTEGER(20).UNSIGNED,
allowNull: false,
primaryKey: true,
},
username: {
type: DataTypes.STRING(32),
allowNull: false,
},
department: {
type: DataTypes.STRING(32),
allowNull: false,
defaultValue: '',
},
employeeType: {
type: DataTypes.STRING(32),
defaultValue: null,
},
roles: {
type: DataTypes.STRING(32),
defaultValue: null,
},
probationStart: {
type: DataTypes.DATE,
defaultValue: null,
},
probationEnd: {
type: DataTypes.DATE,
defaultValue: null,
},
probationDuration: {
type: DataTypes.INTEGER(11).UNSIGNED,
defaultValue: null,
},
protocolStart: {
type: DataTypes.DATE,
defaultValue: null,
},
protocolEnd: {
type: DataTypes.DATE,
defaultValue: null,
},
address: {
type: DataTypes.STRING(32),
defaultValue: null,
},
status: {
type: DataTypes.STRING(32),
defaultValue: null,
},
},
{
tableName: 'userinfo',
underscored: false,
freezeTableName: true,
omitNull: false,
timestamps: false,
paranoid: false,
},
);

return UserInfo;
};
5 changes: 5 additions & 0 deletions packages/toolkits/pro/template/server/eggJs/app/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,9 @@ export default (app: Application) => {

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

router.post('/v1/user/register', controller.user.registerUser);

router.get('/v1/user/userInfo/:id', controller.user.getUserInfo);

router.post('/v1/user/login', controller.user.login);
};
19 changes: 19 additions & 0 deletions packages/toolkits/pro/template/server/eggJs/app/service/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Service } from 'egg';

export default class User extends Service {
public async getUserInfoById(id: string): Promise<any> {
return this.ctx.model.UserInfo.findOne({ where: { id } });
}

public async getUserByName(username: string): Promise<any> {
return this.ctx.model.RegisterUser.findOne({ where: { username } });
}

public async createUser(params: { username: string; password: string }, options?): Promise<any> {
return this.ctx.model.RegisterUser.create(params, options);
}

public async createUserInfo(info, options?): Promise<any> {
return this.ctx.model.UserInfo.create(info, options);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import * as bcrypt from 'bcrypt';

export default class BcryptUtils {
private static saltRounds = 10;
public static genHash(password: string): string {
return bcrypt.hashSync(password, this.saltRounds);
}
public static compare(password: string, encrypted: string): boolean {
return bcrypt.compareSync(password, encrypted);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,26 @@ export default (appInfo: EggAppInfo) => {
username: 'root',
password: '123456',
define: {
timestamps: true,
freezeTableName: true,
underscored: false,
createdAt: 'created_at',
updatedAt: 'updated_at',
timestamps: true,
freezeTableName: true,
underscored: false,
createdAt: 'created_at',
updatedAt: 'updated_at',
},
timezone: '+08:00',
database: 'tiny_server_test'
database: 'tiny_server_test',
};

config.jwt = {
enable: true,
ignore: /user\/(login|register)/,
secret: 'open_tiny_server',
sign: {
expiresIn: 60 * 60 * 24,
},
};
// the return config will combines to EggAppConfig
return {
...config
...config,
};
};
8 changes: 8 additions & 0 deletions packages/toolkits/pro/template/server/eggJs/config/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ const plugin: EggPlugin = {
enable: true,
package: 'egg-sequelize',
},
validate: {
enable: true,
package: 'egg-validate',
},
jwt: {
enable: true,
package: 'egg-jwt',
},
};

export default plugin;
3 changes: 3 additions & 0 deletions packages/toolkits/pro/template/server/eggJs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,12 @@
"clean": "ets clean"
},
"dependencies": {
"bcrypt": "^5.1.0",
"egg": "^2.6.1",
"egg-jwt": "^3.1.7",
"egg-scripts": "^2.6.0",
"egg-sequelize": "^5.2.2",
"egg-validate": "^2.0.2",
"mysql2": "^2.1.0"
},
"devDependencies": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@

import 'egg';
import ExportEmployee from '../../../app/controller/employee';
import ExportUser from '../../../app/controller/user';

declare module 'egg' {
interface IController {
employee: ExportEmployee;
user: ExportUser;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@

import 'egg';
import ExportEmployee from '../../../app/model/employee';
import ExportRegisterUser from '../../../app/model/registerUser';
import ExportUserInfo from '../../../app/model/userInfo';

declare module 'egg' {
interface IModel {
Employee: ReturnType<typeof ExportEmployee>;
RegisterUser: ReturnType<typeof ExportRegisterUser>;
UserInfo: ReturnType<typeof ExportUserInfo>;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ import 'egg';
type AnyClass = new (...args: any[]) => any;
type AnyFunc<T = any> = (...args: any[]) => T;
type CanExportFunc = AnyFunc<Promise<any>> | AnyFunc<IterableIterator<any>>;
type AutoInstanceType<T, U = T extends CanExportFunc ? T : T extends AnyFunc ? ReturnType<T> : T> = U extends AnyClass ? InstanceType<U> : U;
type AutoInstanceType<T, U = T extends CanExportFunc ? T : T extends AnyFunc ? ReturnType<T> : T> = U extends AnyClass
? InstanceType<U>
: U;
import ExportEmployee from '../../../app/service/employee';
import ExportUser from '../../../app/service/user';

declare module 'egg' {
interface IService {
employee: AutoInstanceType<typeof ExportEmployee>;
user: AutoInstanceType<typeof ExportUser>;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import 'egg-static';
import 'egg-jsonp';
import 'egg-view';
import 'egg-sequelize';
import 'egg-validate';
import 'egg-jwt';
import { EggPluginItem } from 'egg';
declare module 'egg' {
interface EggPlugin {
Expand All @@ -32,5 +34,7 @@ declare module 'egg' {
jsonp?: EggPluginItem;
view?: EggPluginItem;
sequelize?: EggPluginItem;
validate?: EggPluginItem;
jwt?: EggPluginItem;
}
}
}