-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth.controller.ts
More file actions
702 lines (638 loc) · 29.3 KB
/
auth.controller.ts
File metadata and controls
702 lines (638 loc) · 29.3 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
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
import {
BadRequestException,
Controller,
Get,
InternalServerErrorException,
Param,
Post,
Query,
Req,
Res,
UseGuards,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import type { Request, Response } from 'express';
import { SignupStep1Dto } from './dto/signup-step1.dto';
import { SignupStep2Dto } from './dto/signup-step2.dto';
import { SignupStep3Dto } from './dto/signup-step3.dto';
import { OAuthCompletionStep1Dto } from './dto/oauth-completion-step1.dto';
import { OAuthCompletionStep2Dto } from './dto/oauth-completion-step2.dto';
import { Body } from '@nestjs/common';
import { LoginDTO } from './dto/login.dto';
import { ChangePasswordAuthDTO } from './dto/change-password-auth.dto';
import { ResetPasswordDto } from './dto/reset-password.dto';
import { ResendOtpDto } from './dto/resend-otp.dto';
import { VerifyPasswordResetOtpDto } from './dto/verify-password-reset-otp.dto';
import { CheckIdentifierDto } from './dto/check-identifier.dto';
import { UpdateUsernameDto } from './dto/update-username.dto';
import { UpdateEmailDto } from './dto/update-email.dto';
import { VerifyUpdateEmailDto } from './dto/verify-update-email.dto';
import { MobileGoogleAuthDto } from './dto/mobile-google-auth.dto';
import { MobileGitHubAuthDto } from './dto/mobile-github-auth.dto';
import { ForgetPasswordDto } from './dto/forget-password.dto';
import { ExchangeTokenDto } from './dto/exchange-token.dto';
import {
ApiBearerAuth,
ApiBody,
ApiCookieAuth,
ApiCreatedResponse,
ApiOkResponse,
ApiOperation,
ApiParam,
ApiQuery,
ApiResponse,
ApiTags,
} from '@nestjs/swagger';
import { GitHubAuthGuard } from './guards/github.guard';
import { GoogleAuthGuard } from './guards/google-auth.guard';
import { FacebookAuthGuard } from './guards/facebook.guard';
import { JwtAuthGuard } from './guards/jwt.guard';
import { ResponseMessage } from 'src/decorators/response-message.decorator';
import { GetUserId } from 'src/decorators/get-userId.decorator';
import {
ApiBadRequestErrorResponse,
ApiConflictErrorResponse,
ApiForbiddenErrorResponse,
ApiInternalServerError,
ApiNotFoundErrorResponse,
ApiUnauthorizedErrorResponse,
ApiUnprocessableEntityErrorResponse,
} from 'src/decorators/swagger-error-responses.decorator';
import { ERROR_MESSAGES, SUCCESS_MESSAGES } from 'src/constants/swagger-messages';
import {
captcha_swagger,
change_password_swagger,
check_identifier_swagger,
confirm_password_swagger,
exchange_token_swagger,
facebook_callback_swagger,
facebook_oauth_swagger,
forget_password_swagger,
generate_otp_swagger,
github_callback_swagger,
github_mobile_swagger,
github_oauth_swagger,
google_callback_swagger,
google_mobile_swagger,
google_oauth_swagger,
login_swagger,
logout_all_swagger,
logout_swagger,
not_me_swagger,
oauth_completion_step1_swagger,
oauth_completion_step2_swagger,
refresh_token_swagger,
reset_password_swagger,
signup_step1_swagger,
signup_step2_swagger,
signup_step3_swagger,
update_email_swagger,
update_username_swagger,
verify_email_swagger,
verify_reset_otp_swagger,
verify_update_email_swagger,
} from './auth.swagger';
import { ConfirmPasswordDto } from './dto/confirm-password.dto';
import { RefreshTokenDto } from './dto/refresh-token.dto';
import { LogoutDto } from './dto/logout.dto';
@ApiTags('Authentication')
@Controller('auth')
export class AuthController {
constructor(private readonly auth_service: AuthService) {}
private httpOnlyRefreshToken(response: Response, refresh: string) {
const is_production = process.env.NODE_ENV === 'production';
response.cookie('refresh_token', refresh, {
httpOnly: true,
secure: true,
sameSite: is_production ? 'strict' : 'none',
maxAge: 7 * 24 * 60 * 60 * 1000,
});
}
@ApiOperation(signup_step1_swagger.operation)
@ApiBody({ type: SignupStep1Dto })
@ApiCreatedResponse(signup_step1_swagger.responses.success)
@ApiConflictErrorResponse(ERROR_MESSAGES.EMAIL_ALREADY_EXISTS)
@ApiInternalServerError(ERROR_MESSAGES.FAILED_TO_SEND_OTP_EMAIL)
@ResponseMessage(SUCCESS_MESSAGES.SIGNUP_STEP1_COMPLETED)
@Post('signup/step1')
async signupStep1(@Body() dto: SignupStep1Dto) {
return this.auth_service.signupStep1(dto);
}
@ApiOperation(signup_step2_swagger.operation)
@ApiBody({ type: SignupStep2Dto })
@ApiOkResponse(signup_step2_swagger.responses.success)
@ApiBadRequestErrorResponse(ERROR_MESSAGES.INVALID_OR_EXPIRED_TOKEN)
@ApiNotFoundErrorResponse(ERROR_MESSAGES.SIGNUP_SESSION_NOT_FOUND)
@ResponseMessage(SUCCESS_MESSAGES.SIGNUP_STEP2_COMPLETED)
@Post('signup/step2')
async signupStep2(@Body() dto: SignupStep2Dto) {
return this.auth_service.signupStep2(dto);
}
@ApiOperation(signup_step3_swagger.operation)
@ApiBody({ type: SignupStep3Dto })
@ApiCreatedResponse(signup_step3_swagger.responses.success)
@ApiNotFoundErrorResponse(ERROR_MESSAGES.SIGNUP_SESSION_NOT_FOUND)
@ApiConflictErrorResponse(ERROR_MESSAGES.USERNAME_ALREADY_TAKEN)
@ApiInternalServerError(ERROR_MESSAGES.FAILED_TO_SAVE_IN_DB)
@ResponseMessage(SUCCESS_MESSAGES.SIGNUP_STEP3_COMPLETED)
@Post('signup/step3')
async signupStep3(@Body() dto: SignupStep3Dto, @Res({ passthrough: true }) response: Response) {
const { user, access_token, refresh_token } = await this.auth_service.signupStep3(dto);
this.httpOnlyRefreshToken(response, refresh_token);
return { user, access_token, refresh_token };
}
@ApiOperation(login_swagger.operation)
@ApiBody({ type: LoginDTO })
@ApiOkResponse(login_swagger.responses.success)
@ApiUnauthorizedErrorResponse(ERROR_MESSAGES.WRONG_PASSWORD)
@ApiNotFoundErrorResponse(ERROR_MESSAGES.USER_NOT_FOUND)
@ApiForbiddenErrorResponse(ERROR_MESSAGES.EMAIL_NOT_VERIFIED)
@ResponseMessage(SUCCESS_MESSAGES.LOGGED_IN)
@Post('login')
async login(@Body() login_dto: LoginDTO, @Res({ passthrough: true }) response: Response) {
const { access_token, refresh_token, user } = await this.auth_service.login(login_dto);
this.httpOnlyRefreshToken(response, refresh_token);
return { user, access_token, refresh_token };
}
@ApiOperation(generate_otp_swagger.operation)
@ApiBody({ type: ResendOtpDto })
@ApiCreatedResponse(generate_otp_swagger.responses.success)
@ApiBadRequestErrorResponse(ERROR_MESSAGES.OTP_REQUEST_WAIT)
@ApiNotFoundErrorResponse(ERROR_MESSAGES.USER_NOT_FOUND_OR_VERIFIED)
@ApiInternalServerError(ERROR_MESSAGES.FAILED_TO_SEND_OTP_EMAIL)
@ResponseMessage(SUCCESS_MESSAGES.OTP_GENERATED)
@Post('resend-otp')
async generateEmailVerification(@Body() resend_otp_dto: ResendOtpDto) {
const { email } = resend_otp_dto;
return this.auth_service.generateEmailVerification(email);
}
@ApiOperation(not_me_swagger.operation)
@ApiQuery(not_me_swagger.api_query)
@ApiOkResponse(not_me_swagger.responses.success)
@ApiUnauthorizedErrorResponse(ERROR_MESSAGES.INVALID_OR_EXPIRED_TOKEN)
@ApiBadRequestErrorResponse(ERROR_MESSAGES.ACCOUNT_ALREADY_VERIFIED)
@ResponseMessage(SUCCESS_MESSAGES.ACCOUNT_REMOVED)
@Get('not-me')
async handleNotMe(@Query('token') token: string) {
return this.auth_service.handleNotMe(token);
}
@ApiBearerAuth('JWT-auth')
@UseGuards(JwtAuthGuard)
@ApiOperation(change_password_swagger.operation)
@ApiBody({ type: ChangePasswordAuthDTO })
@ApiOkResponse(change_password_swagger.responses.success)
@ApiBadRequestErrorResponse(ERROR_MESSAGES.PASSWORD_CONFIRMATION_MISMATCH)
@ApiUnauthorizedErrorResponse(ERROR_MESSAGES.WRONG_PASSWORD)
@ApiNotFoundErrorResponse(ERROR_MESSAGES.USER_NOT_FOUND)
@ResponseMessage(SUCCESS_MESSAGES.PASSWORD_CHANGED)
@Post('change-password')
async changePassword(@Body() body: ChangePasswordAuthDTO, @GetUserId() user_id: string) {
const { old_password, new_password } = body;
return this.auth_service.changePassword(user_id, old_password, new_password);
}
@ApiOperation(forget_password_swagger.operation)
@ApiBody({ type: ForgetPasswordDto })
@ApiOkResponse(forget_password_swagger.responses.success)
@ApiNotFoundErrorResponse(ERROR_MESSAGES.USER_NOT_FOUND)
@ApiInternalServerError(ERROR_MESSAGES.FAILED_TO_SEND_OTP_EMAIL)
@ResponseMessage(SUCCESS_MESSAGES.PASSWORD_RESET_OTP_SENT)
@Post('forget-password')
async forgetPassword(@Body() body: ForgetPasswordDto) {
return this.auth_service.sendResetPasswordEmail(body.identifier);
}
@ApiOperation(verify_reset_otp_swagger.operation)
@ApiBody({ type: VerifyPasswordResetOtpDto })
@ApiOkResponse(verify_reset_otp_swagger.responses.success)
@ApiNotFoundErrorResponse(ERROR_MESSAGES.USER_NOT_FOUND)
@ApiUnprocessableEntityErrorResponse(ERROR_MESSAGES.INVALID_OR_EXPIRED_TOKEN)
@ResponseMessage(SUCCESS_MESSAGES.OTP_VERIFIED)
@Post('password/verify-otp')
async verifyResetPasswordOtp(@Body() verify_password_reset_otp_dto: VerifyPasswordResetOtpDto) {
const { token, identifier } = verify_password_reset_otp_dto;
return this.auth_service.verifyResetPasswordOtp(identifier, token);
}
@ApiOperation(reset_password_swagger.operation)
@ApiBody({ type: ResetPasswordDto })
@ApiOkResponse(reset_password_swagger.responses.success)
@ApiBadRequestErrorResponse(ERROR_MESSAGES.NEW_PASSWORD_SAME_AS_OLD)
@ApiNotFoundErrorResponse(ERROR_MESSAGES.USER_NOT_FOUND)
@ApiUnauthorizedErrorResponse(ERROR_MESSAGES.INVALID_OR_EXPIRED_TOKEN)
@ResponseMessage(SUCCESS_MESSAGES.PASSWORD_RESET)
@Post('reset-password')
async resetPassword(@Body() body: ResetPasswordDto) {
const { new_password, reset_token, identifier } = body;
return this.auth_service.resetPassword(identifier, new_password, reset_token);
}
@ApiBearerAuth('JWT-auth')
@UseGuards(JwtAuthGuard)
@ApiOperation(logout_swagger.operation)
@ApiBody({ type: LogoutDto, required: false })
@ApiCookieAuth('refresh_token')
@ApiOkResponse(logout_swagger.responses.success)
@ApiBadRequestErrorResponse(ERROR_MESSAGES.NO_REFRESH_TOKEN_PROVIDED)
@ApiUnauthorizedErrorResponse(ERROR_MESSAGES.INVALID_OR_EXPIRED_TOKEN)
@ResponseMessage(SUCCESS_MESSAGES.LOGGED_OUT)
@Post('logout')
async logout(
@Body() body: LogoutDto,
@Req() req: Request,
@Res({ passthrough: true }) response: Response
) {
const refresh_token = body.refresh_token || req.cookies['refresh_token'];
if (!refresh_token) throw new BadRequestException('No refresh token provided');
return await this.auth_service.logout(refresh_token, response);
}
@ApiBearerAuth('JWT-auth')
@ApiCookieAuth('refresh_token')
@UseGuards(JwtAuthGuard)
@ApiOperation(logout_all_swagger.operation)
@ApiBody({ type: LogoutDto, required: false })
@ApiOkResponse(logout_all_swagger.responses.success)
@ApiBadRequestErrorResponse(ERROR_MESSAGES.NO_REFRESH_TOKEN_PROVIDED)
@ApiUnauthorizedErrorResponse(ERROR_MESSAGES.INVALID_OR_EXPIRED_TOKEN)
@ResponseMessage(SUCCESS_MESSAGES.LOGGED_OUT_ALL)
@Post('logout-all')
async logoutAll(
@Body() body: LogoutDto,
@Req() req: Request,
@Res({ passthrough: true }) response: Response
) {
const refresh_token = body.refresh_token || req.cookies['refresh_token'];
if (!refresh_token) throw new BadRequestException('No refresh token provided');
return await this.auth_service.logoutAll(refresh_token, response);
}
@ApiOperation(refresh_token_swagger.operation)
@ApiBody({ type: RefreshTokenDto, required: false })
@ApiCookieAuth('refresh_token')
@ApiOkResponse(refresh_token_swagger.responses.success)
@ApiBadRequestErrorResponse(ERROR_MESSAGES.NO_REFRESH_TOKEN_PROVIDED)
@ApiUnauthorizedErrorResponse(ERROR_MESSAGES.INVALID_OR_EXPIRED_TOKEN)
@ResponseMessage(SUCCESS_MESSAGES.NEW_ACCESS_TOKEN)
@Post('refresh')
async refresh(
@Body() body: RefreshTokenDto,
@Req() req: Request,
@Res({ passthrough: true }) response: Response
) {
const refresh_token_input = body.refresh_token || req.cookies['refresh_token'];
if (!refresh_token_input) throw new BadRequestException('No refresh token provided');
const { access_token, refresh_token } =
await this.auth_service.refresh(refresh_token_input);
this.httpOnlyRefreshToken(response, refresh_token);
return { access_token, refresh_token };
}
@ApiOperation(exchange_token_swagger.operation)
@ApiBody({ type: ExchangeTokenDto })
@ApiOkResponse(exchange_token_swagger.responses.completion_success)
@ApiUnauthorizedErrorResponse(ERROR_MESSAGES.INVALID_OR_EXPIRED_TOKEN)
@ResponseMessage(SUCCESS_MESSAGES.TOKEN_EXCHANGE_SUCCESS)
@Post('exchange-token')
async exchangeToken(@Body() body: ExchangeTokenDto, @Res() res: Response) {
const { exchange_token } = body;
const payload = await this.auth_service.validateExchangeToken(exchange_token);
if (payload.type === 'auth') {
if (!payload.user_id) {
throw new BadRequestException(ERROR_MESSAGES.INVALID_OR_EXPIRED_TOKEN);
}
const { access_token, refresh_token } = await this.auth_service.generateTokens(
payload.user_id
);
this.httpOnlyRefreshToken(res, refresh_token);
return res.json({
type: 'auth',
access_token,
});
} else {
return res.json({
type: 'completion',
session_token: payload.session_token,
});
}
}
@ApiOperation(captcha_swagger.operation)
@ApiResponse(captcha_swagger.responses.success)
@ResponseMessage('ReCAPTCHA site key retrieved successfully')
@Get('captcha/site-key')
getCaptchaSiteKey() {
return {
siteKey: process.env.RECAPTCHA_SITE_KEY || '',
};
}
@ApiOperation(check_identifier_swagger.operation)
@ApiBody({ type: CheckIdentifierDto })
@ApiOkResponse(check_identifier_swagger.responses.success)
@ApiNotFoundErrorResponse(ERROR_MESSAGES.USERNAME_NOT_FOUND)
@ResponseMessage(SUCCESS_MESSAGES.IDENTIFIER_AVAILABLE)
@Post('check-identifier')
async checkIdentifier(@Body() dto: CheckIdentifierDto) {
const { identifier } = dto;
return this.auth_service.checkIdentifier(identifier);
}
@ApiBearerAuth('JWT-auth')
@UseGuards(JwtAuthGuard)
@ApiOperation(update_username_swagger.operation)
@ApiBody({ type: UpdateUsernameDto })
@ApiOkResponse(update_username_swagger.responses.success)
@ApiUnauthorizedErrorResponse(ERROR_MESSAGES.INVALID_OR_EXPIRED_TOKEN)
@ApiConflictErrorResponse(ERROR_MESSAGES.USERNAME_ALREADY_TAKEN)
@ApiNotFoundErrorResponse(ERROR_MESSAGES.USER_NOT_FOUND)
@ResponseMessage(SUCCESS_MESSAGES.USERNAME_UPDATED)
@Post('update-username')
async updateUsername(@Body() dto: UpdateUsernameDto, @GetUserId() user_id: string) {
return this.auth_service.updateUsername(user_id, dto.username);
}
@ApiBearerAuth('JWT-auth')
@UseGuards(JwtAuthGuard)
@ApiOperation(update_email_swagger.operation)
@ApiBody({ type: UpdateEmailDto })
@ApiOkResponse(update_email_swagger.responses.success)
@ApiUnauthorizedErrorResponse(ERROR_MESSAGES.INVALID_OR_EXPIRED_TOKEN)
@ApiConflictErrorResponse(ERROR_MESSAGES.EMAIL_ALREADY_EXISTS)
@ApiNotFoundErrorResponse(ERROR_MESSAGES.USER_NOT_FOUND)
@ApiInternalServerError(ERROR_MESSAGES.FAILED_TO_SEND_OTP_EMAIL)
@ResponseMessage(SUCCESS_MESSAGES.EMAIL_UPDATE_INITIATED)
@Post('update-email')
async updateEmail(@Body() dto: UpdateEmailDto, @GetUserId() user_id: string) {
return this.auth_service.updateEmail(user_id, dto.new_email);
}
@ApiBearerAuth('JWT-auth')
@UseGuards(JwtAuthGuard)
@ApiOperation(verify_update_email_swagger.operation)
@ApiBody({ type: VerifyUpdateEmailDto })
@ApiOkResponse(verify_update_email_swagger.responses.success)
@ApiUnauthorizedErrorResponse(ERROR_MESSAGES.INVALID_OR_EXPIRED_TOKEN)
@ApiBadRequestErrorResponse(ERROR_MESSAGES.INVALID_OR_EXPIRED_TOKEN)
@ApiNotFoundErrorResponse(ERROR_MESSAGES.USER_NOT_FOUND)
@ResponseMessage(SUCCESS_MESSAGES.EMAIL_UPDATED)
@Post('update-email/verify')
async verifyUpdateEmail(@Body() dto: VerifyUpdateEmailDto, @GetUserId() user_id: string) {
return this.auth_service.verifyUpdateEmail(user_id, dto.otp);
}
/*
######################### Google OAuth Routes #########################
*/
@UseGuards(GoogleAuthGuard)
@ApiOperation(google_oauth_swagger.operation)
@ApiResponse(google_oauth_swagger.responses.success)
@ApiResponse(google_oauth_swagger.responses.InternalServerError)
@Get('google')
// eslint-disable-next-line @typescript-eslint/no-empty-function
googleLogin() {} // Intentionally empty - GoogleAuthGuard handles the OAuth redirect
@ApiOperation(google_mobile_swagger.operation)
@ApiBody({ type: MobileGoogleAuthDto })
@ApiOkResponse(google_mobile_swagger.responses.success)
@ApiUnauthorizedErrorResponse(ERROR_MESSAGES.GOOGLE_TOKEN_INVALID)
@ApiBadRequestErrorResponse(ERROR_MESSAGES.EMAIL_NOT_PROVIDED_BY_OAUTH_GOOGLE)
@ResponseMessage(SUCCESS_MESSAGES.LOGGED_IN)
@Post('mobile/google')
async mobileGoogleAuth(
@Body() dto: MobileGoogleAuthDto,
@Res({ passthrough: true }) response: Response
) {
const result = await this.auth_service.verifyGoogleMobileToken(
dto.code,
dto.redirect_uri,
dto.code_verifier
);
// Check if user needs to complete OAuth registration
if ('needs_completion' in result && result.needs_completion) {
const session_token = await this.auth_service.createOAuthSession(result.user);
return {
needs_completion: true,
session_token: session_token,
provider: 'google',
};
}
if (!('user' in result) || !('id' in result.user)) {
throw new BadRequestException(ERROR_MESSAGES.GOOGLE_TOKEN_INVALID);
}
const user = result.user;
const { access_token, refresh_token } = await this.auth_service.generateTokens(user.id);
this.httpOnlyRefreshToken(response, refresh_token);
return {
access_token,
refresh_token,
user: user,
};
}
@UseGuards(GoogleAuthGuard)
@ApiOperation(google_callback_swagger.operation)
@ApiResponse(google_callback_swagger.responses.success)
@ApiResponse(google_callback_swagger.responses.AuthFail)
@Get('google/callback')
async googleLoginCallback(@Req() req, @Res() res) {
try {
// if the user doesn't have a record for that email in DB, we will need to redirect the user to complete his data
if (req.user?.needs_completion) {
const session_token = await this.auth_service.createOAuthSession(req.user.user);
const exchange_token = await this.auth_service.createExchangeToken({
session_token,
type: 'completion',
});
return res.redirect(
`${process.env.FRONTEND_URL || 'http://localhost:3001'}/auth/oauth-complete?exchange_token=${encodeURIComponent(exchange_token)}&provider=google`
);
}
// Check if user authentication failed but no completion required
if (!req.user) {
console.log('Google authentication failed - no user found');
return res.redirect(
`${process.env.FRONTEND_URL || 'http://localhost:3001'}/auth/error?message=Authentication%20failed`
);
}
// Normal OAuth flow for existing users
// Create secure exchange token with user_id (tokens will be generated on exchange)
const exchange_token = await this.auth_service.createExchangeToken({
user_id: req.user.id,
type: 'auth',
});
// Redirect to frontend with exchange token
const frontend_url = `${process.env.FRONTEND_URL || 'http://localhost:3001'}/auth/success?exchange_token=${encodeURIComponent(exchange_token)}&provider=google`;
return res.redirect(frontend_url);
} catch (error) {
console.log('Google callback error:', error);
return res.redirect(
`${process.env.FRONTEND_URL || 'http://localhost:3001'}/auth/error?message=Authentication%20failed`
);
}
}
/*
######################### Facebook OAuth Routes #########################
*/
@UseGuards(FacebookAuthGuard)
@ApiOperation(facebook_oauth_swagger.operation)
@ApiResponse(facebook_oauth_swagger.responses.success)
@ApiResponse(facebook_oauth_swagger.responses.InternalServerError)
@Get('facebook')
// eslint-disable-next-line @typescript-eslint/no-empty-function
facebookLogin() {} // Intentionally empty - FacebookAuthGuard handles the OAuth redirect
@UseGuards(FacebookAuthGuard)
@ApiOperation(facebook_callback_swagger.operation)
@ApiResponse(facebook_callback_swagger.responses.success)
@ApiResponse(facebook_callback_swagger.responses.AuthFail)
@Get('facebook/callback')
async facebookLoginCallback(@Req() req, @Res() res) {
try {
// if the user doesn't have a record for that email in DB, we will need to redirect the user to complete his data
if (req.user?.needs_completion) {
const session_token = await this.auth_service.createOAuthSession(req.user.user);
const exchange_token = await this.auth_service.createExchangeToken({
session_token,
type: 'completion',
});
return res.redirect(
`${process.env.FRONTEND_URL || 'http://localhost:3001'}/auth/oauth-complete?exchange_token=${encodeURIComponent(exchange_token)}&provider=facebook`
);
}
// Check if user authentication failed but no completion required
if (!req.user) {
console.log('Facebook authentication failed - no user found');
return res.redirect(
`${process.env.FRONTEND_URL || 'http://localhost:3001'}/auth/error?message=Authentication%20failed`
);
}
// Normal OAuth flow for existing users
const exchange_token = await this.auth_service.createExchangeToken({
user_id: req.user.id,
type: 'auth',
});
// Redirect to frontend with exchange token
const frontend_url = `${process.env.FRONTEND_URL || 'http://localhost:3001'}/auth/success?exchange_token=${encodeURIComponent(exchange_token)}&provider=facebook`;
return res.redirect(frontend_url);
} catch (error) {
console.log('Facebook callback error:', error);
return res.redirect(
`${process.env.FRONTEND_URL || 'http://localhost:3001'}/auth/error?message=Authentication%20failed`
);
}
}
/*
######################### GitHub OAuth Routes #########################
*/
@UseGuards(GitHubAuthGuard)
@ApiOperation(github_oauth_swagger.operation)
@ApiResponse(github_oauth_swagger.responses.success)
@ApiResponse(github_oauth_swagger.responses.InternalServerError)
@Get('github')
// eslint-disable-next-line @typescript-eslint/no-empty-function
async githubLogin() {} // Intentionally empty - GitHubAuthGuard handles the OAuth redirect
@ApiOperation(github_mobile_swagger.operation)
@ApiBody({ type: MobileGitHubAuthDto })
@ApiOkResponse(github_mobile_swagger.responses.success)
@ApiUnauthorizedErrorResponse(ERROR_MESSAGES.GITHUB_TOKEN_INVALID)
@ApiBadRequestErrorResponse(ERROR_MESSAGES.EMAIL_NOT_PROVIDED_BY_OAUTH_GITHUB)
@ResponseMessage(SUCCESS_MESSAGES.LOGGED_IN)
@Post('mobile/github')
async mobileGitHubAuth(
@Body() dto: MobileGitHubAuthDto,
@Res({ passthrough: true }) response: Response
) {
const result = await this.auth_service.verifyGitHubMobileToken(
dto.code,
dto.redirect_uri,
dto.code_verifier
);
if ('needs_completion' in result && result.needs_completion) {
const session_token = await this.auth_service.createOAuthSession(result.user);
return {
needs_completion: true,
session_token: session_token,
provider: 'github',
};
}
if (!('user' in result) || !('id' in result.user)) {
throw new BadRequestException(ERROR_MESSAGES.GITHUB_TOKEN_INVALID);
}
const user = result.user;
const { access_token, refresh_token } = await this.auth_service.generateTokens(user.id);
this.httpOnlyRefreshToken(response, refresh_token);
return {
access_token,
refresh_token,
user: user,
};
}
@UseGuards(GitHubAuthGuard)
@ApiOperation(github_callback_swagger.operation)
@ApiResponse(github_callback_swagger.responses.success)
@ApiResponse(github_callback_swagger.responses.AuthFail)
@Get('github/callback')
async githubCallback(@Req() req: any, @Res() res: Response) {
try {
// if the user doesn't have a record for that email in DB, we will need to redirect the user to complete his data
if (req.user?.needs_completion) {
const session_token = await this.auth_service.createOAuthSession(req.user.user);
const exchange_token = await this.auth_service.createExchangeToken({
session_token,
type: 'completion',
});
return res.redirect(
`${process.env.FRONTEND_URL || 'http://localhost:3001'}/auth/oauth-complete?exchange_token=${encodeURIComponent(exchange_token)}&provider=github`
);
}
// Check if user authentication failed but no completion required
if (!req.user) {
console.log('GitHub authentication failed - no user found');
return res.redirect(
`${process.env.FRONTEND_URL || 'http://localhost:3001'}/auth/error?message=Authentication%20failed`
);
}
// Normal OAuth flow for existing users
const exchange_token = await this.auth_service.createExchangeToken({
user_id: req.user.id,
type: 'auth',
});
// Redirect to frontend with exchange token
const frontend_url = `${process.env.FRONTEND_URL || 'http://localhost:3001'}/auth/success?exchange_token=${encodeURIComponent(exchange_token)}&provider=github`;
return res.redirect(frontend_url);
} catch (error) {
console.log('Github callback error:', error);
return res.redirect(
`${process.env.FRONTEND_URL || 'http://localhost:3001'}/auth/error?message=Authentication%20failed`
);
}
}
// ###################### OAUTH COMPLETION FLOW ######################
@ApiOperation(oauth_completion_step1_swagger.operation)
@ApiBody({ type: OAuthCompletionStep1Dto })
@ApiOkResponse(oauth_completion_step1_swagger.responses.success)
@ApiNotFoundErrorResponse(ERROR_MESSAGES.INVALID_OAUTH_SESSION_TOKEN)
@ResponseMessage(SUCCESS_MESSAGES.BIRTH_DATE_SET)
@Post('oauth/complete/step1')
async oauthCompletionStep1(@Body() dto: OAuthCompletionStep1Dto) {
return this.auth_service.oauthCompletionStep1(dto);
}
@ApiOperation(oauth_completion_step2_swagger.operation)
@ApiBody({ type: OAuthCompletionStep2Dto })
@ApiCreatedResponse(oauth_completion_step2_swagger.responses.success)
@ApiConflictErrorResponse(ERROR_MESSAGES.USERNAME_ALREADY_TAKEN)
@ApiNotFoundErrorResponse(ERROR_MESSAGES.INVALID_OAUTH_SESSION_TOKEN)
@ResponseMessage(SUCCESS_MESSAGES.OAUTH_USER_REGISTERED)
@Post('oauth/complete/step2')
async oauthCompletionStep2(
@Body() dto: OAuthCompletionStep2Dto,
@Res({ passthrough: true }) response: Response
) {
const { access_token, refresh_token, user } =
await this.auth_service.oauthCompletionStep2(dto);
this.httpOnlyRefreshToken(response, refresh_token);
return { access_token, refresh_token, user };
}
@ApiBearerAuth('JWT-auth')
@UseGuards(JwtAuthGuard)
@ApiOperation(confirm_password_swagger.operation)
@ApiBody({ type: ConfirmPasswordDto })
@ApiOkResponse(confirm_password_swagger.responses.success)
@ApiUnauthorizedErrorResponse(ERROR_MESSAGES.INVALID_OR_EXPIRED_TOKEN)
@ApiForbiddenErrorResponse(ERROR_MESSAGES.WRONG_PASSWORD)
@ApiConflictErrorResponse(ERROR_MESSAGES.ACCOUNT_HAS_NO_PASSWORD)
@ApiNotFoundErrorResponse(ERROR_MESSAGES.USER_NOT_FOUND)
@ResponseMessage(SUCCESS_MESSAGES.PASSWORD_CONFIRMED)
@Post('confirm-password')
async confirmPassword(
@Body() confirm_password_dto: ConfirmPasswordDto,
@GetUserId() user_id: string
) {
return this.auth_service.confirmPassword(confirm_password_dto, user_id);
}
}