user.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const mongoose = require('mongoose');
  2. const jwt = require('jsonwebtoken')
  3. const bcrypt = require('bcrypt')
  4. const Schema = mongoose.Schema;
  5. const userSchema = new Schema({
  6. avatar: String,
  7. email: { type: String,
  8. required: 'Email is Required',
  9. lowercase: true,
  10. unique: true,
  11. match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/]},
  12. name: { type: String,
  13. required: true,
  14. minlength: [6, 'Too short, min is 6 characters']},
  15. username: { type: String,
  16. required: true,
  17. minlength: [6, 'Too short, min is 6 characters']},
  18. password: {
  19. type: String,
  20. minlength: [4, 'Too short, min is 4 characters'],
  21. maxlength: [32, 'Too long, max is 32 characters'],
  22. required: 'Password is required'
  23. },
  24. // Very simplified you should have separate collection with roles
  25. // You can create also array of roles in case of multiple roles
  26. role: {
  27. enum: ['guest', 'admin'],
  28. type: String, required: true, default: 'guest'
  29. },
  30. info: String,
  31. products: [{ type: Schema.Types.ObjectId, ref: 'Product' }],
  32. createdAt: { type: Date, default: Date.now },
  33. updatedAt: { type: Date, default: Date.now }
  34. });
  35. userSchema.pre("save", function(next){
  36. const user = this;
  37. bcrypt.genSalt(10, function(err, salt) {
  38. if(err){ return next(err);}
  39. bcrypt.hash(user.password, salt, function(err, hash){
  40. if(err){ return next(err);}
  41. user.password = hash;
  42. next();
  43. });
  44. });
  45. });
  46. //Every user have acces to this methods
  47. userSchema.methods.comparePassword = function(candidatePassword, callback){
  48. bcrypt.compare(candidatePassword, this.password, function(err, isMatch){
  49. if(err) {return callback(err);}
  50. callback(null, isMatch);
  51. });
  52. }
  53. module.exports = mongoose.model('User', userSchema );