Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import mongoose from 'mongoose'
- import crypto from 'crypto'
- const Schema = mongoose.Schema
- const User = new Schema({
- username: {
- type: String
- },
- hashedPassword: {
- type: String,
- required: true
- },
- salt: {
- type: String,
- required: true
- }
- })
- User.methods.encryptPassword = function(password) {
- return crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex')
- }
- User.virtual('userId').get(function() {
- return this.id
- })
- User.virtual('password').set(function(password) {
- this._plainPassword = password
- this.salt = crypto.randomBytes(128).toString('hex')
- this.hashedPassword = this.encryptPassword(password)
- }).get(function() {
- return this._plainPassword
- })
- User.methods.checkPassword = function(password) {
- return this.encryptPassword(password) == this.hashedPassword
- }
- module.exports = mongoose.model('User', User)
Add Comment
Please, Sign In to add comment