|
1 | | -import { Body, Controller, Get, Logger, Post, Req, Res } from '@nestjs/common'; |
| 1 | +import { Body, Controller, Get, Logger, Post, Req, Res, UseGuards } from '@nestjs/common'; |
2 | 2 | import { Throttle } from '@nestjs/throttler'; |
3 | 3 | import { Request, Response } from 'express'; |
4 | 4 | import { AuthService } from './auth.service'; |
5 | 5 | import { RegisterDto } from './dto/register.dto'; |
6 | 6 | import { LoginDto } from './dto/login.dto'; |
7 | 7 | import { GoogleLoginDto } from './dto/google-login.dto'; |
| 8 | +import { GoogleOAuthGuard } from './guards/google-oauth.guard'; |
| 9 | +import { AppConfigService } from '../config/app-config.service'; |
8 | 10 |
|
9 | 11 | @Controller('auth') |
10 | 12 | export class AuthController { |
11 | 13 | private readonly logger = new Logger(AuthController.name); |
12 | 14 |
|
13 | | - constructor(private readonly authService: AuthService) {} |
| 15 | + constructor( |
| 16 | + private readonly authService: AuthService, |
| 17 | + private readonly config: AppConfigService, |
| 18 | + ) {} |
14 | 19 |
|
15 | 20 | @Get('csrf-token') |
16 | 21 | getCsrfToken(@Req() req: Request & { csrfToken?: () => string }) { |
@@ -45,6 +50,28 @@ export class AuthController { |
45 | 50 | return payload; |
46 | 51 | } |
47 | 52 |
|
| 53 | + @Get('google') |
| 54 | + @UseGuards(GoogleOAuthGuard) |
| 55 | + async googleAuth() { |
| 56 | + // Redirects to Google |
| 57 | + } |
| 58 | + |
| 59 | + @Get('google/callback') |
| 60 | + @UseGuards(GoogleOAuthGuard) |
| 61 | + async googleAuthRedirect(@Req() req: Request & { user: any }, @Res() res: Response) { |
| 62 | + this.logger.log(`GET /auth/google/callback email=${req.user.email}`); |
| 63 | + const payload = await this.authService.googleLogin({ |
| 64 | + email: req.user.email, |
| 65 | + name: req.user.name, |
| 66 | + avatarUrl: req.user.avatarUrl, |
| 67 | + }); |
| 68 | + this.authService.setRefreshTokenCookie(res, payload.refreshToken); |
| 69 | + |
| 70 | + // Redirect back to frontend dashboard |
| 71 | + const frontendUrl = this.config.corsOrigins[0]; // Usually the web frontend is first |
| 72 | + res.redirect(`${frontendUrl}/dashboard`); |
| 73 | + } |
| 74 | + |
48 | 75 | @Post('refresh') |
49 | 76 | async refresh(@Req() req: Request & { cookies?: Record<string, string> }, @Res({ passthrough: true }) res: Response) { |
50 | 77 | const token = req.cookies?.refresh_token; |
|
0 commit comments