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.

106 lines
2.5 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. primaryEmail = _.toLower(primaryEmail)
  52. return db.User.findOneAndUpdate({
  53. email: primaryEmail,
  54. provider: profile.provider
  55. }, {
  56. email: primaryEmail,
  57. provider: profile.provider,
  58. providerId: profile.id,
  59. name: profile.displayName || _.split(primaryEmail, '@')[0]
  60. }, {
  61. new: true
  62. }).then((user) => {
  63. // Handle unregistered accounts
  64. if (!user && profile.provider !== 'local' && (appconfig.auth.defaultReadAccess || profile.provider === 'ldap' || profile.provider === 'azure')) {
  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)