Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var mongoose = require('mongoose');
- var Schema = mongoose.Schema;
- var bcrypt = require('bcrypt'), SALT_WORK_FACTOR = 10;
- var UserSchema = new Schema({
- name: {
- first: { type: String, required: true },
- last: { type: String, required: true, default: "resident" }
- },
- uuid: { type: String, required: true, index: { unique: true } },
- passhash: { type: String, required: true },
- salt: { type: String, required: true },
- username: { type: String, unique: true, lowercase: true, trim: true, index: true },
- email: { type: String, unique: true, lowercase: true, trim: true, index: true, match: /.+\@.+\..+/ },
- role: { type: String, default: "user", required: true, enum: ['user', 'admin'] },
- status: { type: String, default: "active", required: true },
- permissions: [String],
- iat: [String],
- verified: { type: Date }
- });
- UserSchema.virtual('Fullname').get(function() {
- var n = this.name.first + " " + this.name.last;
- return n.toString();
- });
- UserSchema.virtual('isBanned').get(function() {
- return (this.status == "banned");
- });
- UserSchema.virtual('isAdmin').get(function() {
- return (this.role == "admin");
- });
- UserSchema.pre('save', function(next) {
- var user = this;
- if (!user.isModified('passhash')) return next();
- bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
- if (err) return next(err);
- user.salt = salt;
- bcrypt.hash(user.passhash, salt, function(err, hash) {
- if (err) return next(err);
- user.passhash = hash;
- next();
- });
- });
- });
- var ErrorMsgs = UserSchema.statics.ErrorMsgs = {
- INVALID_NAME = 0,
- FAILED_LOGIN = 1,
- INCORRECT_PASSWORD = 2,
- INVALID_EMAIL = 3,
- BANNED_ACCOUNT = 4,
- LOCKED_ACCOUNT = 5,
- VERIFY_EMAIL = 6
- };
- UserSchema.path('role').validate(function(value) {
- return /user|admin/i.test(value);
- }, 'Invalid Role');
- UserSchema.methods.checkPass = function (password, callback) {
- bcrypt.compare(password, this.passhash, function (err, match) {
- if (err) return callback(err);
- callback(null, match);
- });
- };
- UserSchema.statics.Auth = function(name, password, callback) {
- };
- module.exports = mongoose.model('User', UserSchema);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement