Evo.Auth/apps/api/src/app.controller.ts

52 lines
1.5 KiB
TypeScript

import { AppService } from './app.service';
import { AuthParams, Params } from './decorators/auth-mode.decorator';
import { AuthToken } from './decorators/token.decorator';
import { Controller, Get, HttpStatus, Req, Res } from '@nestjs/common';
import { ApiExcludeController, ApiResponse } from '@nestjs/swagger';
import { FastifyReply, FastifyRequest } from 'fastify';
@Controller()
@ApiExcludeController()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('auth')
public async auth(
@Req() req: FastifyRequest,
@Res() reply: FastifyReply,
@AuthToken() token: string,
@AuthParams() { authMode }: Params
) {
try {
const { aud } = this.appService.checkToken(token);
const originalUri = req.headers['x-original-uri'];
if (
authMode === 'ldap-tfa' &&
aud === 'auth' &&
!['/auth', '/login', '/socket.io'].some((x) => originalUri.includes(x))
) {
return reply.status(HttpStatus.UNAUTHORIZED).send();
}
reply.header('Authorization', `Bearer ${token}`);
return reply.send();
} catch (error) {
return reply.status(HttpStatus.UNAUTHORIZED).send({ message: error.message });
}
}
@Get('/check-auth')
@ApiResponse({
status: HttpStatus.OK,
})
public async checkAuth(
@AuthParams() { authMode }: Params,
@Req() req: FastifyRequest,
@Res() reply: FastifyReply
) {
return reply.redirect(308, `${req.protocol}://${req.headers.host}/${authMode}/check-auth`);
}
}