Skip to content

Commit

Permalink
Fix api key error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
mohamedsalem401 committed Jun 19, 2024
1 parent 760c574 commit 96667fb
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 29 deletions.
29 changes: 8 additions & 21 deletions packages/api/src/@core/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -362,43 +362,30 @@ export class AuthService {

async validateApiKey(apiKey: string): Promise<boolean> {
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,
},
});

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;
}
}
}
Original file line number Diff line number Diff line change
@@ -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()
Expand All @@ -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);
}
},
);
}
}
}

0 comments on commit 96667fb

Please sign in to comment.