import { BadRequestException, Body, Controller, Get, HttpStatus, Post, Req, Res, UseGuards, } from '@nestjs/common'; import { LoginService } from '../service/login.service'; import { GoogleAuthGuard } from '../../../module/auth/guards/google-auth.guard'; import { JwtAuthGuard } from '../../auth/guards/jwt.guard'; import { Request, Response } from 'express'; import { UserSessionService } from '../service/user-session.service'; import { ConfigService } from '@nestjs/config'; import { IntegrationService } from '../../integration/service/integration.service'; @Controller('auth') export class LoginController { constructor( private loginService: LoginService, private userSessionService: UserSessionService, private configService: ConfigService, private integrationService: IntegrationService, ) {} @Post('login') async login(@Body() body, @Res() res: Response) { const { email_id, password, subdomain } = body; const result = await this.loginService.login({ email_id, password, is_otp: false, // default since you had it before subdomain, }); return res.status(HttpStatus.OK).json(result); } @Post('form-login') async formLogin(@Body() body, @Res() res: Response) { const result = await this.loginService.formLogin(body); return res.status(HttpStatus.OK).json(result); } @UseGuards(JwtAuthGuard) @Post('logout') async logout( @Req() request: Request & { user: any }, @Res() response: Response, ) { const requestUser: any = request.user.userData; response .status(HttpStatus.OK) .json(await this.loginService.logout(requestUser.sessionToken)); } @Get('google') @UseGuards(GoogleAuthGuard) async googleLogin() { // Passport automatically redirects to Google } @Get('google/callback') @UseGuards(GoogleAuthGuard) async googleAuthRedirect(@Req() req: any, @Res() res: Response) { const { email, name, accessToken: googleAccessToken, refreshToken: googleRefreshToken, } = req.user; const { state } = req.query; // Check if this is a Gmail configuration request if ( state && typeof state === 'string' && state.startsWith('gmail_config:') ) { try { // Extract the actual state from the prefixed state const actualState = state.replace('gmail_config:', ''); // Forward to communication service for Gmail config handling using already exchanged tokens const result = await this.integrationService.handleGmailTokensCallback( email, googleAccessToken, googleRefreshToken, actualState, name, ); return res.send( `

Configuration successful. You can close this window.

`, ); } catch (error) { return res.send(`

Configuration failed. Please close this window.

`); } } // Original login flow const data = await this.loginService.loginWithGoogle({ email, }); if (!('accessToken' in data) || !data.accessToken) return res.redirect( `${this.configService.get('BASE_URL')}/auth?email=${email}&error='User not found'`, ); const profile = this.configService.get('PROFILE'); const { accessToken, appcode } = data; if (profile && profile === 'dev') { return res.redirect( `${this.configService.get('DOMAIN_URL')}/auth?token=${accessToken}&appcode=${appcode}`, ); } else { if (data.slug) { return res.redirect( `https://${data.slug}.${this.configService.get('DOMAIN_URL')}/auth?token=${accessToken}&appcode=${appcode}`, ); } } return res.redirect( `${this.configService.get('DOMAIN_URL')}/auth?token=${accessToken}&appcode=${appcode}`, ); } @UseGuards(JwtAuthGuard) @Post('switch') async switchCurrentLevel( @Req() req: Request & { user: any }, @Body() data: { level_id: string; level_type: string; appcode: string; }, ): Promise { const currentUser = req.user.userData; const currentAppcode = currentUser.appcode; // If appcode is changing, validate the new level_id/level_type if (data.appcode !== currentAppcode) { const isValidAccess = await this.userSessionService.checkIfUserHasMapping( currentUser.id, data.appcode, data.level_type, data.level_id, ); if (!isValidAccess) { // If not valid, fetch the default one const userMapping = await this.userSessionService.getUserRoleMappingForApp( currentUser.id, data.appcode, ); if (!userMapping) { throw new BadRequestException( `No mapping found for user in app ${data.appcode}`, ); } data.level_type = userMapping.level_type; data.level_id = userMapping.level_id; } } return await this.userSessionService.switchCurrentLevelService( currentUser, data, ); } }