Skip to content

Commit 98fbec5

Browse files
committed
fix: hook users
1 parent d7f06c7 commit 98fbec5

File tree

1 file changed

+20
-23
lines changed

1 file changed

+20
-23
lines changed

src/models/user.ts

+20-23
Original file line numberDiff line numberDiff line change
@@ -29,18 +29,6 @@ export interface LoginAttributes {
2929
password: string
3030
}
3131

32-
function setUserPassword(instance: UserInstance) {
33-
const { newPassword, confirmNewPassword } = instance
34-
const fdPassword = { newPassword, confirmNewPassword }
35-
const validPassword = schemaUser.createPassword.validateSyncAt(
36-
'confirmNewPassword',
37-
fdPassword
38-
)
39-
const saltRounds = 10
40-
const hash = bcrypt.hashSync(validPassword, saltRounds)
41-
instance.setDataValue('password', hash)
42-
}
43-
4432
interface UserCreationAttributes extends Optional<UserAttributes, 'id'> {}
4533

4634
interface UserInstance
@@ -61,17 +49,6 @@ const User = db.sequelize.define<UserInstance>(
6149
},
6250
},
6351
{
64-
hooks: {
65-
beforeCreate(instance: UserInstance) {
66-
setUserPassword(instance)
67-
},
68-
beforeUpdate(instance: UserInstance) {
69-
const { newPassword, confirmNewPassword } = instance
70-
if (newPassword || confirmNewPassword) {
71-
setUserPassword(instance)
72-
}
73-
},
74-
},
7552
defaultScope: {
7653
attributes: {
7754
exclude: ['password', 'tokenVerify'],
@@ -83,6 +60,26 @@ const User = db.sequelize.define<UserInstance>(
8360
}
8461
)
8562

63+
function setUserPassword(instance: UserInstance) {
64+
const { newPassword, confirmNewPassword } = instance
65+
const fdPassword = { newPassword, confirmNewPassword }
66+
const validPassword = schemaUser.createPassword.validateSyncAt(
67+
'confirmNewPassword',
68+
fdPassword
69+
)
70+
const saltRounds = 10
71+
const hash = bcrypt.hashSync(validPassword, saltRounds)
72+
instance.setDataValue('password', hash)
73+
}
74+
75+
User.addHook('beforeCreate', setUserPassword)
76+
User.addHook('beforeUpdate', (instance: UserInstance) => {
77+
const { newPassword, confirmNewPassword } = instance
78+
if (newPassword || confirmNewPassword) {
79+
setUserPassword(instance)
80+
}
81+
})
82+
8683
// Compare password
8784
User.prototype.comparePassword = function (candidatePassword: string) {
8885
return new Promise((resolve, reject) => {

0 commit comments

Comments
 (0)