user.model.js 1.21 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
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
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,
})

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)