all files / backend/models/ user.js

90% Statements 36/40
30% Branches 3/10
90% Functions 9/10
90% Lines 36/40
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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149                                                                                                                                                                                                                                 
'use strict'
 
let _ = require('lodash')
let mongoose = require('mongoose')
let Bluebird = require('bluebird')
let crypto = require('crypto')
let Jwt = require('app/services/jwt')
let Errors = require('app/errors')
let Schema = mongoose.Schema
 
/**
 * User Schema
 */
var UserSchema = new Schema({
  firstName: {
    type: String
  },
  lastName: String,
  role: {
    type: String,
    default: 'user'
  },
  email: {
    required: true,
    unique: true,
    type: String,
    set: val => val.toLowerCase()
  },
  password: {
    type: String,
    required: true,
    select: false
  },
  salt: {
    type: String,
    default: function () {
      var now = new Date().getTime()
      return crypto
        .createHash('md5')
        .update('MEAN Stack' + now)
        .digest('hex')
    }
  },
  createdOn: {
    type: Date,
    default: Date.now
  },
  updatedOn: {
    type: Date,
    default: Date.now
  }
})
 
UserSchema.virtual('fullname').get(function () {
  let firstName = this.firstName || ''
  let lastName = this.lastName || ''
  return _.trim(`${firstName} ${lastName}`)
})
 
UserSchema.virtual('obfuscatedEmail').get(function () {
  let e = this.email
  let regexp = /(?!^.)(.*)(?=[\w]@)/i
  return e.replace(regexp, '...')
})
 
UserSchema.virtual('response').get(function () {
  return {
    _id: this._id,
    firstName: this.firstName,
    lastName: this.lastName,
    email: this.email,
    token: this.token
  }
})
 
UserSchema.virtual('token').get(function () {
  let payload = {
    _id: this._id,
    role: this.role
  }
 
  return Jwt.signToken(payload)
})
 
UserSchema.pre('save', function (next) {
  // Update the timestamp
  this.updatedOn = Date.now()
 
  return next()
})
 
/**
 * Check if password is valid
 *
 * @param {String} password
 *
 * @return {Boolean}
 */
UserSchema.methods.validatePassword = function validatePassword (password) {
  password = password || ''
 
  let pwHash = crypto
    .createHash('sha1')
    .update(password + this.salt)
    .digest('hex')
 
  return this.password === pwHash
}
 
/**
 * Set the password for this user
 *
 * @param {String} password
 */
UserSchema.methods.setPassword = function setPassword (password) {
  this.password = crypto
    .createHash('sha1')
    .update(password + this.salt)
    .digest('hex')
 
  return this
}
 
/**
 * Find a user by their email
 *
 * @param {String} email
 *
 * @return {Promise}
 */
UserSchema.statics.findByEmail = function findByEmail (email) {
  // We need to have an email to search upon
  Iif (_.isEmpty(email)) {
    return Bluebird.reject(new Errors.BadData('Missing email'))
  }
 
  return this
    .findOne({ 'email': email.toLowerCase() })
    .select('+password')
    .then(function (user) {
      // If null, we didn't find a match
      return _.isNull(user)
        ? Bluebird.reject(new Errors.NotFound(`No user found with ${email}`))
        : user
    })
}
 
module.exports = mongoose.model('User', UserSchema, 'users')