security: AuthGuard classe sur controllers + @Public() decorator pour search
This commit is contained in:
@@ -4,7 +4,9 @@ import {
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { IS_PUBLIC_KEY } from './public.decorator';
|
||||
|
||||
interface CacheEntry {
|
||||
user: any;
|
||||
@@ -17,9 +19,18 @@ const TOKEN_CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
|
||||
export class AuthGuard implements CanActivate {
|
||||
private readonly cache = new Map<string, CacheEntry>();
|
||||
|
||||
constructor(private readonly configService: ConfigService) {}
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly reflector: Reflector,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (isPublic) return true;
|
||||
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const token = this.extractToken(request);
|
||||
|
||||
|
||||
4
backend/src/auth/public.decorator.ts
Normal file
4
backend/src/auth/public.decorator.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const IS_PUBLIC_KEY = 'isPublic';
|
||||
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||
@@ -2,12 +2,12 @@ import { Controller, Get, Req, UseGuards } from '@nestjs/common';
|
||||
import { UserService } from './user.service';
|
||||
import { AuthGuard } from '../auth/auth.guard';
|
||||
|
||||
@UseGuards(AuthGuard)
|
||||
@Controller('api/user')
|
||||
export class UserController {
|
||||
constructor(private readonly userService: UserService) {}
|
||||
|
||||
@Get('me')
|
||||
@UseGuards(AuthGuard)
|
||||
async me(@Req() req: any) {
|
||||
const user = await this.userService.findOrCreate({
|
||||
id: req.user.id,
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { Controller, Get, Query } from '@nestjs/common';
|
||||
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
|
||||
import { AuthGuard } from '../auth/auth.guard';
|
||||
import { Public } from '../auth/public.decorator';
|
||||
import { WorkService } from './work.service';
|
||||
|
||||
@UseGuards(AuthGuard)
|
||||
@Controller('api/works')
|
||||
export class WorkController {
|
||||
constructor(private readonly workService: WorkService) {}
|
||||
|
||||
@Public()
|
||||
@Get('search')
|
||||
async search(
|
||||
@Query('q') query: string,
|
||||
|
||||
Reference in New Issue
Block a user