-
Notifications
You must be signed in to change notification settings - Fork 0
/
User.js
53 lines (49 loc) · 1.13 KB
/
User.js
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
const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
// Schema
const User = new mongoose.Schema({
name: {
type: String,
required: true
},
surname: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
role: {
type: String,
enum: ['student', 'teacher'],
required: true,
},
place: {
type: String,
enum: ['on-campus', 'home-office'],
required: false
},
status: {
type: String,
enum: ['available', 'busy'],
required: false
}
})
// Middleware
User.pre('save', async function () {
// Encrypt password before saving to DB
const salt = await bcrypt.genSalt()
this.password = await bcrypt.hash(this.password, salt)
})
// Instance methods
User.methods.validPassword = async (password, userPass) => {
// Validate password from DB against given password
return await bcrypt.compare(password, userPass)
}
module.exports = mongoose.model('User', User)