-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUser.js
More file actions
60 lines (55 loc) · 1.63 KB
/
Copy pathUser.js
File metadata and controls
60 lines (55 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// models/User.js
// Mongoose schema for platform users (both customers and support agents/admins).
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const userSchema = new mongoose.Schema(
{
name: {
type: String,
required: [true, 'Name is required'],
trim: true,
},
email: {
type: String,
required: [true, 'Email is required'],
unique: true,
lowercase: true,
trim: true,
match: [/^\S+@\S+\.\S+$/, 'Please provide a valid email address'],
},
password: {
type: String,
required: [true, 'Password is required'],
minlength: 6,
select: false, // never return password by default in queries
},
// role controls dashboard access: 'customer' can raise tickets & chat,
// 'agent' can manage tickets, 'admin' has full access including analytics
role: {
type: String,
enum: ['customer', 'agent', 'admin'],
default: 'customer',
},
avatar: {
type: String,
default: '',
},
isActive: {
type: Boolean,
default: true,
},
},
{ timestamps: true }
);
// Hash the password before saving, only if it has been modified
userSchema.pre('save', async function (next) {
if (!this.isModified('password')) return next();
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
next();
});
// Instance method to compare plaintext password with hashed password
userSchema.methods.matchPassword = async function (enteredPassword) {
return bcrypt.compare(enteredPassword, this.password);
};
module.exports = mongoose.model('User', userSchema);