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.6 KiB

  1. "use strict";
  2. const modb = require('mongoose'),
  3. Promise = require('bluebird'),
  4. bcrypt = require('bcryptjs-then'),
  5. _ = require('lodash');
  6. /**
  7. * Region schema
  8. *
  9. * @type {<Mongoose.Schema>}
  10. */
  11. var userSchema = modb.Schema({
  12. email: {
  13. type: String,
  14. required: true,
  15. index: true
  16. },
  17. provider: {
  18. type: String,
  19. required: true
  20. },
  21. providerId: {
  22. type: String
  23. },
  24. password: {
  25. type: String
  26. },
  27. name: {
  28. type: String
  29. },
  30. rights: [{
  31. role: String,
  32. path: String,
  33. exact: Boolean,
  34. deny: Boolean
  35. }]
  36. },
  37. {
  38. timestamps: {}
  39. });
  40. userSchema.statics.processProfile = (profile) => {
  41. let primaryEmail = '';
  42. if(_.isArray(profile.emails)) {
  43. let e = _.find(profile.emails, ['primary', true]);
  44. primaryEmail = (e) ? e.value : _.first(profile.emails).value;
  45. } else if(_.isString(profile.email) && profile.email.length > 5) {
  46. primaryEmail = profile.email;
  47. } else {
  48. return Promise.reject(new Error('Invalid User Email'));
  49. }
  50. return db.User.findOneAndUpdate({
  51. email: primaryEmail,
  52. provider: profile.provider
  53. }, {
  54. email: primaryEmail,
  55. provider: profile.provider,
  56. providerId: profile.id,
  57. name: profile.displayName
  58. }, {
  59. new: true,
  60. upsert: true
  61. }).then((user) => {
  62. return (user) ? user : Promise.reject(new Error('User Upsert failed.'));
  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 = modb.model('User', userSchema);