Advertisement
Guest User

Untitled

a guest
Feb 5th, 2016
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. var mongoose = require('mongoose');
  2. var Schema = mongoose.Schema;
  3. var bcrypt = require('bcrypt'), SALT_WORK_FACTOR = 10;
  4.  
  5.  
  6. var UserSchema = new Schema({
  7. name: {
  8. first: { type: String, required: true },
  9. last: { type: String, required: true, default: "resident" }
  10. },
  11. uuid: { type: String, required: true, index: { unique: true } },
  12. passhash: { type: String, required: true },
  13. salt: { type: String, required: true },
  14. username: { type: String, unique: true, lowercase: true, trim: true, index: true },
  15. email: { type: String, unique: true, lowercase: true, trim: true, index: true, match: /.+\@.+\..+/ },
  16. role: { type: String, default: "user", required: true, enum: ['user', 'admin'] },
  17. status: { type: String, default: "active", required: true },
  18. permissions: [String],
  19. iat: [String],
  20. verified: { type: Date }
  21. });
  22.  
  23. UserSchema.virtual('Fullname').get(function() {
  24. var n = this.name.first + " " + this.name.last;
  25. return n.toString();
  26. });
  27.  
  28. UserSchema.virtual('isBanned').get(function() {
  29. return (this.status == "banned");
  30. });
  31. UserSchema.virtual('isAdmin').get(function() {
  32. return (this.role == "admin");
  33. });
  34.  
  35. UserSchema.pre('save', function(next) {
  36. var user = this;
  37. if (!user.isModified('passhash')) return next();
  38. bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
  39. if (err) return next(err);
  40. user.salt = salt;
  41. bcrypt.hash(user.passhash, salt, function(err, hash) {
  42. if (err) return next(err);
  43. user.passhash = hash;
  44. next();
  45. });
  46. });
  47. });
  48.  
  49. var ErrorMsgs = UserSchema.statics.ErrorMsgs = {
  50. INVALID_NAME = 0,
  51. FAILED_LOGIN = 1,
  52. INCORRECT_PASSWORD = 2,
  53. INVALID_EMAIL = 3,
  54. BANNED_ACCOUNT = 4,
  55. LOCKED_ACCOUNT = 5,
  56. VERIFY_EMAIL = 6
  57. };
  58.  
  59. UserSchema.path('role').validate(function(value) {
  60. return /user|admin/i.test(value);
  61. }, 'Invalid Role');
  62.  
  63. UserSchema.methods.checkPass = function (password, callback) {
  64. bcrypt.compare(password, this.passhash, function (err, match) {
  65. if (err) return callback(err);
  66. callback(null, match);
  67. });
  68. };
  69.  
  70. UserSchema.statics.Auth = function(name, password, callback) {
  71.  
  72. };
  73.  
  74. module.exports = mongoose.model('User', UserSchema);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement