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
@@ -15,6 +15,8 @@ import { PetsController } from './pets.controller';
|
||||
import { PetsService } from './pets.service';
|
||||
import { SslController } from './ssl.controller';
|
||||
import { SslService } from './ssl.service';
|
||||
import { ApiKeysController } from './api-keys.controller';
|
||||
import { ApiKeysService } from './api-keys.service';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
import { RedisModule } from '../redis/redis.module';
|
||||
|
||||
@@ -29,6 +31,7 @@ import { RedisModule } from '../redis/redis.module';
|
||||
WikiController,
|
||||
PetsController,
|
||||
SslController,
|
||||
ApiKeysController,
|
||||
],
|
||||
providers: [
|
||||
AdminService,
|
||||
@@ -39,6 +42,8 @@ import { RedisModule } from '../redis/redis.module';
|
||||
WikiService,
|
||||
PetsService,
|
||||
SslService,
|
||||
ApiKeysService,
|
||||
],
|
||||
exports: [ApiKeysService],
|
||||
})
|
||||
export class AdminModule {}
|
||||
@@ -0,0 +1,67 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Delete,
|
||||
Patch,
|
||||
Body,
|
||||
Param,
|
||||
UseGuards,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { ApiKeysService } from './api-keys.service';
|
||||
import { CreateApiKeyDto } from './dto/api-key.dto';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse } from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Admin - مدیریت کلیدهای دسترسی (API Keys)')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('admin/api-keys')
|
||||
export class ApiKeysController {
|
||||
constructor(private readonly apiKeysService: ApiKeysService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'دریافت لیست کلیدهای دسترسی API' })
|
||||
@ApiResponse({ status: HttpStatus.OK, description: 'لیست کلیدها با موفقیت دریافت شد' })
|
||||
async findAll() {
|
||||
const keys = await this.apiKeysService.findAll();
|
||||
return {
|
||||
success: true,
|
||||
data: keys,
|
||||
};
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'ایجاد یک API Key جدید' })
|
||||
@ApiResponse({ status: HttpStatus.CREATED, description: 'کلید جدید با موفقیت ایجاد شد' })
|
||||
async create(@Body() dto: CreateApiKeyDto) {
|
||||
const result = await this.apiKeysService.create(dto);
|
||||
return {
|
||||
success: true,
|
||||
message: 'کلید دسترسی با موفقیت ایجاد شد. لطفاً آن را در جای امن ذخیره نمایید.',
|
||||
data: result,
|
||||
};
|
||||
}
|
||||
|
||||
@Patch(':id/toggle')
|
||||
@ApiOperation({ summary: 'تغییر وضعیت فعال/غیرفعال کلید' })
|
||||
async toggleStatus(@Param('id') id: string) {
|
||||
const updated = await this.apiKeysService.toggleStatus(id);
|
||||
return {
|
||||
success: true,
|
||||
message: 'وضعیت کلید با موفقیت بهروزرسانی شد',
|
||||
data: updated,
|
||||
};
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@ApiOperation({ summary: 'حذف کلید دسترسی' })
|
||||
async delete(@Param('id') id: string) {
|
||||
await this.apiKeysService.delete(id);
|
||||
return {
|
||||
success: true,
|
||||
message: 'کلید دسترسی با موفقیت حذف شد',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { CreateApiKeyDto } from './dto/api-key.dto';
|
||||
import * as crypto from 'crypto';
|
||||
|
||||
@Injectable()
|
||||
export class ApiKeysService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
private hashKey(key: string): string {
|
||||
return crypto.createHash('sha256').update(key).digest('hex');
|
||||
}
|
||||
|
||||
async findAll() {
|
||||
const keys = await this.prisma.apiKey.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
keyPrefix: true,
|
||||
scopes: true,
|
||||
status: true,
|
||||
description: true,
|
||||
expiresAt: true,
|
||||
lastUsedAt: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
return keys.map((k) => ({
|
||||
...k,
|
||||
scopes: k.scopes ? k.scopes.split(',').map((s) => s.trim()) : ['*'],
|
||||
isExpired: k.expiresAt ? new Date(k.expiresAt) < new Date() : false,
|
||||
}));
|
||||
}
|
||||
|
||||
async create(dto: CreateApiKeyDto) {
|
||||
// Generate secure random key: cn_live_<32 hex chars>
|
||||
const randomBytes = crypto.randomBytes(24).toString('hex');
|
||||
const rawKey = `cn_live_${randomBytes}`;
|
||||
const keyPrefix = rawKey.substring(0, 12);
|
||||
const keyHash = this.hashKey(rawKey);
|
||||
|
||||
const scopesStr = dto.scopes && dto.scopes.length > 0 ? dto.scopes.join(',') : '*';
|
||||
|
||||
const apiKey = await this.prisma.apiKey.create({
|
||||
data: {
|
||||
name: dto.name,
|
||||
keyHash,
|
||||
keyPrefix,
|
||||
scopes: scopesStr,
|
||||
description: dto.description || null,
|
||||
expiresAt: dto.expiresAt ? new Date(dto.expiresAt) : null,
|
||||
status: 'ACTIVE',
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
keyPrefix: true,
|
||||
scopes: true,
|
||||
status: true,
|
||||
description: true,
|
||||
expiresAt: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
apiKey: {
|
||||
...apiKey,
|
||||
scopes: apiKey.scopes.split(','),
|
||||
},
|
||||
rawKey, // Return raw secret only once upon creation
|
||||
};
|
||||
}
|
||||
|
||||
async toggleStatus(id: string) {
|
||||
const key = await this.prisma.apiKey.findUnique({ where: { id } });
|
||||
if (!key) {
|
||||
throw new NotFoundException('کلید یافت نشد');
|
||||
}
|
||||
|
||||
const nextStatus = key.status === 'ACTIVE' ? 'REVOKED' : 'ACTIVE';
|
||||
const updated = await this.prisma.apiKey.update({
|
||||
where: { id },
|
||||
data: { status: nextStatus },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
keyPrefix: true,
|
||||
scopes: true,
|
||||
status: true,
|
||||
expiresAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
...updated,
|
||||
scopes: updated.scopes.split(','),
|
||||
};
|
||||
}
|
||||
|
||||
async delete(id: string) {
|
||||
const key = await this.prisma.apiKey.findUnique({ where: { id } });
|
||||
if (!key) {
|
||||
throw new NotFoundException('کلید یافت نشد');
|
||||
}
|
||||
|
||||
await this.prisma.apiKey.delete({ where: { id } });
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
async validateKey(rawKey: string) {
|
||||
if (!rawKey || typeof rawKey !== 'string' || !rawKey.startsWith('cn_live_')) {
|
||||
throw new UnauthorizedException('API Key نامعتبر است');
|
||||
}
|
||||
|
||||
const keyHash = this.hashKey(rawKey);
|
||||
const key = await this.prisma.apiKey.findUnique({
|
||||
where: { keyHash },
|
||||
});
|
||||
|
||||
if (!key) {
|
||||
throw new UnauthorizedException('API Key یافت نشد یا معتبر نیست');
|
||||
}
|
||||
|
||||
if (key.status !== 'ACTIVE') {
|
||||
throw new UnauthorizedException('این API Key باطل یا غیرفعال شده است');
|
||||
}
|
||||
|
||||
if (key.expiresAt && new Date(key.expiresAt) < new Date()) {
|
||||
throw new UnauthorizedException('این API Key منقضی شده است');
|
||||
}
|
||||
|
||||
// Update lastUsedAt asynchronously in background
|
||||
this.prisma.apiKey
|
||||
.update({
|
||||
where: { id: key.id },
|
||||
data: { lastUsedAt: new Date() },
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
return {
|
||||
id: key.id,
|
||||
name: key.name,
|
||||
role: 'ADMIN', // Grants admin level access for n8n automation
|
||||
email: 'apikey-system@canina.ir',
|
||||
scopes: key.scopes.split(',').map((s) => s.trim()),
|
||||
isApiKey: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { IsString, IsNotEmpty, IsOptional, IsArray } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class CreateApiKeyDto {
|
||||
@ApiProperty({ description: 'نام یا شناسه کلید', example: 'ورکفلو هماهنگی سفارشات n8n' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'توضیحات تکمیلی درباره کلید', example: 'استفاده در وبهوک سفارشات' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'سطوح دسترسی (scopes)', example: ['orders:read', 'orders:write'] })
|
||||
@IsArray()
|
||||
@IsOptional()
|
||||
scopes?: string[];
|
||||
|
||||
@ApiPropertyOptional({ description: 'تاریخ انقضا به فرمت ISO (در صورت خالی بودن، بدون انقضا خواهد بود)', example: '2026-12-31T23:59:59.000Z' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
expiresAt?: string;
|
||||
}
|
||||
Reference in new issue
Block a user