feat(api-keys): add api keys management and authentication for n8n workflows
This commit is contained in:
1 parent
ba9472c938
commit
1fff11ee4f
24 files changed
+158204
-5768
No files matched your search
@@ -1,15 +1,17 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { Module, forwardRef } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { AuthService } from './auth.service';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { AdminModule } from '../admin/admin.module';
|
||||
import { getJwtSecret } from './auth.constants';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
UsersModule,
|
||||
forwardRef(() => AdminModule),
|
||||
PassportModule,
|
||||
JwtModule.registerAsync({
|
||||
useFactory: () => ({
|
||||
|
||||
@@ -1,8 +1,45 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import {
|
||||
Injectable,
|
||||
ExecutionContext,
|
||||
UnauthorizedException,
|
||||
Inject,
|
||||
forwardRef,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { ApiKeysService } from '../admin/api-keys.service';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||
constructor(
|
||||
@Inject(forwardRef(() => ApiKeysService))
|
||||
private readonly apiKeysService?: ApiKeysService,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const apiKeyHeader =
|
||||
request.headers['x-api-key'] ||
|
||||
(request.headers['authorization']?.startsWith('ApiKey ')
|
||||
? request.headers['authorization'].replace('ApiKey ', '').trim()
|
||||
: null);
|
||||
|
||||
if (apiKeyHeader && this.apiKeysService) {
|
||||
try {
|
||||
const apiKeyUser = await this.apiKeysService.validateKey(apiKeyHeader);
|
||||
request.user = apiKeyUser;
|
||||
return true;
|
||||
} catch (err: unknown) {
|
||||
throw new UnauthorizedException(
|
||||
(err as Error)?.message || 'کلید API نامعتبر است',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return super.canActivate(context) as Promise<boolean>;
|
||||
}
|
||||
|
||||
handleRequest<TUser = Record<string, unknown>>(
|
||||
err: unknown,
|
||||
user: TUser | false,
|
||||
@@ -10,7 +47,7 @@ export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||
if (err || !user) {
|
||||
throw (
|
||||
(err as Error) ||
|
||||
new UnauthorizedException('لطفا ابتدا وارد حساب کاربری خود شوید')
|
||||
new UnauthorizedException('لطفا ابتدا وارد حساب کاربری خود شوید یا API Key معتبر ارسال کنید')
|
||||
);
|
||||
}
|
||||
return user;
|
||||
|
||||
Reference in new issue
Block a user