wikijs-fork/models/user.js

108 lines
2.5 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
2017-02-26 23:06:20 +00:00
} else if (_.isString(profile.mail) && profile.mail.length > 5) {
primaryEmail = profile.mail
} else if (profile.user && profile.user.email && profile.user.email.length > 5) {
primaryEmail = profile.user.email
2017-02-09 01:52:37 +00:00
} else {
return Promise.reject(new Error('Invalid User Email'))
}
profile.provider = _.lowerCase(profile.provider)
primaryEmail = _.toLower(primaryEmail)
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-03-12 04:38:47 +00:00
// LDAP - Handle unregistered accounts
// Todo: Allow this behavior for any provider...
if (!user && profile.provider === 'ldap') {
let nUsr = {
email: primaryEmail,
provider: profile.provider,
providerId: profile.id,
password: '',
name: profile.displayName || profile.name || profile.cn,
rights: [{
role: 'read',
path: '/',
exact: false,
deny: false
}]
}
return db.User.create(nUsr)
}
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)