user.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. type: String
  32. }]
  33. },
  34. {
  35. timestamps: {}
  36. });
  37. userSchema.statics.processProfile = (profile) => {
  38. let primaryEmail = '';
  39. if(_.isArray(profile.emails)) {
  40. let e = _.find(profile.emails, ['primary', true]);
  41. primaryEmail = (e) ? e.value : _.first(profile.emails).value;
  42. } else if(_.isString(profile.email) && profile.email.length > 5) {
  43. primaryEmail = profile.email;
  44. } else {
  45. return Promise.reject(new Error('Invalid User Email'));
  46. }
  47. return db.User.findOneAndUpdate({
  48. email: primaryEmail,
  49. provider: profile.provider
  50. }, {
  51. email: primaryEmail,
  52. provider: profile.provider,
  53. providerId: profile.id,
  54. name: profile.displayName
  55. }, {
  56. new: true,
  57. upsert: true
  58. }).then((user) => {
  59. return (user) ? user : Promise.reject(new Error('User Upsert failed.'));
  60. });
  61. };
  62. userSchema.statics.hashPassword = (rawPwd) => {
  63. return bcrypt.hash(rawPwd);
  64. };
  65. userSchema.methods.validatePassword = function(rawPwd) {
  66. let self = this;
  67. return bcrypt.hash(rawPwd).then((pwd) => {
  68. return (self.password === pwd) ? true : Promise.reject(new Error('Invalid Password'));
  69. });
  70. };
  71. module.exports = modb.model('User', userSchema);