Skip to content

Commit

Permalink
(#136) adiciona autenticacao
Browse files Browse the repository at this point in the history
  • Loading branch information
HenriqueAmorim20 committed Oct 24, 2023
1 parent d43bb5f commit 1b5acd5
Show file tree
Hide file tree
Showing 7 changed files with 86 additions and 2 deletions.
4 changes: 4 additions & 0 deletions .env.development
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@ DB_USERNAME=postgres
DB_PASS=postgres
DB_DATABASE=gerocuidado-forum-db
DB_PORT=5002

## TCP
AUTH_HOST=gerocuidado-usuario-api
AUTH_PORT=4001
4 changes: 4 additions & 0 deletions .env.test
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@ DB_USERNAME=postgres
DB_PASS=postgres
DB_DATABASE=gerocuidado-forum-db-test
DB_PORT=5002

## TCP
AUTH_HOST=gerocuidado-usuario-api
AUTH_PORT=4001
4 changes: 4 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ services:
- gerocuidado-forum-db
networks:
- gerocuidado-forum-net
- gerocuidado-apis-net

gerocuidado-forum-db:
build:
Expand All @@ -36,3 +37,6 @@ services:
networks:
gerocuidado-forum-net:
driver: bridge
gerocuidado-apis-net:
name: gerocuidado-apis-net
external: true
2 changes: 2 additions & 0 deletions src/app.controler.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { PublicRoute } from './shared/decorators/public-route.decorator';

@Controller()
export class AppController {
constructor(private readonly service: AppService) {}

@Get('health-check')
@PublicRoute()
heathCheck() {
return this.service.heathCheck();
}
Expand Down
27 changes: 25 additions & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { APP_GUARD } from '@nestjs/core';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controler';
import { AppService } from './app.service';
import { AutenticacaoGuard } from './autenticacao.guard';
import { DbModule } from './config/db/db.module';
import { DbService } from './config/db/db.service';

Expand All @@ -18,9 +21,29 @@ const ENV = process.env.NODE_ENV;
imports: [ConfigModule, DbModule],
useClass: DbService,
}),
ClientsModule.registerAsync([
{
name: 'AUTH_CLIENT',
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
transport: Transport.TCP,
options: {
host: configService.get('AUTH_HOST'),
port: configService.get('AUTH_PORT'),
},
}),
inject: [ConfigService],
},
]),
DbModule,
],
controllers: [AppController],
providers: [AppService],
providers: [
AppService,
{
provide: APP_GUARD,
useClass: AutenticacaoGuard,
},
],
})
export class AppModule {}
43 changes: 43 additions & 0 deletions src/autenticacao.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import {
CanActivate,
ExecutionContext,
Inject,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ClientProxy } from '@nestjs/microservices';
import { lastValueFrom, timeout } from 'rxjs';
import { IS_PUBLIC_KEY } from './shared/decorators/public-route.decorator';

@Injectable()
export class AutenticacaoGuard implements CanActivate {
constructor(
@Inject('AUTH_CLIENT')
private readonly _client: ClientProxy,
private readonly _reflector: Reflector,
) {}

async canActivate(context: ExecutionContext) {
const req = context.switchToHttp().getRequest();
const jwt = req.headers['authorization']?.split(' ')[1];

const isPublic = this._reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);

if (isPublic) return true;

const request = this._client
.send({ role: 'auth', cmd: 'check' }, { jwt })
.pipe(timeout(5000));
const response = await lastValueFrom(request);

if (!response) {
throw new UnauthorizedException('Usuário não autenticado!');
}

return true;
}
}
4 changes: 4 additions & 0 deletions src/shared/decorators/public-route.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { SetMetadata } from '@nestjs/common';

export const IS_PUBLIC_KEY = 'isPublic';
export const PublicRoute = () => SetMetadata(IS_PUBLIC_KEY, true);

0 comments on commit 1b5acd5

Please sign in to comment.