-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
user.service.ts
301 lines (284 loc) · 13 KB
/
user.service.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
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
import { Injectable } from '@nestjs/common';
import { VerifyCustomerAccountResult } from '@vendure/common/lib/generated-shop-types';
import { ID } from '@vendure/common/lib/shared-types';
import { RequestContext } from '../../api/common/request-context';
import { ErrorResultUnion } from '../../common/error/error-result';
import { EntityNotFoundError, InternalServerError } from '../../common/error/errors';
import {
IdentifierChangeTokenExpiredError,
IdentifierChangeTokenInvalidError,
InvalidCredentialsError,
MissingPasswordError,
PasswordAlreadySetError,
PasswordResetTokenExpiredError,
PasswordResetTokenInvalidError,
VerificationTokenExpiredError,
VerificationTokenInvalidError,
} from '../../common/error/generated-graphql-shop-errors';
import { ConfigService } from '../../config/config.service';
import { NativeAuthenticationMethod } from '../../entity/authentication-method/native-authentication-method.entity';
import { User } from '../../entity/user/user.entity';
import { PasswordCipher } from '../helpers/password-cipher/password-cipher';
import { VerificationTokenGenerator } from '../helpers/verification-token-generator/verification-token-generator';
import { TransactionalConnection } from '../transaction/transactional-connection';
import { RoleService } from './role.service';
@Injectable()
export class UserService {
constructor(
private connection: TransactionalConnection,
private configService: ConfigService,
private roleService: RoleService,
private passwordCipher: PasswordCipher,
private verificationTokenGenerator: VerificationTokenGenerator,
) {}
async getUserById(ctx: RequestContext, userId: ID): Promise<User | undefined> {
return this.connection.getRepository(ctx, User).findOne(userId, {
relations: ['roles', 'roles.channels', 'authenticationMethods'],
});
}
async getUserByEmailAddress(ctx: RequestContext, emailAddress: string): Promise<User | undefined> {
return this.connection.getRepository(ctx, User).findOne({
where: {
identifier: emailAddress,
deletedAt: null,
},
relations: ['roles', 'roles.channels', 'authenticationMethods'],
});
}
async createCustomerUser(ctx: RequestContext, identifier: string, password?: string): Promise<User> {
const user = new User();
user.identifier = identifier;
const customerRole = await this.roleService.getCustomerRole();
user.roles = [customerRole];
return this.connection
.getRepository(ctx, User)
.save(await this.addNativeAuthenticationMethod(ctx, user, identifier, password));
}
async addNativeAuthenticationMethod(
ctx: RequestContext,
user: User,
identifier: string,
password?: string,
): Promise<User> {
const checkUser = user.id != null && (await this.getUserById(ctx, user.id));
if (checkUser) {
if (
!!checkUser.authenticationMethods.find(
(m): m is NativeAuthenticationMethod => m instanceof NativeAuthenticationMethod,
)
) {
// User already has a NativeAuthenticationMethod registered, so just return.
return user;
}
}
const authenticationMethod = new NativeAuthenticationMethod();
if (this.configService.authOptions.requireVerification) {
authenticationMethod.verificationToken =
this.verificationTokenGenerator.generateVerificationToken();
user.verified = false;
} else {
user.verified = true;
}
if (password) {
authenticationMethod.passwordHash = await this.passwordCipher.hash(password);
} else {
authenticationMethod.passwordHash = '';
}
authenticationMethod.identifier = identifier;
await this.connection.getRepository(ctx, NativeAuthenticationMethod).save(authenticationMethod);
user.authenticationMethods = [...(user.authenticationMethods ?? []), authenticationMethod];
return user;
}
async createAdminUser(ctx: RequestContext, identifier: string, password: string): Promise<User> {
const user = new User({
identifier,
verified: true,
});
const authenticationMethod = await this.connection
.getRepository(ctx, NativeAuthenticationMethod)
.save(
new NativeAuthenticationMethod({
identifier,
passwordHash: await this.passwordCipher.hash(password),
}),
);
user.authenticationMethods = [authenticationMethod];
return this.connection.getRepository(ctx, User).save(user);
}
async softDelete(ctx: RequestContext, userId: ID) {
await this.connection.getEntityOrThrow(ctx, User, userId);
await this.connection.getRepository(ctx, User).update({ id: userId }, { deletedAt: new Date() });
}
async setVerificationToken(ctx: RequestContext, user: User): Promise<User> {
const nativeAuthMethod = user.getNativeAuthenticationMethod();
nativeAuthMethod.verificationToken = this.verificationTokenGenerator.generateVerificationToken();
user.verified = false;
await this.connection.getRepository(ctx, NativeAuthenticationMethod).save(nativeAuthMethod);
return this.connection.getRepository(ctx, User).save(user);
}
async verifyUserByToken(
ctx: RequestContext,
verificationToken: string,
password?: string,
): Promise<ErrorResultUnion<VerifyCustomerAccountResult, User>> {
const user = await this.connection
.getRepository(ctx, User)
.createQueryBuilder('user')
.leftJoinAndSelect('user.authenticationMethods', 'authenticationMethod')
.addSelect('authenticationMethod.passwordHash')
.where('authenticationMethod.verificationToken = :verificationToken', { verificationToken })
.getOne();
if (user) {
if (this.verificationTokenGenerator.verifyVerificationToken(verificationToken)) {
const nativeAuthMethod = user.getNativeAuthenticationMethod();
if (!password) {
if (!nativeAuthMethod.passwordHash) {
return new MissingPasswordError();
}
} else {
if (!!nativeAuthMethod.passwordHash) {
return new PasswordAlreadySetError();
}
nativeAuthMethod.passwordHash = await this.passwordCipher.hash(password);
}
nativeAuthMethod.verificationToken = null;
user.verified = true;
await this.connection.getRepository(ctx, NativeAuthenticationMethod).save(nativeAuthMethod);
return this.connection.getRepository(ctx, User).save(user);
} else {
return new VerificationTokenExpiredError();
}
} else {
return new VerificationTokenInvalidError();
}
}
async setPasswordResetToken(ctx: RequestContext, emailAddress: string): Promise<User | undefined> {
const user = await this.getUserByEmailAddress(ctx, emailAddress);
if (!user) {
return;
}
const nativeAuthMethod = user.getNativeAuthenticationMethod();
nativeAuthMethod.passwordResetToken =
await this.verificationTokenGenerator.generateVerificationToken();
await this.connection.getRepository(ctx, NativeAuthenticationMethod).save(nativeAuthMethod);
return user;
}
async resetPasswordByToken(
ctx: RequestContext,
passwordResetToken: string,
password: string,
): Promise<User | PasswordResetTokenExpiredError | PasswordResetTokenInvalidError> {
const user = await this.connection
.getRepository(ctx, User)
.createQueryBuilder('user')
.leftJoinAndSelect('user.authenticationMethods', 'authenticationMethod')
.where('authenticationMethod.passwordResetToken = :passwordResetToken', { passwordResetToken })
.getOne();
if (!user) {
return new PasswordResetTokenInvalidError();
}
if (this.verificationTokenGenerator.verifyVerificationToken(passwordResetToken)) {
const nativeAuthMethod = user.getNativeAuthenticationMethod();
nativeAuthMethod.passwordHash = await this.passwordCipher.hash(password);
nativeAuthMethod.passwordResetToken = null;
await this.connection.getRepository(ctx, NativeAuthenticationMethod).save(nativeAuthMethod);
return this.connection.getRepository(ctx, User).save(user);
} else {
return new PasswordResetTokenExpiredError();
}
}
/**
* Changes the User identifier without an email verification step, so this should be only used when
* an Administrator is setting a new email address.
*/
async changeNativeIdentifier(ctx: RequestContext, userId: ID, newIdentifier: string) {
const user = await this.getUserById(ctx, userId);
if (!user) {
return;
}
const nativeAuthMethod = user.getNativeAuthenticationMethod();
user.identifier = newIdentifier;
nativeAuthMethod.identifier = newIdentifier;
nativeAuthMethod.identifierChangeToken = null;
nativeAuthMethod.pendingIdentifier = null;
await this.connection
.getRepository(ctx, NativeAuthenticationMethod)
.save(nativeAuthMethod, { reload: false });
await this.connection.getRepository(ctx, User).save(user, { reload: false });
}
/**
* Changes the User identifier as part of the storefront flow used by Customers to set a
* new email address.
*/
async changeIdentifierByToken(
ctx: RequestContext,
token: string,
): Promise<
| { user: User; oldIdentifier: string }
| IdentifierChangeTokenInvalidError
| IdentifierChangeTokenExpiredError
> {
const user = await this.connection
.getRepository(ctx, User)
.createQueryBuilder('user')
.leftJoinAndSelect('user.authenticationMethods', 'authenticationMethod')
.where('authenticationMethod.identifierChangeToken = :identifierChangeToken', {
identifierChangeToken: token,
})
.getOne();
if (!user) {
return new IdentifierChangeTokenInvalidError();
}
if (!this.verificationTokenGenerator.verifyVerificationToken(token)) {
return new IdentifierChangeTokenExpiredError();
}
const nativeAuthMethod = user.getNativeAuthenticationMethod();
const pendingIdentifier = nativeAuthMethod.pendingIdentifier;
if (!pendingIdentifier) {
throw new InternalServerError('error.pending-identifier-missing');
}
const oldIdentifier = user.identifier;
user.identifier = pendingIdentifier;
nativeAuthMethod.identifier = pendingIdentifier;
nativeAuthMethod.identifierChangeToken = null;
nativeAuthMethod.pendingIdentifier = null;
await this.connection
.getRepository(ctx, NativeAuthenticationMethod)
.save(nativeAuthMethod, { reload: false });
await this.connection.getRepository(ctx, User).save(user, { reload: false });
return { user, oldIdentifier };
}
async updatePassword(
ctx: RequestContext,
userId: ID,
currentPassword: string,
newPassword: string,
): Promise<boolean | InvalidCredentialsError> {
const user = await this.connection
.getRepository(ctx, User)
.createQueryBuilder('user')
.leftJoinAndSelect('user.authenticationMethods', 'authenticationMethods')
.addSelect('authenticationMethods.passwordHash')
.where('user.id = :id', { id: userId })
.getOne();
if (!user) {
throw new EntityNotFoundError('User', userId);
}
const nativeAuthMethod = user.getNativeAuthenticationMethod();
const matches = await this.passwordCipher.check(currentPassword, nativeAuthMethod.passwordHash);
if (!matches) {
return new InvalidCredentialsError('');
}
nativeAuthMethod.passwordHash = await this.passwordCipher.hash(newPassword);
await this.connection
.getRepository(ctx, NativeAuthenticationMethod)
.save(nativeAuthMethod, { reload: false });
return true;
}
async setIdentifierChangeToken(ctx: RequestContext, user: User): Promise<User> {
const nativeAuthMethod = user.getNativeAuthenticationMethod();
nativeAuthMethod.identifierChangeToken = this.verificationTokenGenerator.generateVerificationToken();
await this.connection.getRepository(ctx, NativeAuthenticationMethod).save(nativeAuthMethod);
return user;
}
}