wikijs-fork/models/user.js

83 lines
1.7 KiB
JavaScript
Raw Normal View History

2017-02-09 01:52:37 +00:00
'use strict'
2017-02-09 01:52:37 +00:00
const Promise = require('bluebird')
const bcrypt = require('bcryptjs-then')
const _ = require('lodash')
/**
* Region schema
*
* @type {<Mongoose.Schema>}
*/
2016-11-21 01:09:50 +00:00
var userSchema = Mongoose.Schema({
2017-02-09 01:52:37 +00:00
email: {
type: String,
required: true,
index: true
},
2017-02-09 01:52:37 +00:00
provider: {
type: String,
required: true
},
2017-02-09 01:52:37 +00:00
providerId: {
type: String
},
2017-02-09 01:52:37 +00:00
password: {
type: String
},
2017-02-09 01:52:37 +00:00
name: {
type: String
},
2017-02-09 01:52:37 +00:00
rights: [{
role: String,
path: String,
exact: Boolean,
deny: Boolean
}]
2017-02-09 01:52:37 +00:00
}, { timestamps: {} })
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'))
}
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]
}, {
2017-02-10 18:13:40 +00:00
new: true
2017-02-09 01:52:37 +00:00
}).then((user) => {
2017-02-10 18:13:40 +00:00
return user || Promise.reject(new Error('You have not been authorized to login to this site yet.'))
2017-02-09 01:52:37 +00:00
})
}
userSchema.statics.hashPassword = (rawPwd) => {
2017-02-09 01:52:37 +00:00
return bcrypt.hash(rawPwd)
}
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'))
})
}
2017-02-09 01:52:37 +00:00
module.exports = Mongoose.model('User', userSchema)