Advertisement
Guest User

User Model

a guest
Apr 14th, 2016
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. // import the stuff
  3. var mongoose = require("mongoose");
  4. var Schema = mongoose.Schema;
  5. var relationship = require("mongoose-relationship");
  6.  
  7.  
  8. var Item = require('../models/item.js');  //require Item model to make relational connection to User inventory items
  9. var bcrypt = require('bcrypt-nodejs');
  10.  
  11. var userSchema = new Schema({
  12.  
  13.     firstName: String,
  14.     lastName: String,
  15.     userName: { type: String, required: true, unique: true },
  16.     password: { type: String, required: true },
  17.     created_At: Date,
  18.     updated_At: Date,
  19.     inventory: [
  20.         {
  21.             type: Schema.ObjectId,
  22.             ref: 'Item',
  23.             default: []
  24.         }
  25.     ]
  26. });
  27.  
  28. userSchema.methods.comparePasswords = function(inputPassword, callback) {
  29.     var actualPassword = this.password;
  30.     console.log('INPUT PASSWORD=====', inputPassword);
  31.     console.log('ACTUAL PASSWORD=====', actualPassword);
  32.     bcrypt.compare(inputPassword, actualPassword, function(err, res) {
  33.         if (err) {
  34.             callback(err, null);
  35.         } else {
  36.             callback(null, res);
  37.         }
  38.     });
  39. };
  40.  
  41. userSchema.pre('save', function(next){
  42.     var user = this;
  43.     var password = this.password;
  44.     bcrypt.genSalt(10, function(err, salt) {
  45.         if(err) {
  46.             return next(err);
  47.         }
  48.         bcrypt.hash(password, salt , null, function(err, hash) {
  49.             if(err) {
  50.                 return next(err);
  51.             }
  52.  
  53.             user.password = hash;
  54.             user.salt = salt;
  55.             next();
  56.         });
  57.     });
  58. });
  59.  
  60. //Create a model using the schema
  61. var User = mongoose.model('User', userSchema);
  62.  
  63. module.exports = User;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement