Advertisement
Guest User

Untitled

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