Created
April 14, 2017 15:04
-
-
Save rwoody/1846d870bfec6aa8419d9de3c5e6d624 to your computer and use it in GitHub Desktop.
Mongoose User Password middleware
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
import bcrypt from 'bcrypt' | |
import Promise from 'bluebird' | |
const Constants = { | |
PASSWORD_MAX_LENGTH: 64, | |
PASSWORD_SALT_FACTOR: 10 | |
} | |
const hash = Promise.promisify(bcrypt.hash) | |
const genSalt = Promise.promisify(bcrypt.genSalt) | |
const compare = Promise.promisify(bcrypt.compare) | |
export function comparePassword(password, hashedPassword) { | |
return compare(password, hashedPassword) | |
} | |
export default function encryptPassword(password) { | |
if (password.length > Constants.PASSWORD_MAX_LENGTH) { | |
password = password.substr(0, Constants.PASSWORD_MAX_LENGTH) | |
} | |
return genSalt(Constants.PASSWORD_SALT_FACTOR).then(salt => { | |
return hash(password, salt) | |
}) | |
} |
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
import encryptPassword, {comparePassword} from './encryptPassword' | |
/** | |
* Password hash middleware. | |
*/ | |
UserSchema.pre('save', function (next) { | |
const user = this; | |
if (!user.isModified('password')) { return next(); } | |
encryptPassword(user.password).then(hash => { | |
user.password = hash | |
next() | |
}) | |
.catch(next) | |
}); | |
/** | |
* Instance method for validating user's password. | |
*/ | |
UserSchema.methods = { | |
comparePassword(plainPassword) { | |
return comparePassword(plainPassword, this.password) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment