Last active
July 8, 2017 06:42
-
-
Save thomasvnl/a3541aa6008fd3bab19e7ebcda0a443a to your computer and use it in GitHub Desktop.
NodeJS Mongoose User Schema to be used within a default NodeJS application structure
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
// file: app/models/user.js | |
// Get an instance of mongoose and mongoose Schema | |
var mongoose = require('mongoose'), | |
bcrypt = require('bcrypt'), | |
Schema = mongoose.Schema, | |
SALTINESS = 42; | |
// Create Schema | |
var UserSchema = new Schema({ | |
name: {type: String, require: true, index: {unique: true}}, | |
password: {type: String, require: true}, | |
admin: Boolean | |
}); | |
// Before saving the user, salt the password | |
UserSchema.pre('save', function(next) { | |
var user = this; | |
// No modification of the password, no need to hash it | |
if (!user.isModified('password')) next(); | |
bcrypt.genSalt(SALTINESS, function(error, salt) { | |
// Do not continue, error raised by genSalt | |
if (error) next(error); | |
// Create a bcrypt hash with the generated salt and assign it to the user object | |
bcrypt.hash(user.password, salt, function(error, hash) { | |
// Do not try to store the password, error raised by hash | |
if (error) next(error); | |
// Replace the password with the fresh generated hash and continue operation | |
user.password = hash; | |
next(); | |
}); | |
}); | |
}); | |
// Compare password method for validating a matching hash for a given password @ login | |
UserSchema.methods.comparePassword = comparePassword; | |
// Define comparePassword method | |
function comparePassword(input, callback) { | |
bcrypt.compare(input, this.password, function(error, isMatch) { | |
// Do not continue, error raised by bcrypt compare | |
if (error) return callback(error); | |
// Call the callback and return the result of bcrypt compare as data | |
callback(null, isMatch); | |
}); | |
} | |
// Expose via export | |
module.exports = mongoose.model('User', UserSchema); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment