diff --git a/packages/api/src/@core/auth/auth.service.ts b/packages/api/src/@core/auth/auth.service.ts index bb9ae6b85..5531de7c4 100644 --- a/packages/api/src/@core/auth/auth.service.ts +++ b/packages/api/src/@core/auth/auth.service.ts @@ -62,6 +62,16 @@ export class AuthService { } } + async validateUser(user_id: string) { + const user = await this.prisma.users.findUnique({ + where: { + id_user: user_id, + }, + }); + + return user; + } + async getApiKeys(project_id: string) { try { return await this.prisma.api_keys.findMany({ @@ -352,12 +362,10 @@ export class AuthService { async validateApiKey(apiKey: string): Promise { try { - // Decode the JWT to verify if it's valid and get the payload const decoded = this.jwtService.verify(apiKey, { secret: process.env.JWT_SECRET, }); - //const hashed_api_key = this.hashApiKey(apiKey); const saved_api_key = await this.prisma.api_keys.findUnique({ where: { api_key_hash: apiKey, @@ -365,30 +373,19 @@ export class AuthService { }); if (!saved_api_key) { - throw new ReferenceError('Api Key undefined'); - } - if (String(decoded.projectId) !== String(saved_api_key.id_project)) { - throw new ReferenceError( - 'Failed to validate API key: projectId mismatch.', - ); + return false; } - // Validate that the JWT payload matches the provided userId and projectId - if (String(decoded.sub) !== String(saved_api_key.id_user)) { - throw new ReferenceError( - 'Failed to validate API key: userId mismatch.', - ); + if ( + String(decoded.projectId) !== String(saved_api_key.id_project) || + String(decoded.sub) !== String(saved_api_key.id_user) + ) { + return false; } + return true; } catch (error) { - throwTypedError( - new AuthError({ - name: 'VALIDATE_API_KEY_ERROR', - message: 'AuthService.validateApiKey() call failed', - cause: error, - }), - this.logger, - ); + return false; } } } diff --git a/packages/api/src/@core/auth/strategies/auth-header-api-key.strategy.ts b/packages/api/src/@core/auth/strategies/auth-header-api-key.strategy.ts index c42b6e6cb..1e49c8765 100644 --- a/packages/api/src/@core/auth/strategies/auth-header-api-key.strategy.ts +++ b/packages/api/src/@core/auth/strategies/auth-header-api-key.strategy.ts @@ -1,6 +1,6 @@ -import { HeaderAPIKeyStrategy } from 'passport-headerapikey'; -import { PassportStrategy } from '@nestjs/passport'; import { Injectable, UnauthorizedException } from '@nestjs/common'; +import { PassportStrategy } from '@nestjs/passport'; +import { HeaderAPIKeyStrategy } from 'passport-headerapikey'; import { AuthService } from '../auth.service'; @Injectable() @@ -18,16 +18,15 @@ export class ApiKeyStrategy extends PassportStrategy( if (!isValid) { return done(new UnauthorizedException('Invalid API Key'), null); } - //console.log('validating api request... : ' + req.user); - // If the API key is valid, attach the user to the request object req.user = { ...req.user, apiKeyValidated: true }; - - // If valid, we now have the user info from the API key validation process return done(null, req.user); } catch (error) { - return done(error, false); + if (error instanceof UnauthorizedException) { + return done(error, false); + } + return done(new UnauthorizedException('Invalid API Key'), null); } }, ); } -} +} \ No newline at end of file diff --git a/packages/api/src/@core/auth/strategies/jwt.strategy.ts b/packages/api/src/@core/auth/strategies/jwt.strategy.ts index 6c3ea8926..057a4cbc4 100644 --- a/packages/api/src/@core/auth/strategies/jwt.strategy.ts +++ b/packages/api/src/@core/auth/strategies/jwt.strategy.ts @@ -1,12 +1,13 @@ import { ExtractJwt, Strategy } from 'passport-jwt'; import { PassportStrategy } from '@nestjs/passport'; -import { Injectable } from '@nestjs/common'; +import { Injectable, UnauthorizedException } from '@nestjs/common'; import * as dotenv from 'dotenv'; +import { AuthService } from '../auth.service'; dotenv.config(); @Injectable() export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') { - constructor() { + constructor(private authService: AuthService) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, @@ -15,6 +16,11 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') { } async validate(payload: any) { + const user = await this.authService.validateUser(payload.sub); + if (!user) { + throw new UnauthorizedException(); + } + return { id_user: payload.sub, email: payload.email,