-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuser.ts
More file actions
259 lines (226 loc) · 7.64 KB
/
user.ts
File metadata and controls
259 lines (226 loc) · 7.64 KB
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
import { ResolverContextBase, ResolverContextWithUser, UserJWTData } from '../types/graphql';
import UserModel, { TokensPair } from '../models/user';
import { AuthenticationError, ApolloError, UserInputError } from 'apollo-server-express';
import jwt, { Secret } from 'jsonwebtoken';
import { errorCodes } from '../errors';
import Validator from '../utils/validator';
import { SenderWorkerTaskType } from '../types/userNotifications';
import { TaskPriorities, emailNotification } from '../utils/emailNotifications';
import isE2E from '../utils/isE2E';
import { dateFromObjectId } from '../utils/dates';
import { UserDBScheme } from '@hawk.so/types';
import * as telegram from '../utils/telegram';
import { MongoError } from 'mongodb';
/**
* See all types and fields here {@see ../typeDefs/user.graphql}
*/
export default {
Query: {
/**
* Returns authenticated user data
* @param _obj - parent object (undefined for this resolver)
* @param _args - query args (empty)
* @param user - current authenticated user
* @param factories - factories for working with models
*/
async me(
_obj: undefined,
_args: {},
{ user, factories }: ResolverContextWithUser
): Promise<UserModel | null> {
return factories.usersFactory.findById(user.id);
},
},
Mutation: {
/**
* Register user with provided email
* @param _obj - parent object (undefined for this resolver)
* @param email - user email
* @param utm - UTM parameters
* @param factories - factories for working with models
*/
async signUp(
_obj: undefined,
{ email, utm }: { email: string; utm?: any },
{ factories }: ResolverContextBase
): Promise<boolean | string> {
let user;
try {
user = await factories.usersFactory.create(email, undefined, utm);
const password = user.generatedPassword!;
await emailNotification({
type: SenderWorkerTaskType.SignUp,
payload: {
password: password,
endpoint: email,
},
}, {
priority: TaskPriorities.IMPORTANT,
});
telegram.sendMessage(`🚶 User "${email}" signed up`);
return isE2E ? password : true;
} catch (e) {
if ((e as MongoError).code?.toString() === errorCodes.DB_DUPLICATE_KEY_ERROR) {
throw new AuthenticationError(
'User with this email already registered'
);
}
throw e;
}
},
/**
* Login user with provided email and password
* @param _obj - parent object (undefined for this resolver)
* @param email - user email
* @param password - user password
* @param factories - factories for working with models
*/
async login(
_obj: undefined,
{ email, password }: {email: string; password: string},
{ factories }: ResolverContextBase
): Promise<TokensPair> {
const user = await factories.usersFactory.findByEmail(email);
if (!user || !(await user.comparePassword(password))) {
throw new AuthenticationError('Wrong email or password');
}
return user.generateTokensPair();
},
/**
* Update user's tokens pair
* @param _obj - parent object (undefined for this resolver)
* @param refreshToken - refresh token for getting new token pair
* @param factories - factories for working with models
*/
async refreshTokens(
_obj: undefined,
{ refreshToken }: {refreshToken: string},
{ factories }: ResolverContextBase
): Promise<TokensPair> {
let userId;
try {
const data = await jwt.verify(refreshToken, process.env.JWT_SECRET_REFRESH_TOKEN as Secret) as UserJWTData;
userId = data.userId;
} catch (err) {
throw new AuthenticationError('Invalid refresh token');
}
const user = await factories.usersFactory.findById(userId);
if (!user) {
throw new ApolloError('There is no users with that id');
}
return user.generateTokensPair();
},
/**
* Reset user password
* @param _obj - parent object (undefined for this resolver)
* @param email - user email
* @param factories - factories for working with models
*/
async resetPassword(
_obj: undefined,
{ email }: {email: string},
{ factories }: ResolverContextBase
): Promise<boolean> {
/**
* @todo Better password reset via one-time link
*/
const user = await factories.usersFactory.findByEmail(email);
if (!user) {
return true;
}
try {
const newPassword = await UserModel.generatePassword();
await user.changePassword(newPassword);
await emailNotification({
type: SenderWorkerTaskType.PasswordReset,
payload: {
newPassword: newPassword,
endpoint: email,
},
}, {
priority: TaskPriorities.IMPORTANT,
});
} catch (err) {
throw new ApolloError('Something went wrong');
}
return true;
},
/**
* Update profile user data
* @param _obj - parent object (undefined for this resolver)
* @param name - user's name to change
* @param email - user's email to change
* @param user - current authenticated user
* @param image - user avatar
* @param factories - factories for working with models
*/
async updateProfile(
_obj: undefined,
{ name, email, image }: {name: string; email: string; image: string},
{ user, factories }: ResolverContextWithUser
): Promise<boolean> {
if (email && !Validator.validateEmail(email)) {
throw new UserInputError('Wrong email format');
}
const userWithEmail = await factories.usersFactory.findByEmail(email);
const currentUser = await factories.usersFactory.findById(user.id);
// TODO: replace with email verification
if (userWithEmail && userWithEmail._id.toString() !== user.id) {
throw new UserInputError('This email is taken');
}
try {
const options: {[key: string]: string | object} = {
name,
email,
'notifications.channels.email.endpoint': email,
};
if (image) {
options.image = image;
}
await currentUser!.updateProfile(options);
} catch (err) {
throw new ApolloError((err as Error).toString());
}
return true;
},
/**
* Change user password
* @param _obj - parent object (undefined for this resolver)
* @param oldPassword - old password
* @param newPassword - password to change
* @param user - current authenticated user
* @param factories - factories for working with models
*/
async changePassword(
_obj: undefined,
{ oldPassword, newPassword }: { oldPassword: string; newPassword: string },
{ user, factories }: ResolverContextWithUser
): Promise<boolean> {
const foundUser = await factories.usersFactory.findById(user.id);
if (!foundUser) {
throw new ApolloError('There is no user with such id');
}
if (!user || !(await foundUser.comparePassword(oldPassword))) {
throw new AuthenticationError('Wrong old password. Try again.');
}
try {
await foundUser.changePassword(newPassword);
} catch (err) {
throw new ApolloError('Something went wrong');
}
return true;
},
},
User: {
/**
* Returns user registration date
*
* @param {UserDBScheme} user - result of parent resolver
*
* @returns {Date}
*/
registrationDate(user: UserDBScheme): Date {
return dateFromObjectId(user._id);
},
},
};