Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

useAuthorized refactor

yuneng-jiangc47866afb982
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/hooks/useAuthorized.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/hooks/useAuthorized.test.ts
index 78eddbd8d3c..ef4a779b50b 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/hooks/useAuthorized.test.ts
+++ b/ui/litellm-dashboard/src/app/(dashboard)/hooks/useAuthorized.test.ts
@@ -8,12 +8,13 @@ import useAuthorized from "./useAuthorized";
// Unmock useAuthorized to test the actual implementation
vi.unmock("@/app/(dashboard)/hooks/useAuthorized");
-const { replaceMock, clearTokenCookiesMock, getProxyBaseUrlMock, getUiConfigMock, isJwtExpiredMock } = vi.hoisted(() => ({
+const { replaceMock, clearTokenCookiesMock, getProxyBaseUrlMock, getUiConfigMock, decodeTokenMock, checkTokenValidityMock } = vi.hoisted(() => ({
replaceMock: vi.fn(),
clearTokenCookiesMock: vi.fn(),
getProxyBaseUrlMock: vi.fn(() => "http://proxy.example"),
getUiConfigMock: vi.fn(),
- isJwtExpiredMock: vi.fn(),
+ decodeTokenMock: vi.fn(),
+ checkTokenValidityMock: vi.fn(),
}));
vi.mock("next/navigation", () => ({
@@ -43,7 +44,8 @@ vi.mock("@/utils/jwtUtils", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/utils/jwtUtils")>();
return {
...actual,
- isJwtExpired: isJwtExpiredMock,
+ decodeToken: decodeTokenMock,
+ checkTokenValidity: checkTokenValidityMock,
};
});
@@ -77,7 +79,8 @@ describe("useAuthorized", () => {
clearTokenCookiesMock.mockReset();
getProxyBaseUrlMock.mockClear();
getUiConfigMock.mockReset();
- isJwtExpiredMock.mockReset();
+ decodeTokenMock.mockReset();
+ checkTokenValidityMock.mockReset();
clearCookie();
});
@@ -88,9 +91,8 @@ describe("useAuthorized", () => {
auto_redirect_to_sso: false,
admin_ui_disabled: false,
});
- isJwtExpiredMock.mockReturnValue(false);
-
- const token = createJwt({
+
+ const decodedPayload = {
key: "api-key-123",
user_id: "user-1",
user_email: "[email protected]",
@@ -98,7 +100,12 @@ describe("useAuthorized", () => {
premium_user: true,
disabled_non_admin_personal_key_creation: false,
login_method: "username_password",
- });
+ };
+
+ decodeTokenMock.mockReturnValue(decodedPayload);
+ checkTokenValidityMock.mockReturnValue(true);
+
+ const token = createJwt(decodedPayload);
document.cookie = `token=${token}; path=/;`;
const { result } = renderHook(() => useAuthorized(), { wrapper });
@@ -126,6 +133,9 @@ describe("useAuthorized", () => {
admin_ui_disabled: false,
});
+ decodeTokenMock.mockReturnValue(null);
+ checkTokenValidityMock.mockReturnValue(false);
+
document.cookie = "token=invalid-token; path=/;";
const { result } = renderHook(() => useAuthorized(), { wrapper });
@@ -146,9 +156,8 @@ describe("useAuthorized", () => {
auto_redirect_to_sso: false,
admin_ui_disabled: true,
});
- isJwtExpiredMock.mockReturnValue(false);
- const token = createJwt({
+ const decodedPayload = {
key: "api-key-123",
user_id: "user-1",
user_email: "[email protected]",
@@ -156,7 +165,12 @@ describe("useAuthorized", () => {
premium_user: true,
disabled_non_admin_personal_key_creation: false,
login_method: "username_password",
- });
+ };
+
+ decodeTokenMock.mockReturnValue(decodedPayload);
+ checkTokenValidityMock.mockReturnValue(true);
+
+ const token = createJwt(decodedPayload);
document.cookie = `token=${token}; path=/;`;
const { result } = renderHook(() => useAuthorized(), { wrapper });
@@ -178,6 +192,9 @@ describe("useAuthorized", () => {
admin_ui_disabled: false,
});
+ decodeTokenMock.mockReturnValue(null);
+ checkTokenValidityMock.mockReturnValue(false);
+
// No token cookie set
const { result } = renderHook(() => useAuthorized(), { wrapper });
@@ -196,14 +213,18 @@ describe("useAuthorized", () => {
auto_redirect_to_sso: false,
admin_ui_disabled: false,
});
- isJwtExpiredMock.mockReturnValue(true);
- const token = createJwt({
+ const decodedPayload = {
key: "api-key-123",
user_id: "user-1",
user_email: "[email protected]",
user_role: "app_admin",
- });
+ };
+
+ decodeTokenMock.mockReturnValue(decodedPayload);
+ checkTokenValidityMock.mockReturnValue(false);
+
+ const token = createJwt(decodedPayload);
document.cookie = `token=${token}; path=/;`;
const { result } = renderHook(() => useAuthorized(), { wrapper });
@@ -213,6 +234,6 @@ describe("useAuthorized", () => {
});
expect(replaceMock).toHaveBeenCalledWith("http://proxy.example/ui/login");
- expect(isJwtExpiredMock).toHaveBeenCalledWith(token);
+ expect(checkTokenValidityMock).toHaveBeenCalledWith(token);
});
});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/hooks/useAuthorized.ts b/ui/litellm-dashboard/src/app/(dashboard)/hooks/useAuthorized.ts
index 531a240a371..0b60971c1eb 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/hooks/useAuthorized.ts
+++ b/ui/litellm-dashboard/src/app/(dashboard)/hooks/useAuthorized.ts
@@ -2,8 +2,7 @@
import { getProxyBaseUrl } from "@/components/networking";
import { clearTokenCookies, getCookie } from "@/utils/cookieUtils";
-import { isJwtExpired } from "@/utils/jwtUtils";
-import { jwtDecode } from "jwt-decode";
+import { checkTokenValidity, decodeToken } from "@/utils/jwtUtils";
import { useRouter } from "next/navigation";
import { useEffect, useMemo } from "react";
import { useUIConfig } from "./uiConfig/useUIConfig";
@@ -43,44 +42,31 @@ const useAuthorized = () => {
const token = typeof document !== "undefined" ? getCookie("token") : null;
- // Step 1: Check for missing token or expired JWT - kick out immediately (even if UI Config is loading)
+ const decoded = useMemo(() => decodeToken(token), [token]);
+ const isTokenValid = useMemo(() => checkTokenValidity(token), [token]);
+ const isLoading = isUIConfigLoading;
+ const isAuthorized = isTokenValid && !uiConfig?.admin_ui_disabled;
+
+ // Single useEffect for all redirect logic
useEffect(() => {
- if (!token || (token && isJwtExpired(token))) {
+ if (isLoading) return;
+
+ if (!isAuthorized) {
if (token) {
clearTokenCookies();
}
router.replace(`${getProxyBaseUrl()}/ui/login`);
}
- }, [token, router]);
-
- useEffect(() => {
- if (isUIConfigLoading) {
- return;
- }
- if (uiConfig?.admin_ui_disabled) {
- router.replace(`${getProxyBaseUrl()}/ui/login`);
- }
- }, [router, isUIConfigLoading, uiConfig]);
-
- // Decode safely
- const decoded = useMemo(() => {
- if (!token) return null;
- try {
- return jwtDecode(token) as Record<string, any>;
- } catch {
- // Bad token in cookie — clear and bounce
- clearTokenCookies();
- router.replace(`${getProxyBaseUrl()}/ui/login`);
- return null;
- }
- }, [token, router]);
+ }, [isLoading, isAuthorized, token, router]);
return {
- token: token,
+ isLoading,
+ isAuthorized,
+ token: isAuthorized ? token : null,
accessToken: decoded?.key ?? null,
userId: decoded?.user_id ?? null,
userEmail: decoded?.user_email ?? null,
- userRole: formatUserRole(decoded?.user_role ?? null),
+ userRole: formatUserRole(decoded?.user_role),
premiumUser: decoded?.premium_user ?? null,
disabledPersonalKeyCreation: decoded?.disabled_non_admin_personal_key_creation ?? null,
showSSOBanner: decoded?.login_method === "username_password",
diff --git a/ui/litellm-dashboard/src/utils/jwtUtils.test.ts b/ui/litellm-dashboard/src/utils/jwtUtils.test.ts
index d695a3c37bb..bad8d4f6653 100644
--- a/ui/litellm-dashboard/src/utils/jwtUtils.test.ts
+++ b/ui/litellm-dashboard/src/utils/jwtUtils.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
-import { isJwtExpired } from "./jwtUtils";
+import { isJwtExpired, decodeToken, checkTokenValidity } from "./jwtUtils";
import { jwtDecode } from "jwt-decode";
vi.mock("jwt-decode");
@@ -50,4 +50,81 @@ describe("jwtUtils", () => {
expect(isJwtExpired("invalid-token")).toBe(true);
});
+
+ describe("decodeToken", () => {
+ it("should return null if token is null", () => {
+ expect(decodeToken(null)).toBeNull();
+ });
+
+ it("should return null if token is empty string", () => {
+ expect(decodeToken("")).toBeNull();
+ });
+
+ it("should decode a valid token", () => {
+ const mockPayload = {
+ key: "api-key-123",
+ user_id: "user-1",
+ user_email: "[email protected]",
+ user_role: "app_admin",
+ };
+ vi.mocked(jwtDecode).mockReturnValue(mockPayload);
+
+ expect(decodeToken("valid-token")).toEqual(mockPayload);
+ expect(jwtDecode).toHaveBeenCalledWith("valid-token");
+ });
+
+ it("should return null if jwtDecode throws an error", () => {
+ vi.mocked(jwtDecode).mockImplementation(() => {
+ throw new Error("Invalid token");
+ });
+
+ expect(decodeToken("invalid-token")).toBeNull();
+ });
+ });
+
+ describe("checkTokenValidity", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("should return false if token is null", () => {
+ expect(checkTokenValidity(null)).toBe(false);
+ });
+
+ it("should return false if token is empty string", () => {
+ expect(checkTokenValidity("")).toBe(false);
+ });
+
+ it("should return true for a valid, non-expired token", () => {
+ const mockDateNow = 1716838401000;
+ vi.spyOn(Date, "now").mockReturnValue(mockDateNow);
+ const mockPayload = {
+ exp: Math.floor(mockDateNow / 1000) + 1000,
+ user_id: "user-1",
+ };
+ vi.mocked(jwtDecode).mockReturnValue(mockPayload);
+
+ expect(checkTokenValidity("valid-token")).toBe(true);
+ });
+
+ it("should return false for an expired token", () => {
+ const mockDateNow = 1716838401000;
+ vi.spyOn(Date, "now").mockReturnValue(mockDateNow);
+ const mockPayload = {
+ exp: Math.floor(mockDateNow / 1000) - 1,
+ user_id: "user-1",
+ };
+ vi.mocked(jwtDecode).mockReturnValue(mockPayload);
+
+ expect(checkTokenValidity("expired-token")).toBe(false);
+ });
+
+ it("should return false if token cannot be decoded", () => {
+ vi.mocked(jwtDecode).mockImplementation(() => {
+ throw new Error("Invalid token");
+ });
+
+ expect(checkTokenValidity("invalid-token")).toBe(false);
+ });
+ });
});
diff --git a/ui/litellm-dashboard/src/utils/jwtUtils.ts b/ui/litellm-dashboard/src/utils/jwtUtils.ts
index d3db41a411a..2a7972ad4cc 100644
--- a/ui/litellm-dashboard/src/utils/jwtUtils.ts
+++ b/ui/litellm-dashboard/src/utils/jwtUtils.ts
@@ -12,3 +12,18 @@ export function isJwtExpired(token: string): boolean {
return true;
}
}
+
+export function decodeToken(token: string | null): Record<string, any> | null {
+ if (!token) return null;
+ try {
+ return jwtDecode(token) as Record<string, any>;
+ } catch {
+ return null;
+ }
+}
+
+export function checkTokenValidity(token: string | null): boolean {
+ if (!token) return false;
+ const decoded = decodeToken(token);
+ return decoded !== null && !isJwtExpired(token);
+}