detrash / recy-network

Recy Network is a solution of recycling and composting for humanity to live in a world free of waste in nature!
https://recy.life
MIT License
3 stars 1 forks source link

API Key #69

Open yurimutti opened 1 month ago

yurimutti commented 1 month ago

Step-by-Step Guide

  1. Set Up a Service for API Key Management

    Create a service to handle the generation, storage, and validation of API keys.

    1import { Injectable } from '@nestjs/common';
    2import { randomBytes } from 'crypto';
    3
    4@Injectable()
    5export class ApiKeyService {
    6  // Method to generate a new API key
    7  generateApiKey(): string {
    8    return randomBytes(32).toString('hex'); // Generates a 64-character hexadecimal string
    9  }
    10
    11  // Method to store the API key in the database
    12  async storeApiKey(partnerId: string, apiKey: string): Promise<void> {
    13    // Implement database logic to store the API key with the partner ID
    14  }
    15
    16  // Method to validate an API key
    17  async validateApiKey(apiKey: string): Promise<boolean> {
    18    // Implement database logic to check if the API key is valid and active
    19    return true; // Return true if valid, false otherwise
    20  }
    21}
  2. Create a Controller to Handle API Key Requests

    Create a controller to expose endpoints for generating and managing API keys.

    1import { Controller, Post, Body } from '@nestjs/common';
    2import { ApiKeyService } from './api-key.service';
    3
    4@Controller('api-keys')
    5export class ApiKeyController {
    6  constructor(private readonly apiKeyService: ApiKeyService) {}
    7
    8  @Post('generate')
    9  async generateApiKey(@Body('partnerId') partnerId: string): Promise<{ apiKey: string }> {
    10    const apiKey = this.apiKeyService.generateApiKey();
    11    await this.apiKeyService.storeApiKey(partnerId, apiKey);
    12    return { apiKey };
    13  }
    14}
  3. Secure Your Endpoints with API Key Validation

    Use a guard or middleware to validate API keys for protected endpoints.

    1import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
    2import { ApiKeyService } from './api-key.service';
    3
    4@Injectable()
    5export class ApiKeyGuard implements CanActivate {
    6  constructor(private readonly apiKeyService: ApiKeyService) {}
    7
    8  async canActivate(context: ExecutionContext): Promise<boolean> {
    9    const request = context.switchToHttp().getRequest();
    10    const apiKey = request.headers['x-api-key'];
    11    return this.apiKeyService.validateApiKey(apiKey);
    12  }
    13}

    Apply the guard to your routes:

    1import { Controller, Get, UseGuards } from '@nestjs/common';
    2import { ApiKeyGuard } from './api-key.guard';
    3
    4@Controller('protected')
    5export class ProtectedController {
    6  @Get()
    7  @UseGuards(ApiKeyGuard)
    8  getProtectedResource() {
    9    return { message: 'This is a protected resource' };
    10  }
    11}

Additional Considerations