-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
user.service.ts
339 lines (293 loc) · 7.71 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
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
import {
ConflictException,
Inject,
Injectable,
Logger,
UnauthorizedException
} from '@nestjs/common'
import { UpdateUserDto } from '../dto/update.user/update.user'
import { AuthProvider, User } from '@prisma/client'
import { PrismaService } from '../../prisma/prisma.service'
import { CreateUserDto } from '../dto/create.user/create.user'
import {
IMailService,
MAIL_SERVICE
} from '../../mail/services/interface.service'
import createUser from '../../common/create-user'
import generateOtp from '../../common/generate-otp'
import { EnvSchema } from '../../common/env/env.schema'
@Injectable()
export class UserService {
private readonly log = new Logger(UserService.name)
constructor(
private readonly prisma: PrismaService,
@Inject(MAIL_SERVICE) private readonly mailService: IMailService
) {}
async onApplicationBootstrap() {
await this.checkIfAdminExistsOrCreate()
}
async getSelf(user: User) {
return user
}
async updateSelf(user: User, dto: UpdateUserDto) {
const data = {
name: dto?.name,
profilePictureUrl: dto?.profilePictureUrl,
isOnboardingFinished: dto.isOnboardingFinished
}
if (dto?.email) {
const userExists =
(await this.prisma.user.count({
where: {
email: dto.email
}
})) > 0
if (userExists) {
throw new ConflictException('User with this email already exists')
}
const otp = await generateOtp(user.email, user.id, this.prisma)
await this.prisma.userEmailChange.upsert({
where: {
otpId: otp.id
},
update: {
newEmail: dto.email
},
create: {
newEmail: dto.email,
otpId: otp.id
}
})
await this.mailService.sendEmailChangedOtp(dto.email, otp.code)
}
this.log.log(`Updating user ${user.id} with data ${dto}`)
const updatedUser = await this.prisma.user.update({
where: {
id: user.id
},
data
})
return updatedUser
}
async updateUser(userId: string, dto: UpdateUserDto) {
const data = {
name: dto.name,
profilePictureUrl: dto.profilePictureUrl,
isAdmin: dto.isAdmin,
isActive: dto.isActive,
isOnboardingFinished: dto.isOnboardingFinished
}
if (dto.email) {
const userExists =
(await this.prisma.user.count({
where: {
email: dto.email
}
})) > 0
if (userExists) {
throw new ConflictException('User with this email already exists')
}
//directly updating email when admin triggered
await this.prisma.user.update({
where: {
id: userId
},
data: {
email: dto.email,
authProvider: AuthProvider.EMAIL_OTP
}
})
}
this.log.log(`Updating user ${userId} with data ${dto}`)
return await this.prisma.user.update({
where: {
id: userId
},
data
})
}
async validateEmailChangeOtp(user: User, otpCode: string): Promise<User> {
const otp = await this.prisma.otp.findUnique({
where: {
userId: user.id,
code: otpCode
}
})
if (!otp || otp.expiresAt < new Date()) {
this.log.log(`OTP expired or invalid`)
throw new UnauthorizedException('Invalid or expired OTP')
}
const userEmailChange = await this.prisma.userEmailChange.findUnique({
where: {
otpId: otp.id
}
})
const deleteEmailChangeRecord = this.prisma.userEmailChange.delete({
where: {
otpId: otp.id
}
})
const deleteOtp = this.prisma.otp.delete({
where: {
userId: user.id,
code: otpCode
}
})
const updateUserOp = this.prisma.user.update({
where: {
id: user.id
},
data: {
email: userEmailChange.newEmail,
authProvider: AuthProvider.EMAIL_OTP
}
})
this.log.log(
`Changing email to ${userEmailChange.newEmail} for user ${user.id}`
)
const results = await this.prisma.$transaction([
deleteEmailChangeRecord,
deleteOtp,
updateUserOp
])
return results[2]
}
async resendEmailChangeOtp(user: User) {
const oldOtp = await this.prisma.otp.findUnique({
where: {
userId: user.id
},
include: {
emailChange: true
}
})
if (!oldOtp?.emailChange) {
throw new ConflictException(
`No previous OTP for email change exists for user ${user.id}`
)
}
const newOtp = await generateOtp(user.email, user.id, this.prisma)
await this.mailService.sendEmailChangedOtp(
oldOtp.emailChange.newEmail,
newOtp.code
)
}
async getUserById(userId: string) {
return await this.prisma.user.findUnique({
where: {
id: userId
}
})
}
async getAllUsers(
page: number,
limit: number,
sort: string,
order: string,
search: string
): Promise<User[]> {
return await this.prisma.user.findMany({
skip: (page - 1) * limit,
take: limit,
orderBy: {
[sort]: order
},
where: {
OR: [
{
name: {
contains: search
}
},
{
email: {
contains: search
}
}
]
}
})
}
async deleteSelf(user: User) {
this.deleteUserById(user.id)
}
async deleteUser(userId: User['id']) {
this.deleteUserById(userId)
}
private async deleteUserById(userId: User['id']) {
await this.prisma.$transaction([
// Delete the user
this.prisma.user.delete({
where: {
id: userId
}
}),
// Delete the default workspace of this user
this.prisma.workspace.deleteMany({
where: {
ownerId: userId,
isDefault: true
}
})
])
this.log.log(`Deleted user ${userId}`)
}
async createUser(user: CreateUserDto) {
this.log.log(`Creating user with email ${user.email}`)
// Check for duplicate user
const checkDuplicateUser =
(await this.prisma.user.count({
where: {
email: user.email
}
})) > 0
if (checkDuplicateUser) {
throw new ConflictException('User already exists with this email')
}
// Create the user's default workspace along with user
const userWithWorkspace = await createUser(
{ authProvider: AuthProvider.EMAIL_OTP, ...user },
this.prisma
)
this.log.log(`Created user with email ${user.email}`)
await this.mailService.accountLoginEmail(userWithWorkspace.email)
this.log.log(`Sent login email to ${user.email}`)
return userWithWorkspace
}
private async checkIfAdminExistsOrCreate() {
const parsedEnv = EnvSchema.safeParse(process.env)
let nodeEnv
if (!parsedEnv.success) {
nodeEnv = 'dev' // Default to a valid value or handle appropriately
} else {
nodeEnv = parsedEnv.data.NODE_ENV
}
if (nodeEnv === 'test' || nodeEnv === 'e2e') {
return
}
const adminExists =
(await this.prisma.user.count({
where: {
isAdmin: true
}
})) > 0
if (!adminExists) {
this.log.warn('No admin user found', 'UserService')
this.log.log('Creating admin user', 'UserService')
// Create the admin user
const adminUser = await this.prisma.user.create({
data: {
name: 'Admin',
email: process.env.ADMIN_EMAIL,
isAdmin: true,
isActive: true,
isOnboardingFinished: true
}
})
await this.mailService.adminUserCreateEmail(adminUser.email)
this.log.log('Created admin user', 'UserService')
return
}
this.log.log('Admin user found', 'UserService')
}
}