bullpen/backend/models/auth.model.js

62 lines
1.6 KiB
JavaScript

const { Model } = require('sequelize');
const bcrypt = require("bcryptjs");
module.exports = (sequelize, DataTypes) => {
class Auth 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) {
Auth.hasOne(models.User, {
foreignKey: 'authId',
as: 'user'
});
Auth.hasMany(models.RefreshToken, {
foreignKey: 'authId',
as: 'tokens'
});
}
}
Auth.init({
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {isEmail: true},
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
}, {
sequelize,
modelName: 'Auth',
tableName: 'Authentications',
timestamps: true,
hooks: {
beforeCreate: async (auth) => {
const salt = await bcrypt.genSalt(10);
auth.password = await bcrypt.hash(auth.password, salt);
}
}
}, {
defaultScope: {
attributes: { exclude: ['password'] },
},
scopes: {
withSecretColumns: {
attributes: { include: ['password'] },
},
},
});
Auth.prototype.validPassword = function (password) {
return bcrypt.compareSync(password, this.password);
};
return Auth;
}