user.model.js 1.32 KB
Newer Older
Yoon, Daeki's avatar
Yoon, Daeki committed
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
import mongoose from 'mongoose'
import bcrypt from 'bcrypt'

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    trim: true,
    required: 'Name is required'
  },
  email: {
    type: String,
    trim: true,
    unique: 'Email is already exists',
    match: [/.+\@.+\..+/, 'Please fill a valid email address'],
    required: 'Email is required'
  },
  created: {
    type: Date,
    default: Date.now,
  },
  updated: Date,
  hashedPassword: {
    type: String,
    required: 'Password is required'
  },
  salt: String,
Yoon, Daeki's avatar
Yoon, Daeki committed
27
28
29
30
  photo: {
    data: Buffer,
    contentType: String,
  },
Yoon, Daeki's avatar
quiz    
Yoon, Daeki committed
31
32
33
34
  instructor: {
    type: Boolean,
    default: false,
  },
Yoon, Daeki's avatar
Yoon, Daeki committed
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
})

UserSchema.virtual('password')
.set(function (password) {
  this._password = password
  this.salt = bcrypt.genSaltSync()
  this.hashedPassword = bcrypt.hashSync(password, this.salt)
})
.get(() => {
  return this._password
})

UserSchema.methods.authenticate = function (plainText) {
  return bcrypt.compareSync(plainText, this.hashedPassword)
}

UserSchema.path('hashedPassword').validate(function (value) {
  if (this._password && this._password.length < 6) {
    this.invalidate('password', 'Password must be at least 6 characters.')
  }
  if (this.isNew && !this._password) {
    this.invalidate('password', 'Password is required')
  }
})

export default mongoose.model('User', UserSchema)