Created
July 14, 2019 13:51
-
-
Save kosinix/cc81ae4bebc0d363f87c40f544aca9a4 to your computer and use it in GitHub Desktop.
Express - Mongoose: Basic user table with password hash and checking methods.
This file contains hidden or 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
//// Core modules | |
const crypto = require('crypto'); | |
const util = require('util'); | |
//// External modules | |
const mongoose = require('mongoose'); | |
//// Modules | |
const randomBytesAsync = util.promisify(crypto.randomBytes); | |
const Schema = mongoose.Schema; | |
const schema = new Schema({ | |
username: { | |
type: String, | |
trim: true, | |
}, | |
passwordHash: { | |
type: String, | |
trim: true, | |
}, | |
salt: { | |
type: String, | |
trim: true, | |
}, | |
}, { timestamps: true }) | |
//// Schema methods | |
schema.statics.randomStringAsync = async function (length = 32) { | |
let salt = await randomBytesAsync(length); | |
return salt.toString('hex'); | |
} | |
schema.statics.hashPassword = function (password, salt) { | |
return crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex'); | |
}; | |
//// Instance methods | |
schema.methods.generatePasswordAsync = async function () { | |
let plainPass = await this.constructor.randomStringAsync() | |
let salt = await this.constructor.randomStringAsync(16) | |
this.passwordHash = this.constructor.hashPassword(plainPass, salt); | |
this.salt = salt; | |
return plainPass; | |
} | |
schema.methods.checkPassword = function (password) { | |
return this.passwordHash === this.constructor.hashPassword(password, this.salt); | |
} | |
//// Middlewares | |
module.exports = schema |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment