Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var mongoose = require('mongoose');
- var jwt = require('jsonwebtoken');
- var UserSchema = new mongoose.Schema({
- username: {type: String, lowercase: true, unique: true},
- hash: String,
- salt: String
- });
- mongoose.model('User', UserSchema);
- var crypto = require('crypto');
- // Accepts a password then generates a salt and associated password hash
- UserSchema.methods.setPassword = function(password) {
- console.log(password);
- this.salt = crypto.randomBytes(16).toString('hex');
- this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
- };
- // Accepts a password and compares it to the hash stored, returning a boolean
- UserSchema.methods.validPassword = function(password) {
- var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
- return this.hash === hash;
- };
- UserSchema.methods.generateJWT = function() {
- // set expiration to 60 days
- var today = new Date();
- var exp = new Date(today);
- exp.setDate(today.getDate() + 60);
- return jwt.sign({
- _id: this._id,
- username: this.username,
- exp: parseInt(exp.getTime() / 1000),
- }, 'SECRET');
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement