Skip to content

Instantly share code, notes, and snippets.

@kosinix
Created July 14, 2019 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kosinix/cc81ae4bebc0d363f87c40f544aca9a4 to your computer and use it in GitHub Desktop.
Save kosinix/cc81ae4bebc0d363f87c40f544aca9a4 to your computer and use it in GitHub Desktop.
Express - Mongoose: Basic user table with password hash and checking methods.
//// 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