This repository has been archived by the owner on Jul 26, 2018. It is now read-only.
/
user.js
101 lines (88 loc) · 2.82 KB
/
user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
* Module dependencies.
*/
var orm = require('orm'),
bcrypt = require('bcrypt'),
SALT_WORK_FACTOR = 10,
_ = require('underscore');
/**
* Validations
*/
var validatePresenceOf = function(value) {
return value && value.length;
};
/**
* User Schema
*/
module.exports = function (db, callback) {
db.load("./article", function (err) {
if (err) return callback(err);
var UserSchema = db.define("user", {
name: String,
email: String,
username: String,
provider: String,
password: String
},{
validations: {
name: orm.validators.notEmptyString('Name cannot be blank'),
email: orm.validators.notEmptyString('Email cannot be blank'),
username: [orm.validators.notEmptyString('Username cannot be blank'), orm.validators.unique("Username must be unique")],
password: orm.validators.notEmptyString('Password cannot be blank')
},
autoFetch: true,
hooks: {
/**
* Pre-save hook
*/
beforeSave: function(next) {
if (!this.isNew) return next();
if (!validatePresenceOf(this.password))
next(new Error('Invalid password'));
else
next();
},
beforeCreate: function (next) {
this.password = this.encryptPassword(this.password);
next();
}
},
/**
* Methods
*/
methods: {
/**
* Authenticate - check if the passwords are the same
*
* @param {String} plainText
* @return {Boolean}
* @api public
*/
authenticate: function(plainText) {
return bcrypt.compareSync(plainText, this.password);
},
/**
* Encrypt password
*
* @param {String} password
* @return {String}
* @api public
*/
encryptPassword: function(password) {
if (!password) return '';
return bcrypt.hashSync (password, bcrypt.genSaltSync(SALT_WORK_FACTOR));
}
}
});
return callback();
});
};
/**
* Virtuals
*/
/*UserSchema.virtual('password').set(function(password) {
this._password = password;
this.hashed_password = this.encryptPassword(password);
}).get(function() {
return this._password;
});*/