aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/app/models/User.js
blob: c07a29805ed24bc6f827b5b23eff706d0a21daaa (plain) (blame)
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179

/**
 * Module dependencies
 */

var mongoose = require('mongoose')
  , Schema = mongoose.Schema
  , crypto = require('crypto')
  , authTypes = ['facebook', 'twitter'];


/**
 *  User schema
 *
 *  statuscodes:
 *  1: invited
 *  2: unconfirmed
 *  3: active
 *  4: paying user
 */

var UserSchema = new Schema({
    name:               String
  , email:              { type: String, unique: true }
  , username:           String
  , provider:           String
  , hashed_password:    String
  , salt:               String
  , accessToken:        String
  , facebook:           {}
  , twitter:            {}
  , status:             { type: Number, default: 2 }
  , randomToken:        String
  , created:            { type: Date, default: Date.now }
  , updated:            { type: Date, default: Date.now }
});


/**
 * Virtuals
 */

UserSchema.virtual('password').set(function(password) {
    this._password = password
    this.salt = this.makeSalt()
    this.hashed_password = this.encryptPassword(password)
  }).get(function() { return this._password });


/**
 *  Validations
 */

var validatePrecenceOf = function(value) {
    return value && value.length;
}


// the four validations below only apply if you are signing up traditionally

UserSchema.path('name').validate(function(name) {
    // if you're authenticated by any of the oauth strategies (facebook, twitter), don't validate
    if(authTypes.indexOf(this.provider) !== -1 || this.status === 1) return true;
    return name.length;
}, 'Name cannot be blank');

UserSchema.path('email').validate(function(email) {
    if(authTypes.indexOf(this.provider) !== -1) return true;
    return email.length;
}, 'Email cannot be blank');

UserSchema.path('username').validate(function(username) {
    if(authTypes.indexOf(this.provider) !== -1 || this.status === 1) return true;
    return username.length;
}, 'Username cannot be blank');

UserSchema.path('hashed_password').validate(function(hashed_password) {
    if(authTypes.indexOf(this.provider) !== -1) return true;
    return hashed_password.length;
}, 'Password cannot be blank');


/**
 * Pre-save hook
 */

UserSchema.pre('save', function(next) {
    if (!this.isNew || this.status === 1) return next();

    this.updated = Date.now();
    next();

});


/**
 * Methods
 */

UserSchema.methods = {

   /**
    * Authenticate - check if passwords are the same
    *
    * @param {String} plainText
    * @return {Bolean}
    * @api public
    */

    authenticate: function(plainText) {
        return this.encryptPassword(plainText) === this.hashed_password; // will return true or false
    },


   /**
    * Make salt
    * This is used to make the password hash cryptographically stronger
    *
    * @return {String}
    */

    makeSalt: function() {
        return Math.round((new Date().valueOf() * Math.random())) + ''; // valueOf date and random number = random stuff!
    },


   /**
    * Encrypt password
    *
    * @param {String} password
    * @return {String}
    */

    encryptPassword: function(password) {
        if (!password) return '';
        // if the user isn't registered, he has no salt. Therefore he can not log in. He has to use his email.
        return crypto.createHmac('sha1', this.salt || Math.random() + Math.random()).update(password).digest('hex');
    },


   /**
    * Generate random access token for Remember Me function
    *
    * @param {Number} length
    * @param {Boolean} noDate
    * @return {String}
    */

    generateRandomToken: function(length, noDate) {
        if (typeof(length) === undefined) length = 16; // default length of token
        var chars = '_-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
          , token = noDate ? '' : new Date().getTime() + '_'; // if noDate is provided as true, the random token will not start with a timestamp.
        for (var i = 0; i < length; i++) {
            var x = Math.floor(Math.random() * chars.length);
            token += chars.charAt(x);
        }
        return token;
    }
}

UserSchema.statics = {

   /**
    * Load user from their email address
    *
    * @param {String} email
    * @param {Function} callback
    */

    loadUser: function(email, callback) {
        this.findOne({ email: email })
        .exec(callback);
    }

}

mongoose.model('User', UserSchema);