Files
adastra_api/src/database/models/mysql/User.js
T
2025-08-19 05:13:24 +02:00

161 lines
4.4 KiB
JavaScript

const { DataTypes, Model } = require("sequelize");
var crypto = require('crypto');
var jwt = require('jsonwebtoken'),
config = require('../../../config')
const sequelize = require("../../config/sequelize");
class User extends Model { }
const UserModel = () => {
User.init(
{
id: {
type: DataTypes.STRING(24),
allowNull: false,
primaryKey: true
},
email: {
type: DataTypes.STRING(255),
allowNull: false,
unique: "email"
},
username: {
type: DataTypes.STRING(255),
allowNull: false,
unique: "username"
},
firstname: {
type: DataTypes.STRING(255),
allowNull: true
},
lastname: {
type: DataTypes.STRING(255),
allowNull: true
},
phone: {
type: DataTypes.STRING(20),
allowNull: true
},
image: {
type: DataTypes.STRING(128),
allowNull: true
},
role: {
type: DataTypes.STRING(20),
allowNull: true
},
salt: {
type: DataTypes.STRING(255),
allowNull: false
},
hash: {
type: DataTypes.TEXT,
allowNull: false
}
},
{
sequelize,
tableName: 'user',
timestamps: true,
indexes: [
{
name: "PRIMARY",
unique: true,
using: "BTREE",
fields: [
{ name: "id" },
]
},
{
name: "email",
unique: true,
using: "BTREE",
fields: [
{ name: "email" },
]
},
{
name: "username",
unique: true,
using: "BTREE",
fields: [
{ name: "username" },
]
},
]
}
);
User.beforeCreate((user) => {
if (typeof user.username === 'undefined') {
user.username = `${user.firstname}_${user.lastname}`;
}
user.setPassword(user.password);
user.role = 'User';
});
User.prototype.validPassword = function (password) {
let hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
return this.hash === hash;
};
User.prototype.setPassword = function (password) {
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex');
};
User.prototype.generateJWT = function () {
var today = new Date();
var exp = new Date(today.getTime() + (config.session_lifetime * 1000));
return jwt.sign({
id: this.id,
username: this.username,
exp: parseInt(exp.getTime() / 1000)
}, config.secret, { algorithm: 'HS256' });
};
User.prototype.toAuthJSON = function () {
return {
id: this.id,
email: this.email,
username: this.username,
firstname: this.firstname,
lastname: this.lastname,
phone: this.phone,
image: this.image || '/assets/images/avatars/default.jpg',
role: this.role,
token: this.generateJWT()
};
};
User.prototype.toJSONFor = function () {
return {
id: this.id,
email: this.email,
username: this.username,
firstname: this.firstname,
lastname: this.lastname,
phone: this.phone,
image: this.image,
role: this.role
};
};
User.prototype.toProfileJSONFor = function () {
return {
email: this.email,
username: this.username,
firstname: this.firstname,
lastname: this.lastname,
phone: this.phone,
image: this.image || '/assets/images/avatars/default.jpg'
};
};
return User;
};
module.exports = UserModel;