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.

87 lines
1.6 KiB

  1. "use strict";
  2. const Promise = require('bluebird'),
  3. bcrypt = require('bcryptjs-then'),
  4. _ = 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. },
  36. {
  37. timestamps: {}
  38. });
  39. userSchema.statics.processProfile = (profile) => {
  40. let primaryEmail = '';
  41. if(_.isArray(profile.emails)) {
  42. let e = _.find(profile.emails, ['primary', true]);
  43. primaryEmail = (e) ? e.value : _.first(profile.emails).value;
  44. } else if(_.isString(profile.email) && profile.email.length > 5) {
  45. primaryEmail = profile.email;
  46. } else {
  47. return Promise.reject(new Error('Invalid User Email'));
  48. }
  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
  57. }, {
  58. new: true,
  59. upsert: true
  60. }).then((user) => {
  61. return (user) ? user : Promise.reject(new Error('User Upsert failed.'));
  62. });
  63. };
  64. userSchema.statics.hashPassword = (rawPwd) => {
  65. return bcrypt.hash(rawPwd);
  66. };
  67. userSchema.methods.validatePassword = function(rawPwd) {
  68. return bcrypt.compare(rawPwd, this.password).then((isValid) => {
  69. return (isValid) ? true : Promise.reject(new Error('Invalid Login'));
  70. });
  71. };
  72. module.exports = Mongoose.model('User', userSchema);