2017-02-09 01:52:37 +00:00
|
|
|
'use strict'
|
2016-10-15 03:31:15 +00:00
|
|
|
|
2017-02-09 01:52:37 +00:00
|
|
|
const Promise = require('bluebird')
|
|
|
|
const bcrypt = require('bcryptjs-then')
|
|
|
|
const _ = require('lodash')
|
2016-10-15 03:31:15 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Region schema
|
|
|
|
*
|
|
|
|
* @type {<Mongoose.Schema>}
|
|
|
|
*/
|
2016-11-21 01:09:50 +00:00
|
|
|
var userSchema = Mongoose.Schema({
|
2016-10-15 03:31:15 +00:00
|
|
|
|
2017-02-09 01:52:37 +00:00
|
|
|
email: {
|
|
|
|
type: String,
|
|
|
|
required: true,
|
|
|
|
index: true
|
|
|
|
},
|
2016-10-30 22:41:10 +00:00
|
|
|
|
2017-02-09 01:52:37 +00:00
|
|
|
provider: {
|
|
|
|
type: String,
|
|
|
|
required: true
|
|
|
|
},
|
2016-10-30 22:41:10 +00:00
|
|
|
|
2017-02-09 01:52:37 +00:00
|
|
|
providerId: {
|
|
|
|
type: String
|
|
|
|
},
|
2016-10-30 22:41:10 +00:00
|
|
|
|
2017-02-09 01:52:37 +00:00
|
|
|
password: {
|
|
|
|
type: String
|
|
|
|
},
|
2016-10-30 22:41:10 +00:00
|
|
|
|
2017-02-09 01:52:37 +00:00
|
|
|
name: {
|
|
|
|
type: String
|
|
|
|
},
|
2016-10-30 22:41:10 +00:00
|
|
|
|
2017-02-09 01:52:37 +00:00
|
|
|
rights: [{
|
|
|
|
role: String,
|
|
|
|
path: String,
|
|
|
|
exact: Boolean,
|
|
|
|
deny: Boolean
|
|
|
|
}]
|
2016-10-15 03:31:15 +00:00
|
|
|
|
2017-02-09 01:52:37 +00:00
|
|
|
}, { timestamps: {} })
|
2016-10-15 03:31:15 +00:00
|
|
|
|
2016-10-30 22:41:10 +00:00
|
|
|
userSchema.statics.processProfile = (profile) => {
|
2017-02-09 01:52:37 +00:00
|
|
|
let primaryEmail = ''
|
|
|
|
if (_.isArray(profile.emails)) {
|
|
|
|
let e = _.find(profile.emails, ['primary', true])
|
|
|
|
primaryEmail = (e) ? e.value : _.first(profile.emails).value
|
|
|
|
} else if (_.isString(profile.email) && profile.email.length > 5) {
|
|
|
|
primaryEmail = profile.email
|
|
|
|
} else {
|
|
|
|
return Promise.reject(new Error('Invalid User Email'))
|
|
|
|
}
|
2016-10-30 22:41:10 +00:00
|
|
|
|
2017-02-09 01:52:37 +00:00
|
|
|
return db.User.findOneAndUpdate({
|
|
|
|
email: primaryEmail,
|
|
|
|
provider: profile.provider
|
|
|
|
}, {
|
|
|
|
email: primaryEmail,
|
|
|
|
provider: profile.provider,
|
|
|
|
providerId: profile.id,
|
|
|
|
name: profile.displayName || _.split(primaryEmail, '@')[0]
|
|
|
|
}, {
|
|
|
|
new: true,
|
|
|
|
upsert: true
|
|
|
|
}).then((user) => {
|
|
|
|
return user || Promise.reject(new Error('User Upsert failed.'))
|
|
|
|
})
|
|
|
|
}
|
2016-10-30 22:41:10 +00:00
|
|
|
|
|
|
|
userSchema.statics.hashPassword = (rawPwd) => {
|
2017-02-09 01:52:37 +00:00
|
|
|
return bcrypt.hash(rawPwd)
|
|
|
|
}
|
2016-10-30 22:41:10 +00:00
|
|
|
|
2017-02-09 01:52:37 +00:00
|
|
|
userSchema.methods.validatePassword = function (rawPwd) {
|
|
|
|
return bcrypt.compare(rawPwd, this.password).then((isValid) => {
|
|
|
|
return (isValid) ? true : Promise.reject(new Error('Invalid Login'))
|
|
|
|
})
|
|
|
|
}
|
2016-10-30 22:41:10 +00:00
|
|
|
|
2017-02-09 01:52:37 +00:00
|
|
|
module.exports = Mongoose.model('User', userSchema)
|