Last active
September 11, 2017 20:10
-
-
Save jdtdesigns/aa51ea20201598631fc8418acde36727 to your computer and use it in GitHub Desktop.
User model with encryption and roles -- Mongoose
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
const mongoose = require('mongoose'); | |
const Schema = mongoose.Schema; | |
// const bcrypt = require('bcrypt'); | |
mongoose.Promise = global.Promise; // removes deprecation warning | |
const UserSchema = new Schema({ | |
username: { | |
type: String, | |
required: true, | |
unique: true | |
}, | |
email: { | |
type: String, | |
required: true, | |
unique: true | |
}, | |
image: { | |
type: String, | |
required: true | |
}, | |
accessToken: String, | |
refreshToken: String, | |
created_at: Date, | |
updated_at: Date | |
}); | |
UserSchema.plugin(require('mongoose-role'), { | |
roles: ['public', 'user', 'manager', 'admin'], | |
accessLevels: { | |
'public': ['public', 'user', 'admin'], | |
'anon': ['public'], | |
'user': ['user', 'admin'], | |
'admin': ['admin'] | |
} | |
}); | |
UserSchema.pre('save', function(next) { | |
let user = this; | |
let date = new Date(); | |
user.updated_at = date; | |
if ( !user.created_at ) { | |
user.created_at = date; | |
next(); | |
} else next(); | |
// bcrypt.genSalt(10, (err, salt) => { | |
// if ( err ) return next(err); | |
// bcrypt.hash(user.password, salt, (err, hash) => { | |
// if ( err ) return next(err); | |
// user.password = hash; | |
// next(); | |
// }); | |
// }); | |
}); | |
UserSchema.methods.toJSON = function() { | |
let user = this.toObject(); | |
delete user.__v; | |
delete user.created_at; | |
delete user.updated_at; | |
return user; | |
} | |
// UserSchema.methods.comparePassword = function(pass, cb) { | |
// bcrypt.compare(pass, this.password, (err, isMatch) => { | |
// if ( err ) return cb(err); | |
// cb(null, isMatch); | |
// }); | |
// } | |
module.exports = mongoose.model('User', UserSchema); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment