CurrentUserIdProvider

mail@pastecode.io avatar
unknown
typescript
20 days ago
2.1 kB
5
Indexable
Never
//In server/fd/fd-toolbox/auth/users/current-user-id-provider.ts:
import { AsyncLocalStorage } from 'async_hooks';
import { Uuid } from "@server/fd/fd-toolbox/types/uuid";
import { ToolboxUserConstants } from "@server/fd/fd-toolbox/constants/toolbox-user-constants";
import { jwtDecode } from 'jwt-decode';

interface RequestContext {
  userId: Uuid;
}

const asyncLocalStorage = new AsyncLocalStorage<RequestContext>();

let currentUserId: Uuid = ToolboxUserConstants.WorkerBotId;

export function getUserId(): Uuid {
  const context = asyncLocalStorage.getStore();
  return context?.userId ?? currentUserId;
}

export function setCurrentUserId(userId: Uuid): void {
  currentUserId = userId;
}

export function resetCurrentUserId(): void {
  currentUserId = ToolboxUserConstants.WorkerBotId;
}

export function runWithContext(userId: Uuid, callback: () => void): void {
  asyncLocalStorage.run({ userId }, callback);
}

export function extractUserIdFromRequest(req: Request): Uuid {
  const authHeader = req.headers.get('authorization');
  if (authHeader && authHeader.startsWith('Bearer ')) {
    const token = authHeader.substring(7);
    try {
      const decoded = jwtDecode(token);
      if (decoded && typeof decoded === 'object' && 'sub' in decoded) {
        return decoded.sub as Uuid;
      }
    } catch (error) {
      console.error('Error decoding JWT:', error);
    }
  }
  return ToolboxUserConstants.WorkerBotId;
}


//In your API route files (e.g., server/app/api/example/route.ts):
import { getUserId, runWithContext, extractUserIdFromRequest } from '@server/fd/fd-toolbox/auth/users/current-user-id-provider';
import { globalErrorHandlerApiWrapper } from "@server/web-framework/global-error-handler-api-wrapper";

export async function getHandler(req: Request) {
  return runWithContext(extractUserIdFromRequest(req), async () => {
    const userId = getUserId();
    // Use userId in your logic
    // ...
    return Response.json({ userId }, { status: 200 });
  });
}

export const GET = globalErrorHandlerApiWrapper(getHandler);

Leave a Comment