import { Controller, Get, Redirect, Req, UseGuards } from '@nestjs/common'; import { ApiTags } from '@nestjs/swagger'; import { AuthGuard } from '@nestjs/passport'; import { ConnectionClientService } from '../connection/client.service'; import jwt from 'jsonwebtoken'; import DadosferaLogger from '@dadosfera/dadosfera-logs/dist'; import { PackTheMetadata } from 'src/utils/ PackTheMetadata'; import { ApiInternalOnlyEndpoint } from 'src/decorators/swagger.decorator'; @ApiTags('oauth') @Controller('oauth') export class OauthController { redirectUrl: string; constructor( private connectionService: ConnectionClientService, private logger: DadosferaLogger, ) { switch (process.env.ENV) { case 'stg': this.redirectUrl = `https://app.${process.env.ENV}.dadosfera.ai/collect/auth-callback`; break; case 'prd': this.redirectUrl = `https://app.dadosfera.ai/collect/auth-callback`; break; default: this.redirectUrl = `http://localhost:4200/collect/auth-callback`; } } @Get('hubspot') @UseGuards(AuthGuard('hubspot')) async oauthHubspot() { return true; } @ApiInternalOnlyEndpoint() @Get('hubspot/callback') @UseGuards(AuthGuard('hubspot')) @Redirect() async oauthHubspotCallback(@Req() req) { return await this.callback(req); } @Get('googleads') @UseGuards(AuthGuard('google')) async oauthGoogleAds() { return true; } @ApiInternalOnlyEndpoint() @Get('googleads/callback') @UseGuards(AuthGuard('google')) @Redirect() async oauthGoogleAdsCallback(@Req() req) { return await this.callback(req); } @Get('google-sheets') @UseGuards(AuthGuard('google')) async oauthGoogleSheets() { return true; } @ApiInternalOnlyEndpoint() @Get('google-sheets/callback') @UseGuards(AuthGuard('google')) @Redirect() async oauthGoogleSheetsCallback(@Req() req) { return await this.callback(req); } @Get('facebook') @UseGuards(AuthGuard('facebook')) async oauthFacebook() { return true; } @ApiInternalOnlyEndpoint() @Get('facebook/callback') @UseGuards(AuthGuard('facebook')) @Redirect() async oauthFacebookCallback(@Req() req) { return await this.callback(req); } @Get('mailchimp') @UseGuards(AuthGuard('mailchimp')) async oauthMailchimp() { return true; } @ApiInternalOnlyEndpoint() @Get('mailchimp/callback') @UseGuards(AuthGuard('mailchimp')) @Redirect() async oauthMailchimpCallback(@Req() req) { return await this.callback(req); } @Get('salesforce') @UseGuards(AuthGuard('salesforce')) async oauthSalesforce() { return true; } @ApiInternalOnlyEndpoint() @Get('salesforce/callback') @UseGuards(AuthGuard('salesforce')) @Redirect() async oauthSalesforceCallback(@Req() req) { return await this.callback(req); } async callback(@Req() req) { const { error, state } = req.query; const url = new URL(this.redirectUrl); if (error) { this.logger.error(error); url.searchParams.set('error', 'Erro ao autorizar'); url.searchParams.set( 'error_description', `Credenciais inválidas. Erro: [${error}]`, ); return { url: url.href }; } const { authInfo } = req; if (!authInfo) { this.logger.error('No authInfo', req); url.searchParams.set('error', 'Erro ao autorizar'); url.searchParams.set('error_description', `Credenciais inválidas.`); return { url: url.href }; } const { accessToken: access_token, refreshToken: refresh_token } = authInfo; let connectionInfo: any; try { connectionInfo = jwt.verify(state as string, process.env.JWT_PRIVATE_KEY); } catch (error) { this.logger.error('Invalid state JWT', { state, req, error }); url.searchParams.set('error', 'Erro ao autorizar'); url.searchParams.set( 'error_description', 'Ocorreu um erro ao autorizá-lo. Por favor tente novamente', ); return { url: url.href }; } connectionInfo.properties.access_token = access_token; connectionInfo.properties.refresh_token = refresh_token; const { customer_id, customer_name, user_id } = connectionInfo; try { const response = connectionInfo.id ? await this.connectionService.updateConnection( connectionInfo.id, connectionInfo, PackTheMetadata({ customer_id, customer_name, user_id }), ) : await this.connectionService.createConnection( connectionInfo, PackTheMetadata({ customer_id, customer_name, user_id }), ); url.searchParams.set('connection_id', response.connection.id); return { url: url.href }; } catch (error) { this.logger.error(error); url.searchParams.set('error', 'Erro ao autorizar'); url.searchParams.set( 'error_description', 'Ocorreu um erro interno ao autorizá-lo. Por favor tente novamente mais tarde', ); return { url: url.href }; } } }