|
1 | | -import { Body, Controller, Post, Res, UnauthorizedException } from '@nestjs/common'; |
2 | | -import type { Response } from 'express'; |
| 1 | +import { Body, Controller, Get, Post, Req, Res, UnauthorizedException, UseGuards } from '@nestjs/common'; |
| 2 | +import type { Request, Response } from 'express'; |
3 | 3 | import { TelegramAuthService } from './telegram-auth.service'; |
4 | 4 | import { AuthService } from './auth.service'; |
5 | 5 | import { LoginDto } from './dto/login.dto'; |
6 | 6 | import { RegisterDto } from './dto/register.dto'; |
7 | 7 | import { Public } from '@common/decorators/public.decorator'; |
| 8 | +import { AuthGuard } from '@nestjs/passport'; |
8 | 9 |
|
9 | 10 | import { |
10 | 11 | AuthResponse, |
@@ -44,6 +45,52 @@ export class AuthController { |
44 | 45 | return { access_token }; |
45 | 46 | } |
46 | 47 |
|
| 48 | + @Public() |
| 49 | + @Post('refresh') |
| 50 | + async refresh(@Req() req: Request, @Res({ passthrough: true }) res: Response): Promise<AuthResponse> { |
| 51 | + const refreshToken = req.cookies?.refresh_token; |
| 52 | + if (!refreshToken) { |
| 53 | + throw new UnauthorizedException('No refresh token provided'); |
| 54 | + } |
| 55 | + |
| 56 | + const { access_token, refresh_token } = await this.authService.refreshToken(refreshToken); |
| 57 | + |
| 58 | + res.cookie('refresh_token', refresh_token, { |
| 59 | + httpOnly: true, |
| 60 | + secure: process.env.NODE_ENV === 'production', |
| 61 | + sameSite: 'strict', |
| 62 | + maxAge: 7 * 24 * 60 * 60 * 1000, |
| 63 | + }); |
| 64 | + |
| 65 | + return { access_token }; |
| 66 | + } |
| 67 | + |
| 68 | + @Public() |
| 69 | + @Get('google') |
| 70 | + @UseGuards(AuthGuard('google')) |
| 71 | + async googleAuth(@Req() req: Request) { |
| 72 | + // Initiates Google OAuth2 flow |
| 73 | + } |
| 74 | + |
| 75 | + @Public() |
| 76 | + @Get('google/callback') |
| 77 | + @UseGuards(AuthGuard('google')) |
| 78 | + async googleAuthRedirect(@Req() req: Request, @Res({ passthrough: true }) res: Response) { |
| 79 | + const user = await this.authService.validateGoogleUser(req.user); |
| 80 | + const { access_token, refresh_token } = await this.authService.googleLogin(user); |
| 81 | + |
| 82 | + res.cookie('refresh_token', refresh_token, { |
| 83 | + httpOnly: true, |
| 84 | + secure: process.env.NODE_ENV === 'production', |
| 85 | + sameSite: 'strict', |
| 86 | + maxAge: 7 * 24 * 60 * 60 * 1000, |
| 87 | + }); |
| 88 | + |
| 89 | + // Redirect to frontend with access token in query string or handle differently based on frontend setup |
| 90 | + // For now returning the token directly. |
| 91 | + res.redirect(`http://localhost:4200/auth/login?token=${access_token}`); |
| 92 | + } |
| 93 | + |
47 | 94 | @Post('telegram') |
48 | 95 | async telegramAuth( |
49 | 96 | @Body() body: { initData: string }, |
|
0 commit comments