Files
2025-08-10 09:15:18 +02:00

66 lines
1.9 KiB
JavaScript

'use strict';
const bcrypt = require("bcryptjs");
const {
Model
} = require('sequelize');
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) {
/* define association here */
}
}
User.init({
userId: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false},
email: {type: DataTypes.STRING, allowNull: false, unique: true},
username: {type: DataTypes.STRING, allowNull: false, unique: true},
firstname: {type: DataTypes.STRING},
lastname: {type: DataTypes.STRING},
bio: {type: DataTypes.TEXT, allowNull: true},
image: {type: DataTypes.TEXT, allowNull: true},
role: {type: DataTypes.STRING},
password: {type: DataTypes.STRING, allowNull: false}
}, {
sequelize,
timestamps: false,
modelName: 'User',
tableName: 'user',
createdAt: true,
updatedAt: true
});
User.prototype.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};
const DEFAULT_SALT_ROUNDS = 10;
User.addHook("beforeCreate", async (user) => {
const encryptedPassword = await bcrypt.hash(
user.password,
DEFAULT_SALT_ROUNDS
);
user.password = encryptedPassword;
});
User.prototype.toJSONFor = function () {
return {
userId: this.userId,
email: this.email,
username: this.username,
firstname: this.firstname,
lastname: this.lastname,
bio: this.bio,
image: this.image,
role: this.role
};
};
return User;
};