-
Notifications
You must be signed in to change notification settings - Fork 137
/
user.server.model.js
executable file
·359 lines (340 loc) · 8.55 KB
/
user.server.model.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
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
path = require('path'),
textService = require(path.resolve('./modules/core/server/services/text.server.service')),
languages = require(path.resolve('./config/languages/languages.json')),
authenticationService = require(path.resolve('./modules/users/server/services/authentication.server.service')),
textService = require(path.resolve('./modules/core/server/services/text.server.service')),
crypto = require('crypto'),
mongoose = require('mongoose'),
uniqueValidation = require('mongoose-beautiful-unique-validation'),
validator = require('validator'),
Schema = mongoose.Schema;
var passwordMinLength = 8;
/**
* A Validation function for local strategy properties
*/
var validateLocalStrategyProperty = function (property) {
return ((this.provider !== 'local' && !this.updated) || property.length);
};
/**
* A Validation function for local strategy email
*/
var validateLocalStrategyEmail = function (email) {
return ((this.provider !== 'local' && !this.updated) || validator.isEmail(email));
};
/**
* A Validation function for password
*/
var validatePassword = function (password) {
return password && validator.isLength(password, passwordMinLength);
};
/**
* A Validation function for username
*/
var validateUsername = function (username) {
return this.provider !== 'local' || authenticationService.validateUsername(username);
};
var setPlainTextField = function (value) {
return textService.plainText(value, true);
};
/**
* SubSchema for `User` schema's `member` array
* This could be defined directly under `UserSchema` as well,
* but then we'd have extra `_id`'s hanging around.
*/
var UserMemberSchema = new Schema({
tribe: {
type: Schema.Types.ObjectId,
ref: 'Tribe',
required: true
},
since: {
type: Date,
default: Date.now,
required: true
}
}, { _id: false });
/**
* SubSchema for `User` schema's `pushRegistration` array
*/
var UserPushRegistrationSchema = new Schema({
platform: {
type: String,
// android, ios, web → Firebase; expo → Exponent
enum: ['android', 'ios', 'web', 'expo'],
required: true
},
token: {
type: String,
required: true
},
created: {
type: Date,
default: Date.now,
required: true
},
deviceId: {
type: String,
trim: true
}
}, { _id: false });
/**
* User Schema
*/
var UserSchema = new Schema({
firstName: {
type: String,
required: true,
validate: [validateLocalStrategyProperty, 'Please fill in your first name'],
set: setPlainTextField
},
lastName: {
type: String,
required: true,
validate: [validateLocalStrategyProperty, 'Please fill in your last name'],
set: setPlainTextField
},
/* This is generated in Schema pre-save hook below */
displayName: {
type: String
},
email: {
type: String,
trim: true,
unique: 'Email exists already.',
lowercase: true,
required: true,
validate: [validateLocalStrategyEmail, 'Please fill a valid email address']
},
/* New email is stored here until it is confirmed */
emailTemporary: {
type: String,
trim: true,
lowercase: true,
default: '',
match: [/.+\@.+\..+/, 'Please enter a valid email address']
},
tagline: {
type: String,
default: '',
set: setPlainTextField
},
description: {
type: String,
default: '',
set: textService.html
},
birthdate: {
type: Date
},
gender: {
type: String,
enum: ['', 'female', 'male', 'non-binary', 'other'],
default: ''
},
languages: {
type: [{
type: String,
enum: _.keys(languages)
}],
default: []
},
locationLiving: {
type: String,
set: setPlainTextField
},
locationFrom: {
type: String,
set: setPlainTextField
},
// Lowercase enforced username
username: {
type: String,
unique: 'Username exists already.',
required: true,
validate: [validateUsername, 'Please fill in valid username: 3+ characters long, non banned word, characters "_-.", no consecutive dots, does not begin or end with dots, letters a-z and numbers 0-9.'],
lowercase: true, // Stops users creating case sensitive duplicate usernames with "username" and "USERname", via @link https://github.com/meanjs/mean/issues/147
trim: true
},
usernameUpdated: {
type: Date
},
// Stores unaltered original username
displayUsername: {
type: String,
trim: true,
set: setPlainTextField
},
// Bewelcome.org username
extSitesBW: {
type: String,
trim: true,
set: setPlainTextField
},
// Couchsurfing.com username
extSitesCS: {
type: String,
trim: true,
set: setPlainTextField
},
// Warmshowers.org username
extSitesWS: {
type: String,
trim: true,
set: setPlainTextField
},
password: {
type: String,
default: '',
validate: [validatePassword, 'Password should be more than ' + passwordMinLength + ' characters long.']
},
emailHash: {
type: String
},
salt: {
type: String
},
/* All this provider stuff relates to oauth logins, will always be local for
Trustroots, comes from boilerplate. Will be removed one day. */
provider: {
type: String,
required: true,
default: 'local'
},
/* Facebook, Twitter etc data is stored here. */
providerData: {},
additionalProvidersData: {},
roles: {
type: [{
type: String,
enum: ['user', 'admin', 'suspended']
}],
default: ['user']
},
/* The last time the user was logged in; collected from July 2017 onwards */
seen: {
type: Date
},
updated: {
type: Date
},
created: {
type: Date,
default: Date.now
},
avatarSource: {
type: String,
enum: ['none', 'gravatar', 'facebook', 'local'],
default: 'gravatar'
},
avatarUploaded: {
type: Boolean,
default: false
},
newsletter: {
type: Boolean,
default: false
},
/* Preferred interface language (client, emails, ...) */
locale: {
type: String,
default: ''
},
passwordUpdated: {
type: Date
},
/* For email confirmations */
emailToken: {
type: String
},
/* New users are public=false until they validate their email. If public=false,
users can't email other users, can't be seen by other users. They are
effectively black holed... */
public: {
type: Boolean,
default: false
},
/* Count and latest date of emails sent to remind about un-finished signup
Will be removed once user sets `public:true` */
publicReminderCount: {
type: Number
},
publicReminderSent: {
type: Date
},
welcomeSequenceSent: {
type: Date
},
// Count on which welcome sequence step (onboarding emails) user is at
welcomeSequenceStep: {
type: Number,
default: 0
},
/* For reset password */
resetPasswordToken: {
type: String
},
resetPasswordExpires: {
type: Date
},
/* For removing the profile */
removeProfileToken: {
type: String
},
removeProfileExpires: {
type: Date
},
/* Tribes user is member of */
member: {
type: [UserMemberSchema]
},
pushRegistration: {
type: [UserPushRegistrationSchema],
default: []
}
});
/**
* Hook a pre save method to hash the password
*/
UserSchema.pre('save', function (next) {
if (this.password && this.isModified('password') && this.password.length >= passwordMinLength) {
this.salt = crypto.randomBytes(16).toString('base64');
this.password = this.hashPassword(this.password);
}
// Pre-cached email hash to use with Gravatar
if (this.email && this.isModified('email') && this.email !== '') {
this.emailHash = crypto.createHash('md5').update(this.email.trim().toLowerCase()).digest('hex');
}
// Generate `displayName`
if (this.isModified('firstName') || this.isModified('lastName')) {
this.displayName = this.firstName + ' ' + this.lastName;
}
next();
});
/**
* Create instance method for hashing a password
*/
UserSchema.methods.hashPassword = function (password) {
if (this.salt && password) {
return crypto.pbkdf2Sync(password, Buffer.from(this.salt, 'base64'), 10000, 64, 'SHA1').toString('base64');
} else {
return password;
}
};
/**
* Create instance method for authenticating user
*/
UserSchema.methods.authenticate = function (password) {
return this.password === this.hashPassword(password);
};
/**
* Make sure unique fields yeld verbal errors
* @link https://www.npmjs.com/package/mongoose-beautiful-unique-validation
*/
UserSchema.plugin(uniqueValidation);
UserSchema.index({ username: 'text', firstName: 'text', lastName: 'text' });
mongoose.model('User', UserSchema);