-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathuser.model.ts
250 lines (233 loc) · 5.73 KB
/
user.model.ts
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
export {};
import { NextFunction, Request, Response, Router } from 'express';
const mongoose = require('mongoose');
const httpStatus = require('http-status');
const bcrypt = require('bcryptjs');
const moment = require('moment-timezone');
const jwt = require('jwt-simple');
const uuidv4 = require('uuid/v4');
const APIError = require('../../api/utils/APIError');
import { transformData, listData } from '../../api/utils/ModelUtils';
const { env, JWT_SECRET, JWT_EXPIRATION_MINUTES } = require('../../config/vars');
/**
* User Roles
*/
const roles = ['user', 'admin'];
/**
* User Schema
* @private
*/
const userSchema = new mongoose.Schema(
{
email: {
type: String,
match: /^\S+@\S+\.\S+$/,
required: true,
unique: true,
trim: true,
lowercase: true,
index: { unique: true }
},
password: {
type: String,
required: true,
minlength: 6,
maxlength: 128
},
tempPassword: {
type: String, // one-time temporary password (must delete after user logged in)
required: false,
minlength: 6,
maxlength: 128
},
name: {
type: String,
maxlength: 128,
index: true,
trim: true
},
services: {
facebook: String,
google: String
},
role: {
type: String,
enum: roles,
default: 'user'
},
picture: {
type: String,
trim: true
}
},
{
timestamps: true
}
);
const ALLOWED_FIELDS = ['id', 'name', 'email', 'picture', 'role', 'createdAt'];
/**
* Add your
* - pre-save hooks
* - validations
* - virtuals
*/
userSchema.pre('save', async function save(next: NextFunction) {
try {
// modifying password => encrypt it:
const rounds = env === 'test' ? 1 : 10;
if (this.isModified('password')) {
const hash = await bcrypt.hash(this.password, rounds);
this.password = hash;
} else if (this.isModified('tempPassword')) {
const hash = await bcrypt.hash(this.tempPassword, rounds);
this.tempPassword = hash;
}
return next(); // normal save
} catch (error) {
return next(error);
}
});
/**
* Methods
*/
userSchema.method({
// query is optional, e.g. to transform data for response but only include certain "fields"
transform({ query = {} }: { query?: any } = {}) {
// transform every record (only respond allowed fields and "&fields=" in query)
return transformData(this, query, ALLOWED_FIELDS);
},
token() {
const playload = {
exp: moment().add(JWT_EXPIRATION_MINUTES, 'minutes').unix(),
iat: moment().unix(),
sub: this._id
};
return jwt.encode(playload, JWT_SECRET);
},
async passwordMatches(password: string) {
return bcrypt.compare(password, this.password);
}
});
/**
* Statics
*/
userSchema.statics = {
roles,
/**
* Get user
*
* @param {ObjectId} id - The objectId of user.
* @returns {Promise<User, APIError>}
*/
async get(id: any) {
try {
let user;
if (mongoose.Types.ObjectId.isValid(id)) {
user = await this.findById(id).exec();
}
if (user) {
return user;
}
throw new APIError({
message: 'User does not exist',
status: httpStatus.NOT_FOUND
});
} catch (error) {
throw error;
}
},
/**
* Find user by email and tries to generate a JWT token
*
* @param {ObjectId} id - The objectId of user.
* @returns {Promise<User, APIError>}
*/
async findAndGenerateToken(options: any) {
const { email, password, refreshObject } = options;
if (!email) {
throw new APIError({ message: 'An email is required to generate a token' });
}
const user = await this.findOne({ email }).exec();
const err: any = {
status: httpStatus.UNAUTHORIZED,
isPublic: true
};
if (password) {
if (user && (await user.passwordMatches(password))) {
return { user, accessToken: user.token() };
}
err.message = 'Incorrect email or password';
} else if (refreshObject && refreshObject.userEmail === email) {
if (moment(refreshObject.expires).isBefore()) {
err.message = 'Invalid refresh token.';
} else {
return { user, accessToken: user.token() };
}
} else {
err.message = 'Incorrect email or refreshToken';
}
throw new APIError(err);
},
/**
* List users.
* @returns {Promise<User[]>}
*/
list({ query }: { query: any }) {
return listData(this, query, ALLOWED_FIELDS);
},
/**
* Return new validation error
* if error is a mongoose duplicate key error
*
* @param {Error} error
* @returns {Error|APIError}
*/
checkDuplicateEmail(error: any) {
if (error.name === 'MongoError' && error.code === 11000) {
return new APIError({
message: 'Validation Error',
errors: [
{
field: 'email',
location: 'body',
messages: ['"email" already exists']
}
],
status: httpStatus.CONFLICT,
isPublic: true,
stack: error.stack
});
}
return error;
},
async oAuthLogin({ service, id, email, name, picture }: any) {
const user = await this.findOne({ $or: [{ [`services.${service}`]: id }, { email }] });
if (user) {
user.services[service] = id;
if (!user.name) {
user.name = name;
}
if (!user.picture) {
user.picture = picture;
}
return user.save();
}
const password = uuidv4();
return this.create({
services: { [service]: id },
email,
password,
name,
picture
});
},
async count() {
return this.find().count();
}
};
/**
* @typedef User
*/
const User = mongoose.model('User', userSchema);
User.ALLOWED_FIELDS = ALLOWED_FIELDS;
module.exports = User;