harris_paint / src /models /Admin.js
aliroohan179's picture
Upload 58 files
10821c7 verified
Raw
History Blame Contribute Delete
1.93 kB
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const adminSchema = new mongoose.Schema(
{
email: { type: String, required: true, unique: true, lowercase: true, trim: true },
passwordHash: { type: String, required: true },
role: {
type: String,
required: true,
enum: ['super_admin', 'regional_manager', 'marketing_manager', 'consultant_admin', 'support_agent'],
},
profile: {
firstName: { type: String, required: true },
lastName: { type: String, required: true },
phone: { type: String },
avatarUrl: { type: String },
},
assignedMarkets: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Market' }],
// Auth
refreshToken: { type: String },
mfaEnabled: { type: Boolean, default: false },
mfaSecret: { type: String },
lastLogin: { type: Date },
passwordChangedAt: { type: Date },
accountStatus: {
type: String,
enum: ['active', 'deactivated'],
default: 'active',
},
// Security
loginAudit: [
{
timestamp: { type: Date, default: Date.now },
ipAddress: { type: String },
sessionDuration: { type: Number },
},
],
},
{ timestamps: true }
);
// Hash password before saving
adminSchema.pre('save', async function () {
if (!this.isModified('passwordHash')) return;
this.passwordHash = await bcrypt.hash(this.passwordHash, 12);
this.passwordChangedAt = new Date();
});
// Compare password method
adminSchema.methods.comparePassword = async function (candidatePassword) {
return bcrypt.compare(candidatePassword, this.passwordHash);
};
// Remove sensitive fields from JSON output
adminSchema.methods.toJSON = function () {
const obj = this.toObject();
delete obj.passwordHash;
delete obj.refreshToken;
delete obj.mfaSecret;
delete obj.loginAudit;
return obj;
};
module.exports = mongoose.model('Admin', adminSchema);