Advertisement
Guest User

Untitled

a guest
Oct 5th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. const mongoose = require('../mongoose');
  2. const validator = require('validator');
  3. const bcrypt = require('bcrypt');
  4. const jwt = require('jsonwebtoken');
  5. const {JWT_SECRET} = require("../config");
  6.  
  7. const UserSchema = new mongoose.Schema({
  8. username: {
  9. type: String,
  10. unique: true,
  11. trim: true,
  12. required: 'Please supply an username'
  13. },
  14. email: {
  15. type: String,
  16. unique: true,
  17. lowercase: true,
  18. trim: true,
  19. validate: {
  20. validator: value => validator.isEmail(value),
  21. message: 'Invalid email address'
  22. },
  23. required: 'Please supply an email'
  24. },
  25. hash: {
  26. type: String,
  27. required: 'Please supply an hash'
  28. },
  29. productId: {
  30. type: mongoose.Schema.Types.ObjectId,
  31. ref: 'Product'
  32. }
  33. });
  34.  
  35. function autopopulate(next) {
  36. this.populate('productId');
  37. next();
  38. }
  39.  
  40. UserSchema.pre('find', autopopulate);
  41. UserSchema.pre('findOne', autopopulate);
  42.  
  43. UserSchema.methods.hashPassword = async function(password) {
  44. const hash = await bcrypt.hash(password, 8);
  45. this.hash = hash;
  46. }
  47.  
  48. UserSchema.methods.verifyPassword = async function(password) {
  49. return await bcrypt.compare(password, this.hash);
  50. }
  51.  
  52. UserSchema.methods.generateJWT = function() {
  53. return jwt.sign({
  54. _id: this._id,
  55. username: this.username,
  56. email: this.email
  57. }, JWT_SECRET, {
  58. expiresIn: '1day',
  59. subject: 'air'
  60. });
  61. }
  62.  
  63. const User = mongoose.model('User', UserSchema);
  64. module.exports = User;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement