Skip to content

Eliminate redundant database query in adminGuard middleware #537

Description

@DeFiVC

Bug Description

The adminGuard middleware in src/middleware/auth.ts (lines 123-136) makes an additional database query on every admin endpoint request to check if the user is an admin. This is redundant since authGuard already fetches the user.

Location

src/middleware/auth.ts lines 123-136

export async function adminGuard(
    request: FastifyRequest,
    _reply: FastifyReply,
): Promise<void> {
    const { authUser } = request as AuthenticatedRequest;

    const user = await db.query.users.findFirst({
        where: eq(users.id, authUser.id),
    });

    if (!user?.isAdmin) {
        throw new ForbiddenError("Admin access required");
    }
}

The Problem

  1. authGuard (which runs before adminGuard) already fetches the full user row at line 61
  2. adminGuard fetches the same user row again
  3. Every admin endpoint makes 2 database queries for the same user
  4. The isAdmin flag could be included in the authUser object set by authGuard

Recommended Fix

Include isAdmin in the authGuard response and check it in adminGuard:

// In authGuard:
(request as AuthenticatedRequest).authUser = {
    id: user.id,
    stellarAddress: user.stellarAddress,
    isAdmin: user.isAdmin,  // Include this
};

// In adminGuard:
export async function adminGuard(
    request: FastifyRequest,
    _reply: FastifyReply,
): Promise<void> {
    const { authUser } = request as AuthenticatedRequest;
    if (!authUser.isAdmin) {
        throw new ForbiddenError("Admin access required");
    }
}

Acceptance Criteria

  • Include isAdmin in the AuthUser interface
  • Set it in authGuard from the already-fetched user row
  • Remove the redundant database query in adminGuard
  • Verify admin endpoints still work correctly

Severity

low - Performance optimization. Eliminates one database query per admin request.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions