CentralBackend/models/User.js
2025-09-07 12:44:01 +02:00

65 lines
1.6 KiB
JavaScript

const db = require('../database/database');
const argon2 = require('argon2');
const jwt = require('jsonwebtoken');
class User {
constructor(id, email, password, userType, createdAt, updatedAt, role) {
this.id = id;
this.email = email;
this.password = password;
this.userType = userType; // 'personal' or 'company'
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.role = role; // Add role property
}
// Hash password
static async hashPassword(password) {
console.log('🔐 Hashing password with Argon2...');
return await argon2.hash(password, {
type: argon2.argon2i,
memoryCost: 2 ** 16, // 64 MB
timeCost: 3,
parallelism: 1,
});
}
// Compare password
async comparePassword(password) {
console.log('🔍 Comparing password with Argon2...');
return await argon2.verify(this.password, password);
}
// Generate JWT token
generateToken() {
console.log('🎫 Generating JWT token for user:', this.id);
return jwt.sign(
{
userId: this.id,
email: this.email,
userType: this.userType
},
process.env.JWT_SECRET,
{ expiresIn: process.env.JWT_EXPIRES_IN }
);
}
// Verify JWT token
static verifyToken(token) {
try {
return jwt.verify(token, process.env.JWT_SECRET);
} catch (error) {
console.error('💥 Token verification failed:', error.message);
return null;
}
}
// Get user basic info (without password)
getPublicData() {
const { password, ...publicData } = this;
return publicData;
}
}
module.exports = User;