user.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. 'use strict'
  2. const Promise = require('bluebird')
  3. const bcrypt = require('bcryptjs-then')
  4. const _ = require('lodash')
  5. /**
  6. * Region schema
  7. *
  8. * @type {<Mongoose.Schema>}
  9. */
  10. var userSchema = Mongoose.Schema({
  11. email: {
  12. type: String,
  13. required: true,
  14. index: true
  15. },
  16. provider: {
  17. type: String,
  18. required: true
  19. },
  20. providerId: {
  21. type: String
  22. },
  23. password: {
  24. type: String
  25. },
  26. name: {
  27. type: String
  28. },
  29. rights: [{
  30. role: String,
  31. path: String,
  32. exact: Boolean,
  33. deny: Boolean
  34. }]
  35. }, { timestamps: {} })
  36. userSchema.statics.processProfile = (profile) => {
  37. let primaryEmail = ''
  38. if (_.isArray(profile.emails)) {
  39. let e = _.find(profile.emails, ['primary', true])
  40. primaryEmail = (e) ? e.value : _.first(profile.emails).value
  41. } else if (_.isString(profile.email) && profile.email.length > 5) {
  42. primaryEmail = profile.email
  43. } else if (profile.user && profile.user.email && profile.user.email.length > 5) {
  44. primaryEmail = profile.user.email
  45. } else {
  46. return Promise.reject(new Error('Invalid User Email'))
  47. }
  48. profile.provider = _.lowerCase(profile.provider)
  49. return db.User.findOneAndUpdate({
  50. email: primaryEmail,
  51. provider: profile.provider
  52. }, {
  53. email: primaryEmail,
  54. provider: profile.provider,
  55. providerId: profile.id,
  56. name: profile.displayName || _.split(primaryEmail, '@')[0]
  57. }, {
  58. new: true
  59. }).then((user) => {
  60. return user || Promise.reject(new Error('You have not been authorized to login to this site yet.'))
  61. })
  62. }
  63. userSchema.statics.hashPassword = (rawPwd) => {
  64. return bcrypt.hash(rawPwd)
  65. }
  66. userSchema.methods.validatePassword = function (rawPwd) {
  67. return bcrypt.compare(rawPwd, this.password).then((isValid) => {
  68. return (isValid) ? true : Promise.reject(new Error('Invalid Login'))
  69. })
  70. }
  71. module.exports = Mongoose.model('User', userSchema)