You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
1.9 KiB

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