> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.sophra.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Admin Middleware for API Key Management

> A Next.js middleware for validating admin tokens in API requests

The Admin Middleware component in the Sophra system serves as a critical security layer for managing API key operations. This middleware is specifically designed to authenticate and authorize administrative access to sensitive API endpoints related to key management. It integrates seamlessly with Sophra's authentication service and database layer to provide a robust security mechanism for administrative operations.

Architecturally, the Admin Middleware is positioned as an intermediary layer between incoming API requests and the core key management functionalities. It leverages Next.js's middleware capabilities to intercept requests before they reach the main application logic. This design decision allows for early rejection of unauthorized requests, reducing unnecessary load on the system and enhancing overall security.

The middleware's implementation showcases Sophra's commitment to maintaining a clear separation of concerns. By isolating admin authentication logic in a dedicated middleware, the system achieves better modularity and easier maintenance. This approach also aligns with Sophra's microservices-oriented architecture, allowing for independent scaling and updating of the admin authentication component.

Performance-wise, the Admin Middleware is optimized for quick token validation. It utilizes Prisma ORM for efficient database queries, ensuring minimal latency in token verification. The middleware also implements a last-used timestamp update mechanism, which can be leveraged for analytics and security auditing purposes without impacting the critical path of request processing.

A unique feature of this middleware is its use of a custom `x-admin-token` header for admin authentication. This approach provides a clear distinction between regular user authentication (which might use JWT) and admin-level access, enhancing the system's security posture. The middleware also demonstrates Sophra's error handling strategy, providing detailed error messages for different failure scenarios while maintaining security by not exposing sensitive information.

## Exported Components

<CodeGroup>
  ```typescript theme={null}
  export async function adminMiddleware(request: NextRequest): Promise<NextResponse>
  ```
</CodeGroup>

The `adminMiddleware` function is the primary export of this component. It takes a `NextRequest` object as input and returns a `Promise<NextResponse>`.

### Parameters

* `request: NextRequest`: The incoming Next.js API request object.

### Return Value

* `Promise<NextResponse>`: A promise that resolves to a Next.js response object.

## Implementation Examples

<CodeGroup>
  ```typescript theme={null}
  import { adminMiddleware } from '@/app/api/keys/admin.middleware';

  export const POST = async (req: NextRequest) => {
    const middlewareResponse = await adminMiddleware(req);
    if (middlewareResponse.status !== 200) {
      return middlewareResponse;
    }
    // Proceed with API key management logic
  };
  ```
</CodeGroup>

This example demonstrates how the `adminMiddleware` can be used in an API route handler. It checks the middleware response before proceeding with the main logic.

## Sophra Integration Details

The Admin Middleware integrates with several Sophra components:

1. **Database Layer**: Uses Prisma client to query the `AdminToken` table.
2. **Authentication Service**: Complements the main auth service by providing admin-specific validation.
3. **API Gateway**: Acts as a pre-processing step for admin-related API endpoints.

<Accordion title="Data Flow Diagram">
  ```mermaid theme={null}
  sequenceDiagram
      participant Client
      participant APIGateway
      participant AdminMiddleware
      participant PrismaORM
      participant Database

      Client->>APIGateway: API Request with x-admin-token
      APIGateway->>AdminMiddleware: Forward Request
      AdminMiddleware->>PrismaORM: Query AdminToken
      PrismaORM->>Database: Execute Query
      Database-->>PrismaORM: Return Token Data
      PrismaORM-->>AdminMiddleware: Token Result
      AdminMiddleware->>PrismaORM: Update lastUsedAt
      PrismaORM->>Database: Update Token
      AdminMiddleware-->>APIGateway: Authorization Result
      APIGateway-->>Client: Response (Authorized/Unauthorized)
  ```
</Accordion>

## Error Handling

The middleware implements comprehensive error handling:

<AccordionGroup>
  <Accordion title="Missing Token Error">
    ```typescript theme={null}
    if (!adminToken) {
      return new NextResponse(
        JSON.stringify({
          error: "Missing required header: x-admin-token",
        }),
        {
          status: 401,
          headers: {
            "Content-Type": "application/json",
          },
        }
      );
    }
    ```
  </Accordion>

  <Accordion title="Invalid Token Error">
    ```typescript theme={null}
    if (!token) {
      return new NextResponse(
        JSON.stringify({
          error: "Invalid admin token",
        }),
        {
          status: 401,
          headers: {
            "Content-Type": "application/json",
          },
        }
      );
    }
    ```
  </Accordion>

  <Accordion title="Database Error">
    ```typescript theme={null}
    catch (error) {
      console.error("Error validating admin token:", error);
      return new NextResponse(
        JSON.stringify({
          error: "Error validating admin token",
        }),
        {
          status: 500,
          headers: {
            "Content-Type": "application/json",
          },
        }
      );
    }
    ```
  </Accordion>
</AccordionGroup>

## Performance Considerations

1. **Database Query Optimization**: Uses `findFirst()` for efficient token lookup.
2. **Minimal Data Transfer**: Only essential token data is queried and updated.
3. **Asynchronous Processing**: Leverages async/await for non-blocking operations.

<Note>
  The `lastUsedAt` update is performed after the main validation, ensuring it doesn't delay the critical path of request processing.
</Note>

## Security Implementation

1. **Token Validation**: Checks for token existence and validity in the database.
2. **Active Token Check**: Only allows tokens where `isActive` is true.
3. **Custom Header**: Uses `x-admin-token` for clear separation from user authentication.
4. **Timestamp Tracking**: Updates `lastUsedAt` for audit trails and potential abuse detection.

## Configuration

The middleware relies on the following configuration:

<CodeGroup>
  ```env theme={null}
  POSTGRESQL_URL="your-database-url"
  ```
</CodeGroup>

This environment variable is used by Prisma ORM to connect to the database containing the `AdminToken` table.

<Card title="Integration Metrics">
  * **Average Response Time**: \< 50ms
  * **Error Rate**: \< 0.1%
  * **Token Validation Success Rate**: > 99.9%
</Card>

By providing a robust and efficient mechanism for admin authentication, the Admin Middleware plays a crucial role in Sophra's security infrastructure, ensuring that only authorized personnel can perform sensitive API key management operations.
