fix: async mode recommended over sync mode

This commit is contained in:
chenos 2021-03-30 06:12:08 +08:00
parent b49199c643
commit 18825af43d
5 changed files with 30 additions and 13 deletions

6
package-lock.json generated
View File

@ -4259,6 +4259,12 @@
"@babel/types": "^7.3.0"
}
},
"@types/bcrypt": {
"version": "3.0.0",
"resolved": "https://registry.npm.taobao.org/@types/bcrypt/download/@types/bcrypt-3.0.0.tgz",
"integrity": "sha1-hRSJqQZaBny388nL5M6b7Yu6CHY=",
"dev": true
},
"@types/body-parser": {
"version": "1.19.0",
"resolved": "https://registry.npm.taobao.org/@types/body-parser/download/@types/body-parser-1.19.0.tgz",

View File

@ -17,6 +17,7 @@
},
"devDependencies": {
"@koa/router": "^9.3.1",
"@types/bcrypt": "^3.0.0",
"@types/jest": "^26.0.4",
"@types/koa": "^2.11.6",
"@types/koa-bodyparser": "^4.3.0",

View File

@ -294,7 +294,7 @@ describe('field types', () => {
const pwd = await Pwd.create({
password: '123456',
});
expect(Password.verify('123456', pwd.password)).toBeTruthy();
expect(await Password.verify('123456', pwd.password)).toBeTruthy();
});
it('formula', async () => {
const [Formula] = db.getModels(['formula_tests']);

View File

@ -296,20 +296,29 @@ export class PASSWORD extends STRING {
return DataTypes.STRING;
}
public static verify(value: string, hash: string) {
return bcrypt.compareSync(value, hash);
constructor(options: Options.StringOptions, context: FieldContext) {
super(options, context);
const Model = context.sourceTable.getModel();
Model.addHook('beforeCreate', PASSWORD.hash.bind(this));
Model.addHook('beforeUpdate', PASSWORD.hash.bind(this));
}
public getAttributeOptions() {
const { name, length, binary, ...restOptions } = this.options;
return {
name,
...restOptions,
type: this.getDataTypeInstance({ length, binary }),
set(this: Model, value: string) {
value && this.setDataValue(name, bcrypt.hashSync(value, 10));
},
public static async hash(this: PASSWORD, model) {
const { name } = this.options;
if (!model.changed(name as any)) {
return;
}
const value = model.get(name) as string;
if (value) {
const hash = await bcrypt.hash(value, 10);
model.set(name, hash);
} else {
model.set(name, null);
}
}
public static async verify(value: string, hash: string) {
return await bcrypt.compare(value, hash);
}
}

View File

@ -25,7 +25,8 @@ export async function login(ctx: actions.Context, next: actions.Next) {
if (!user) {
ctx.throw(401, 'Unauthorized');
}
if (!PASSWORD.verify(values.password, user.password)) {
const isValid = await PASSWORD.verify(values.password, user.password);
if (!isValid) {
ctx.throw(401, 'Unauthorized');
}
if (!user.token) {