Files
drone-detector/server/models/User.js
2025-09-12 12:16:24 +02:00

139 lines
3.1 KiB
JavaScript

const { DataTypes, Op } = require('sequelize');
module.exports = (sequelize) => {
const User = sequelize.define('User', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
len: [3, 50]
}
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
password_hash: {
type: DataTypes.STRING,
allowNull: false
},
first_name: {
type: DataTypes.STRING,
allowNull: true
},
last_name: {
type: DataTypes.STRING,
allowNull: true
},
phone_number: {
type: DataTypes.STRING,
allowNull: true,
comment: 'Phone number for SMS alerts (include country code)'
},
role: {
type: DataTypes.ENUM('admin', 'operator', 'viewer'),
defaultValue: 'viewer',
comment: 'User role for permission management'
},
is_active: {
type: DataTypes.BOOLEAN,
defaultValue: true
},
sms_alerts_enabled: {
type: DataTypes.BOOLEAN,
defaultValue: false,
comment: 'Whether user wants to receive SMS alerts'
},
email_alerts_enabled: {
type: DataTypes.BOOLEAN,
defaultValue: true,
comment: 'Whether user wants to receive email alerts'
},
last_login: {
type: DataTypes.DATE,
allowNull: true
},
timezone: {
type: DataTypes.STRING,
defaultValue: 'UTC',
comment: 'User timezone for alert scheduling'
},
tenant_id: {
type: DataTypes.UUID,
allowNull: true,
references: {
model: 'tenants',
key: 'id'
},
comment: 'Tenant this user belongs to (null for default tenant)'
},
external_provider: {
type: DataTypes.ENUM('local', 'saml', 'oauth', 'ldap', 'custom_sso'),
defaultValue: 'local',
comment: 'Authentication provider used for this user'
},
external_id: {
type: DataTypes.STRING,
allowNull: true,
comment: 'User ID from external authentication provider'
},
created_at: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
},
updated_at: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
}
}, {
tableName: 'users',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
indexes: [
{
fields: ['email']
},
{
fields: ['username']
},
{
fields: ['phone_number']
},
{
fields: ['tenant_id']
},
{
fields: ['external_provider']
},
{
fields: ['external_id', 'tenant_id'],
unique: true,
name: 'users_external_id_tenant_unique',
where: { external_id: { [Op.ne]: null } }
}
]
});
// Associations
User.associate = (models) => {
// User belongs to a tenant
User.belongsTo(models.Tenant, {
foreignKey: 'tenant_id',
as: 'tenant'
});
};
return User;
};