user.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. // LDAP - Handle unregistered accounts
  63. // Todo: Allow this behavior for any provider...
  64. if (!user && profile.provider === 'ldap') {
  65. let nUsr = {
  66. email: primaryEmail,
  67. provider: profile.provider,
  68. providerId: profile.id,
  69. password: '',
  70. name: profile.displayName || profile.name || profile.cn,
  71. rights: [{
  72. role: 'read',
  73. path: '/',
  74. exact: false,
  75. deny: false
  76. }]
  77. }
  78. return db.User.create(nUsr)
  79. }
  80. return user || Promise.reject(new Error('You have not been authorized to login to this site yet.'))
  81. })
  82. }
  83. userSchema.statics.hashPassword = (rawPwd) => {
  84. return bcrypt.hash(rawPwd)
  85. }
  86. userSchema.methods.validatePassword = function (rawPwd) {
  87. return bcrypt.compare(rawPwd, this.password).then((isValid) => {
  88. return (isValid) ? true : Promise.reject(new Error('Invalid Login'))
  89. })
  90. }
  91. module.exports = Mongoose.model('User', userSchema)