64 lines
1.7 KiB
JavaScript
64 lines
1.7 KiB
JavaScript
"use strict";
|
|
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) {
|
|
this.hasMany(models.TimeEntry, { foreignKey: "userId" });
|
|
this.hasMany(models.ActivityLog, { foreignKey: "userId" });
|
|
}
|
|
|
|
// Instance method to check password
|
|
async checkPassword(password) {
|
|
return bcrypt.compare(password, this.password);
|
|
}
|
|
}
|
|
|
|
User.init(
|
|
{
|
|
username: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false,
|
|
unique: true,
|
|
},
|
|
password: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false,
|
|
},
|
|
role: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false,
|
|
defaultValue: "user",
|
|
},
|
|
},
|
|
{
|
|
sequelize,
|
|
modelName: "User",
|
|
hooks: {
|
|
beforeCreate: async (user) => {
|
|
if (user.password) {
|
|
const bcrypt = require("bcryptjs");
|
|
const salt = await bcrypt.genSalt(10);
|
|
user.password = await bcrypt.hash(user.password, salt);
|
|
}
|
|
},
|
|
beforeUpdate: async (user) => {
|
|
if (user.password && user.changed("password")) {
|
|
console.log("Хэшируем пароль при обновлении");
|
|
const bcrypt = require("bcryptjs");
|
|
const salt = await bcrypt.genSalt(10);
|
|
user.password = await bcrypt.hash(user.password, salt);
|
|
console.log("Пароль хэширован");
|
|
}
|
|
},
|
|
},
|
|
}
|
|
);
|
|
return User;
|
|
};
|