Created
June 15, 2021 07:42
-
-
Save kek-Sec/62e0561ba6b424ca455db7552919a824 to your computer and use it in GitHub Desktop.
Moongoose JWT model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose'); | |
var uniqueValidator = require('mongoose-unique-validator'); | |
var crypto = require('crypto'); | |
var jwt = require('jsonwebtoken'); | |
var secret = require('../config').secret; | |
var UserSchema = new mongoose.Schema({ | |
username: | |
{ | |
type: String, | |
lowercase: true, | |
unique: true, | |
required: [true, "can't be blank"], | |
match: [/^[a-zA-Z0-9]+$/, 'is invalid'], | |
index: true | |
}, | |
email: | |
{ | |
type: String, | |
lowercase: true, | |
unique: true, | |
required: [true, "can't be blank"], | |
match: [/\S+@\S+\.\S+/, 'is invalid'], | |
index: true | |
}, | |
bio: String, | |
hash: String, | |
salt: String | |
}, { timestamps: true }); | |
UserSchema.plugin(uniqueValidator, { message: 'is already taken.' }); | |
//#region methods | |
UserSchema.methods.setPassword = function (password) { | |
this.salt = crypto.randomBytes(16).toString('hex'); | |
this.hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex'); | |
}; | |
UserSchema.methods.validPassword = function(password) { | |
var hash = crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex'); | |
return this.hash === hash; | |
}; | |
UserSchema.methods.generateJWT = function(){ | |
var today = new Date(); | |
var exp = new Date(today); | |
exp.setDate(today.getDate + 30); | |
return jwt.sign( | |
{ | |
id: this.id, | |
username: this.username, | |
exp: parseInt(exp.getTime() / 1000), | |
}, secret | |
); | |
}; | |
UserSchema.methods.toAuthJson = function(){ | |
return{ | |
username: this.username, | |
email: this.email, | |
token: this.generateJWT(), | |
image: this.image | |
}; | |
}; | |
//#endregion | |
mongoose.model('User', UserSchema); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment