diff --git a/src/authentication/extract-user.ts b/src/authentication/extract-user.ts new file mode 100644 index 0000000..96a3602 --- /dev/null +++ b/src/authentication/extract-user.ts @@ -0,0 +1,20 @@ +import jwt, { JwtPayload } from 'jsonwebtoken'; + +export function extractUserFrom(aRawJwt: string) { + const decodedToken = jwt.decode(aRawJwt, { + complete: true, + }); + + const payload = decodedToken.payload as JwtPayload; + + return { + user_id: payload.user_id, + username: payload.username, + permissions: payload.permissions, + customer_id: payload.customer_id, + customer_name: payload.customer_name, + customer_tier: payload.customer_tier, + customer_modules: payload.customer_modules, + access_token: aRawJwt, + } +} diff --git a/src/modules/mixpanel/mixpanel.controller.ts b/src/modules/mixpanel/mixpanel.controller.ts index 477569b..2b2d314 100644 --- a/src/modules/mixpanel/mixpanel.controller.ts +++ b/src/modules/mixpanel/mixpanel.controller.ts @@ -1,29 +1,46 @@ import { Body, Controller, Inject, Param, Post, Req } from '@nestjs/common'; -import { init } from 'mixpanel'; -import { Authenticated } from 'src/decorators/authentication.decorator'; import { ApiInternalOnlyController } from 'src/decorators/swagger.decorator'; -import { RequestUser, User } from 'src/decorators/user.decorator'; +import { RequestUser } from 'src/decorators/user.decorator'; import { MixpanelService } from './mixpanel.service'; +import { extractUserFrom } from 'src/authentication/extract-user'; +import DadosferaLogger from '@dadosfera/dadosfera-logs'; @ApiInternalOnlyController() @Controller('trackEvent') export class MixpanelController { + logger: DadosferaLogger; + constructor( - private mixpanelService: MixpanelService - ) {} + @Inject(DadosferaLogger) + dadosferaLogger: DadosferaLogger, + private mixpanelService: MixpanelService, + ) { + this.logger = dadosferaLogger.logger; + } + @Post(':id') async trackEvent( @Param('id') id, @Body() body, - @User() user: RequestUser, @Req() request ) { + this.logger.info(`POST Track Event: ${id}`) delete body.info; + + const anonymousUser = { + username: "anonymous", + customer_name: "anonymous" + } as RequestUser + + const hasToken = request.headers['authorization']; + + const user = hasToken ? extractUserFrom(hasToken) : anonymousUser; + + this.logger.info(`Has user: ${typeof hasToken == "string"}`) await this.mixpanelService.track(id, user, request, body) + this.logger.info(`Event successful`) return { id, body, user: user.username }; } - - }