SHARE
TWEET

Untitled

a guest Jul 18th, 2019 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Pulling in required dependencies
  2. const mongoose = require('mongoose');
  3. const bcrypt   = require('bcrypt-nodejs');
  4. const Schema = mongoose.Schema;
  5.  
  6. //Creat UserSchema
  7. const UserSchema = new Schema({
  8.     local: {
  9.         email: String,
  10.         password: String,
  11.         resetPasswordToken: String,
  12.         resetPasswordExpires: Date
  13.     },
  14.     role: {
  15.         type: String,
  16.         default: 'user',
  17.     },
  18.     books_downloaded: {
  19.         booksId: {
  20.             type: Array,
  21.             required: false,
  22.         },
  23.     },
  24.     books_needed: {
  25.         type: Object,
  26.         default: null,
  27.     },
  28.     created_at: {
  29.         type: Date,
  30.         default: Date.now,
  31.     },
  32. });
  33.  
  34. // methods=====================================================
  35. // generating a hash
  36. UserSchema.methods.generateHash = (password) => {
  37.     return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
  38. }
  39.  
  40. //Hashing password on update
  41. UserSchema.pre('save', function(next) {
  42.     const User = this;
  43.     const SALT_FACTOR = 5;
  44.  
  45.     if(!User.isModified('local.password')) return next();
  46.    
  47.     bcrypt.genSalt(SALT_FACTOR, function(err,salt) {
  48.         if(err) return next(err);
  49.        
  50.         bcrypt.hash(User.local.password, salt, null, function(err,hash) {
  51.             if(err) return next(err);
  52.             User.local.password = hash;
  53.             next();
  54.         });
  55.     });
  56. });
  57.  
  58. // expose User model to the app
  59. module.exports = mongoose.model('User', UserSchema);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top