user.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 {
  44. return Promise.reject(new Error('Invalid User Email'))
  45. }
  46. return db.User.findOneAndUpdate({
  47. email: primaryEmail,
  48. provider: profile.provider
  49. }, {
  50. email: primaryEmail,
  51. provider: profile.provider,
  52. providerId: profile.id,
  53. name: profile.displayName || _.split(primaryEmail, '@')[0]
  54. }, {
  55. new: true
  56. }).then((user) => {
  57. return user || Promise.reject(new Error('You have not been authorized to login to this site yet.'))
  58. })
  59. }
  60. userSchema.statics.hashPassword = (rawPwd) => {
  61. return bcrypt.hash(rawPwd)
  62. }
  63. userSchema.methods.validatePassword = function (rawPwd) {
  64. return bcrypt.compare(rawPwd, this.password).then((isValid) => {
  65. return (isValid) ? true : Promise.reject(new Error('Invalid Login'))
  66. })
  67. }
  68. module.exports = Mongoose.model('User', userSchema)