/* eslint-disable @typescript-eslint/explicit-member-accessibility */ import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Body, Controller, Get, HttpException, HttpStatus, Inject, Post, Query, Req, Res, } from '@nestjs/common'; import { ApiResponse, ApiTags } from '@nestjs/swagger'; import axios from 'axios'; import { Cache } from 'cache-manager'; import { FastifyReply, FastifyRequest } from 'fastify'; import { cookieOptions } from 'src/config/cookie'; import { env } from 'src/config/env'; import { AuthToken } from 'src/decorators/token.decorator'; import { Credentials } from 'src/dto/credentials'; import { LdapController } from 'src/ldap/ldap.controller'; import { LdapService } from 'src/ldap/ldap.service'; import type { User } from 'src/utils/ldap'; @Controller('ldap-tfa') @ApiTags('ldap-tfa') export class LdapTfaController extends LdapController { constructor( protected readonly ldapService: LdapService, @Inject(CACHE_MANAGER) private readonly cacheManager: Cache ) { super(ldapService); } @Post('/login') @ApiResponse({ status: HttpStatus.OK, }) async login( @Body() credentials: Credentials, @Req() _req: FastifyRequest, @Res() reply: FastifyReply ) { try { const token = await this.ldapService.login(credentials, { audience: 'auth' }); const user = await this.ldapService.getUser(token); return reply.setCookie(env.COOKIE_TOKEN_NAME, token, cookieOptions).status(200).send(user); } catch { throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); } } @Post('/login-telegram') @ApiResponse({ status: HttpStatus.OK, }) async loginTelegram(@AuthToken() token: string, @Res() reply: FastifyReply) { const user = await this.ldapService.getUser(token); const authId = crypto.randomUUID(); const { employeeID } = user; // Change TTL this.cacheManager.set(authId, user); return axios .get(env.TELEGRAM_SERVICE_URL_SEND_MESSAGE, { params: { authId, employeeID, }, }) .then((res) => reply.status(200).send(res.data)) .catch((error) => reply.status(500).send(error)); } @Get('/telegram-confirm') @ApiResponse({ status: HttpStatus.OK, }) async telegramConfirm( @Query('authId') authId: string, @Query('employeeID') employeeID: string, @Res() reply: FastifyReply ) { const user = (await this.cacheManager.get(authId)) as User; // eslint-disable-next-line @typescript-eslint/no-unused-vars const token = await this.ldapService.login({ login: user.username }); return reply.status(200).send(); } @Get('/telegram-reject') @ApiResponse({ status: HttpStatus.OK, }) async telegramReject( @Query('authId') authId: string, @Query('employeeID') employeeID: string, @Res() reply: FastifyReply ) { return reply.status(200).send(); } }