import { BadRequestException, Controller, Get, Redirect, Req, UseGuards, } from '@nestjs/common'; import { ApiTags } from '@nestjs/swagger'; import { AuthGuard } from '@nestjs/passport'; import { InputsClientService } from 'src/clients/inputs/client.service'; import { InputsService } from '../inputs/inputs.service'; import { Request } from 'express'; @ApiTags('oauth') @Controller('oauth') export class OauthController { inputService: InputsService; frontendRedirectUri = ''; constructor(private inputsClientService: InputsClientService) { this.inputService = new InputsService(this.inputsClientService); switch (process.env.ENV) { case 'dev': case 'stg': this.frontendRedirectUri = `https://app.${process.env.ENV}.dadosfera.ai/coletix/auth-callback`; break; case 'prd': this.frontendRedirectUri = `https://app.dadosfera.ai/coletix/auth-callback`; break; default: this.frontendRedirectUri = `http://localhost:4200/coletix/auth-callback`; } } @Get('hubspot') @UseGuards(AuthGuard('hubspot')) async oauthHubspot() { return true; } @Get('hubspot/callback') @UseGuards(AuthGuard('hubspot')) @Redirect() async oauthHubspotCallback(@Req() req) { return await this.callback(req, 'hubspot'); } @Get('google') @UseGuards(AuthGuard('google')) async oauthGoogle() { return true; } @Get('google/callback') @UseGuards(AuthGuard('google')) @Redirect() async oauthGoogleCallback(@Req() req) { return await this.callback(req, 'google'); } @Get('facebook') @UseGuards(AuthGuard('facebook')) async oauthFacebook() { return true; } @Get('facebook/callback') @UseGuards(AuthGuard('facebook')) @Redirect() async oauthFacebookCallback(@Req() req) { return await this.callback(req, 'facebook'); } async callback(@Req() req, plugin) { const { authInfo } = req; const request: Request = req; if (!authInfo) throw new BadRequestException('Oauth tokens not found'); const { accessToken: access_token, refreshToken: refresh_token } = authInfo; const { state: customer_id } = request.query; const response = await this.inputService.create({ info: { customer_id, customer: 'customer', user_id: 'empty' }, plugin, credentials: { access_token, refresh_token }, }); return { url: `${this.frontendRedirectUri}?input_id=${response.input.id}` }; } }