2026-04-15-1 dashboard
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { ScheduleModule } from '@nestjs/schedule';
|
||||
@@ -25,7 +26,7 @@ import { ThrottlerModule } from '@nestjs/throttler';
|
||||
}),
|
||||
}),
|
||||
ThrottlerModule.forRoot([{
|
||||
ttl: 60,
|
||||
ttl: 60000,
|
||||
limit: 10, // Default fallback limit
|
||||
}]),
|
||||
AuthModule,
|
||||
@@ -33,5 +34,6 @@ import { ThrottlerModule } from '@nestjs/throttler';
|
||||
MapsModule,
|
||||
GeocodingModule,
|
||||
],
|
||||
providers: [],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Tenant } from './entities/tenant.entity';
|
||||
import { ApiKey } from './entities/api-key.entity';
|
||||
import { RedisModule } from '../common/redis.module';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { TenantController } from './tenant.controller';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
@@ -12,6 +13,7 @@ import { ConfigService } from '@nestjs/config';
|
||||
TypeOrmModule.forFeature([Tenant, ApiKey]),
|
||||
RedisModule,
|
||||
],
|
||||
controllers: [TenantController],
|
||||
providers: [AuthService],
|
||||
exports: [AuthService],
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Injectable, UnauthorizedException, Logger } from '@nestjs/common';
|
||||
import { Injectable, UnauthorizedException, Logger, NotFoundException, ConflictException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { createHash } from 'crypto';
|
||||
@@ -124,4 +124,44 @@ export class AuthService {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all API keys for a specific tenant
|
||||
*/
|
||||
async getApiKeys(tenantId: string): Promise<ApiKey[]> {
|
||||
return this.apiKeyRepository.find({
|
||||
where: { tenantId },
|
||||
order: { createdAt: 'DESC' }
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new API key for a tenant
|
||||
*/
|
||||
async createApiKey(tenantId: string, name: string, rateLimit?: number, allowedOrigins?: string[]): Promise<ApiKey> {
|
||||
const existingKeysCount = await this.apiKeyRepository.count({ where: { tenantId } });
|
||||
if (existingKeysCount >= 1) {
|
||||
throw new ConflictException('Limit reached: Only 1 API key allowed per developer currently.');
|
||||
}
|
||||
|
||||
const key = `in_${createHash('md5').update(Math.random().toString()).digest('hex').substring(0, 24)}`;
|
||||
|
||||
const apiKey = this.apiKeyRepository.create({
|
||||
key,
|
||||
secretHash: this.hashSecret(key),
|
||||
name,
|
||||
tenantId,
|
||||
rateLimit: rateLimit || 100,
|
||||
allowedOrigins: allowedOrigins || [],
|
||||
isActive: true
|
||||
});
|
||||
|
||||
return this.apiKeyRepository.save(apiKey);
|
||||
}
|
||||
|
||||
async getDefaultTenant(): Promise<Tenant> {
|
||||
const tenant = await this.tenantRepository.findOne({ where: {} });
|
||||
if (!tenant) throw new NotFoundException('No tenants found in system');
|
||||
return tenant;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { IsString, IsOptional, IsNumber, IsArray } from 'class-validator';
|
||||
|
||||
export class CreateKeyDto {
|
||||
@IsString()
|
||||
name: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
rateLimit?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
allowedOrigins?: string[];
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Controller, Get, Post, Body, Param } from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { CreateKeyDto } from './dto/management/create-key.dto';
|
||||
import { ApiTags, ApiOperation } from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('auth')
|
||||
@Controller('auth/management')
|
||||
export class TenantController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@Get('keys/:tenantId')
|
||||
@ApiOperation({ summary: 'Get all API keys for a tenant' })
|
||||
async getKeys(@Param('tenantId') tenantId: string) {
|
||||
return this.authService.getApiKeys(tenantId);
|
||||
}
|
||||
|
||||
@Post('keys/:tenantId')
|
||||
@ApiOperation({ summary: 'Create a new API key' })
|
||||
async createKey(
|
||||
@Param('tenantId') tenantId: string,
|
||||
@Body() dto: CreateKeyDto
|
||||
) {
|
||||
return this.authService.createApiKey(
|
||||
tenantId,
|
||||
dto.name,
|
||||
dto.rateLimit,
|
||||
dto.allowedOrigins
|
||||
);
|
||||
}
|
||||
|
||||
@Get('me')
|
||||
@ApiOperation({ summary: 'Identify the default tenant (Demo Only)' })
|
||||
async getMe() {
|
||||
return this.authService.getDefaultTenant();
|
||||
}
|
||||
}
|
||||
@@ -1,34 +1,31 @@
|
||||
import { Injectable, ExecutionContext } from '@nestjs/common';
|
||||
import { Injectable, ExecutionContext, Logger } from '@nestjs/common';
|
||||
import { ThrottlerGuard, ThrottlerRequest } from '@nestjs/throttler';
|
||||
|
||||
@Injectable()
|
||||
export class TenantThrottlerGuard extends ThrottlerGuard {
|
||||
/**
|
||||
* Resolve per-tenant and per-key rate limits dynamically
|
||||
* تحديد حدود الاستخدام لكل مستخدم (Tenant) بشكل ديناميكي
|
||||
*/
|
||||
private readonly logger = new Logger(TenantThrottlerGuard.name);
|
||||
|
||||
protected async getTracker(req: Record<string, any>): Promise<string> {
|
||||
// Collect tracker info from the request (attached by ApiKeyGuard)
|
||||
const apiKeyId = req['apiKey']?.id || req.ip;
|
||||
return `throttler:key:${apiKeyId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* NestJS Throttler v6+: Override handleRequest to inject dynamic limits
|
||||
*/
|
||||
protected async handleRequest(
|
||||
requestProps: ThrottlerRequest,
|
||||
): Promise<boolean> {
|
||||
const { context, limit } = requestProps;
|
||||
const { context, limit, ttl } = requestProps;
|
||||
const request = context.switchToHttp().getRequest();
|
||||
|
||||
// Read dynamic limit from request metadata (set in ApiKeyGuard)
|
||||
const dynamicLimit = request['rateLimit'] || limit;
|
||||
const dynamicLimit = request['rateLimit'];
|
||||
|
||||
// Update the limit in the request properties before passing to super
|
||||
requestProps.limit = dynamicLimit;
|
||||
if (dynamicLimit) {
|
||||
this.logger.debug(`Applying dynamic rate limit: ${dynamicLimit} req/min for key ${request['apiKey']?.id}`);
|
||||
requestProps.limit = dynamicLimit;
|
||||
} else {
|
||||
this.logger.debug(`Applying default rate limit: ${limit} req/min`);
|
||||
}
|
||||
|
||||
// Proceed with standard throttler logic
|
||||
return super.handleRequest(requestProps);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ import helmet from 'helmet';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
const app = await NestFactory.create(AppModule, {
|
||||
logger: ['error', 'warn', 'log', 'debug', 'verbose'],
|
||||
});
|
||||
|
||||
// 1. Modern Security Headers (Prevention of XSS, Clickjacking, etc.)
|
||||
app.use(helmet());
|
||||
|
||||
Reference in New Issue
Block a user