import { Body, Controller, Get, HttpCode, Post, Req, Res } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import type { InfoConexion, UsuarioSesion } from '@dp/shared'; import type { Request, Response } from 'express'; import { AppConfig } from '../config/configuration.js'; import { ServiceLayerClient } from '../service-layer/service-layer.client.js'; import { SessionStore } from '../service-layer/session.store.js'; import { VERSION_APP } from '../version.js'; import type { SapSession } from '../service-layer/session.store.js'; import { LoginDto } from './dto/login.dto.js'; import { CurrentSession, Public, SESSION_COOKIE } from './session.guard.js'; function aUsuario(sesion: SapSession): UsuarioSesion { return { userName: sesion.userName, companyDb: sesion.companyDb, version: sesion.version, app: VERSION_APP }; } @Controller('auth') export class AuthController { constructor( private readonly serviceLayer: ServiceLayerClient, private readonly sessions: SessionStore, private readonly config: ConfigService, ) {} @Public() @Get('info') info(): InfoConexion { return { companyDb: this.config.get('serviceLayer', { infer: true }).companyDb, dbType: this.config.get('dbType', { infer: true }), app: VERSION_APP, }; } @Public() @Post('login') @HttpCode(200) async login(@Body() dto: LoginDto, @Res({ passthrough: true }) res: Response): Promise { const sesion = await this.serviceLayer.login(dto.userName, dto.password); res.cookie(SESSION_COOKIE, sesion.id, { httpOnly: true, sameSite: 'strict', secure: this.config.get('cookieSecure', { infer: true }), path: '/', }); return aUsuario(sesion); } @Public() @Post('logout') @HttpCode(204) async logout(@Req() req: Request, @Res({ passthrough: true }) res: Response): Promise { const sesion = this.sessions.obtener(req.cookies?.[SESSION_COOKIE] as string | undefined); if (sesion) { await this.serviceLayer.logout(sesion); } res.clearCookie(SESSION_COOKIE, { path: '/' }); } @Get('me') me(@CurrentSession() sesion: SapSession): UsuarioSesion { return aUsuario(sesion); } }