Skip to content

Instantly share code, notes, and snippets.

@Bioblaze
Created February 5, 2016 23:40
Show Gist options
  • Save Bioblaze/e80f4f5b5eee340e6ea0 to your computer and use it in GitHub Desktop.
Save Bioblaze/e80f4f5b5eee340e6ea0 to your computer and use it in GitHub Desktop.
Half Done Example of a Use Data model for Virtual Worlds
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment