-
Notifications
You must be signed in to change notification settings - Fork 0
/
UserModel.js
90 lines (82 loc) · 2.37 KB
/
UserModel.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
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// define the schema for our user model
var userSchema = mongoose.Schema({
profilePic : {
type: String,
default: '/files/profile.png'
},
local : {
email : String,
password : String,
name : String
},
facebook : {
id : String,
token : String,
email : String,
name : String
},
twitter : {
id : String,
token : String,
displayName : String,
username : String
},
google : {
id : String,
token : String,
email : String,
name : String
},
name: {type: String, default:null},
address: {type: String, default:null},
about: {type: String, default:null},
phone:{type:String, default:null},
token : String,
sockets :[String]
});
userSchema.plugin(require('mongoose-role'), {
roles: ['user', 'admin'],
accessLevels: {
'admin': ['user', 'admin'],
'user': ['user']
}
});
userSchema.virtual('password')
.set(function(password) {
this._password = password;
this.salt = this.makeSalt();
this.local.password = this.encryptPassword(password);
})
.get(function() { return this._password });
var validatePresenceOf = function (value) {
return value && value.length;
};
// methods ======================
userSchema.methods = {
generateHash: function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
},
validPassword: function(password) {
return bcrypt.compareSync(password, this.local.password);
},
authenticate: function (plainText) {
return this.encryptPassword(plainText) === this.local.password;
},
makeSalt: function () {
return Math.round((new Date().valueOf() * Math.random())) + '';
},
encryptPassword: function (password) {
if (!password) return '';
var encrypred;
try {
encrypred = crypto.createHmac('sha1', this.salt).update(password).digest('hex');
return encrypred;
} catch (err) {
return '';
}
}
} //methods end
// create the model for users and expose it to our app
module.exports = mongoose.model('User', userSchema);