Advertisement
Guest User

Untitled

a guest
Jun 8th, 2016
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1.  
  2.  
  3. var mongoose = require('mongoose');
  4. var baseModelPlugin = require('./plugins/baseModelPlugin');
  5.  
  6.  
  7. // define the schema for our user model
  8. var userSchema = new mongoose.Schema({
  9. profile: {
  10. firstName: String,
  11. lastName: String,
  12. avatar: String
  13. },
  14. username: {
  15. type: String,
  16. trim: true,
  17. unique: true,
  18. sparse: true,
  19. index: true,
  20. required: true
  21. },
  22. email: {
  23. type: String,
  24. trim: true,
  25. unique: true,
  26. sparse: true,
  27. required: true,
  28. match: [
  29. /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
  30. 'Please fill a valid email address'
  31. ],
  32. index: true
  33. },
  34. password: {
  35. type: String,
  36. required: true
  37. },
  38. role: String,
  39. account: {
  40. active: {
  41. type: Boolean,
  42. default: false
  43. },
  44. resetPasswordToken: String,
  45. resetPasswordExpires: Date,
  46. activationToken: String,
  47. activationExpires: Date
  48. }
  49. }, { timestamps: true });
  50.  
  51. userSchema.plugin(baseModelPlugin);
  52.  
  53. // generating a hash
  54. userSchema.methods.generateHash = function (password) {
  55. var bcrypt = require('bcrypt-nodejs');
  56. return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
  57. };
  58.  
  59. // generating a random hash
  60. userSchema.methods.generateRandomHash = function () {
  61. var bcrypt = require('bcrypt-nodejs');
  62. var random_text = require('crypto').randomBytes(16).toString('hex')
  63. .replace(/\+/g, '0') // replace '+' with '0'
  64. .replace(/\//g, '0'); // replace '/' with '0';
  65. return bcrypt.hashSync(random_text, bcrypt.genSaltSync(5), null);
  66. };
  67.  
  68. // checking if password is valid
  69. userSchema.methods.validatePassword = function (password) {
  70. var bcrypt = require('bcrypt-nodejs');
  71. return bcrypt.compareSync(password, this.password);
  72. };
  73.  
  74.  
  75. userSchema.methods.toJSON = function () {
  76. var obj = this.toObject();
  77. // remove props that should not be exposed
  78. delete obj.password;
  79. delete obj.__v;
  80. delete obj._id;
  81. delete obj.account;
  82.  
  83. return obj;
  84. };
  85.  
  86. userSchema.statics.findOneByAnyEmailOrUsername = function (val) {
  87. return this
  88. .findOne()
  89. .or([{ username: val }, { email: val }]);
  90. };
  91.  
  92. // create the model and expose it to our app
  93. module.exports = mongoose.model('User', userSchema);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement