Files
gancio/server/api/models/user.js

54 lines
1.1 KiB
JavaScript
Raw Normal View History

2020-06-27 02:10:10 +02:00
2019-07-07 23:00:31 +02:00
const bcrypt = require('bcryptjs')
2020-06-27 02:10:10 +02:00
const { Model, DataTypes } = require('sequelize')
2021-09-27 11:14:11 +02:00
const sequelize = require('./index').sequelize
2019-07-29 14:10:18 +02:00
2020-06-27 02:10:10 +02:00
class User extends Model {}
2019-04-03 00:25:12 +02:00
2020-06-27 02:10:10 +02:00
User.init({
settings: {
type: DataTypes.JSON,
defaultValue: []
},
email: {
type: DataTypes.STRING,
unique: { msg: 'error.email_taken' },
validate: {
notEmpty: true
},
index: true,
allowNull: false
},
description: DataTypes.TEXT,
password: DataTypes.STRING,
recover_code: DataTypes.STRING,
is_admin: DataTypes.BOOLEAN,
is_active: DataTypes.BOOLEAN
}, {
sequelize,
modelName: 'user',
scopes: {
withoutPassword: {
attributes: { exclude: ['password', 'recover_code'] }
},
withRecover: {
attributes: { exclude: ['password'] }
2020-06-27 02:10:10 +02:00
}
2019-04-03 00:25:12 +02:00
}
2020-06-27 02:10:10 +02:00
})
2019-06-07 17:02:33 +02:00
2020-06-27 02:10:10 +02:00
User.prototype.comparePassword = async function (pwd) {
if (!this.password) { return false }
2022-06-11 10:34:55 +02:00
return bcrypt.compare(pwd, this.password)
2019-09-11 19:12:24 +02:00
}
2020-06-27 02:10:10 +02:00
2022-06-11 10:34:55 +02:00
User.beforeSave(async (user, _options) => {
2020-06-27 02:10:10 +02:00
if (user.changed('password')) {
const salt = await bcrypt.genSalt(10)
const hash = await bcrypt.hash(user.password, salt)
user.password = hash
}
})
module.exports = User