72 lines
1.6 KiB
JavaScript
72 lines
1.6 KiB
JavaScript
const { Model } = require('sequelize');
|
|
const bcrypt = require("bcryptjs");
|
|
|
|
module.exports = (sequelize, DataTypes) => {
|
|
class User extends Model {
|
|
/**
|
|
* Helper method for defining associations.
|
|
* This method is not a part of Sequelize lifecycle.
|
|
* The `models/index` file will call this method automatically.
|
|
*/
|
|
static associate(models) {
|
|
User.belongsToMany(models.Role, {
|
|
through: "UserRoles",
|
|
foreignKey: 'userId',
|
|
as: 'roles',
|
|
});
|
|
User.hasOne(models.RefreshToken, {
|
|
foreignKey: 'userId',
|
|
targetKey: 'id'
|
|
});
|
|
}
|
|
}
|
|
User.init({
|
|
firstName: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false
|
|
},
|
|
lastName: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false
|
|
},
|
|
dateOfBirth: {
|
|
type: DataTypes.DATE,
|
|
allowNull: false
|
|
},
|
|
email: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false,
|
|
unique: true
|
|
},
|
|
password: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false
|
|
}
|
|
}, {
|
|
sequelize,
|
|
modelName: 'User',
|
|
tableName: "Users",
|
|
hooks: {
|
|
beforeCreate: async (user) => {
|
|
const salt = await bcrypt.genSalt(10);
|
|
user.password = await bcrypt.hash(user.password, salt);
|
|
}
|
|
}
|
|
}, {
|
|
defaultScope: {
|
|
attributes: { exclude: ['password'] },
|
|
},
|
|
scopes: {
|
|
withSecretColumns: {
|
|
attributes: { include: ['password'] },
|
|
},
|
|
},
|
|
});
|
|
|
|
User.prototype.validPassword = function (password) {
|
|
return bcrypt.compareSync(password, this.password);
|
|
};
|
|
|
|
return User;
|
|
};
|