Guest User

Users.js

a guest
Nov 22nd, 2016
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. var mongoose = require('mongoose');
  2. var crypto = require('crypto');
  3. var jwt = require('jsonwebtoken');
  4.  
  5. var UserSchema = new mongoose.Schema({
  6. username: {type: String, lowercase: true, unique: true},
  7. hash: String,
  8. salt: String
  9. });
  10.  
  11. UserSchema.methods.generateJWT = function() {
  12. var today = new Date();
  13. var exp = new Date(today);
  14. exp.setDate(today.getDate() + 60);
  15.  
  16. return jwt.sign({
  17. _id: this._id,
  18. username: this.username,
  19. exp: parseInt(exp.getTime() / 1000),
  20. }, 'SECRET');
  21. };
  22.  
  23. UserSchema.methods.setPassword = function(password){
  24. this.salt = crypto.randomBytes(16).toString('hex');
  25.  
  26. this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
  27. };
  28.  
  29. UserSchema.methods.validPassword = function(password) {
  30. var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
  31.  
  32. return this.hash === hash;
  33. };
  34.  
  35. mongoose.model('User', UserSchema);
Add Comment
Please, Sign In to add comment