fix: prevent unauthorized API calls before authentication

- Add global AuthGuard component to handle authentication at layout level
- Make all API query hooks conditional on authentication status
- Define public routes (like /transcripts/new) that don't require auth
- Fix login flow to use NextAuth signIn instead of non-existent /login route
- Prevent 401 errors by waiting for auth token before making API calls

Previously, all routes under (app) were publicly accessible with each page
handling auth individually. Now authentication is enforced globally while
still allowing specific routes to remain public.
This commit is contained in:
2025-08-28 15:35:49 -06:00
parent 0eac7501c5
commit 26154af25c
5 changed files with 144 additions and 79 deletions

View File

@@ -1,53 +1,13 @@
"use client";
import { useEffect, useContext, useRef } from "react";
import { client, configureApiAuth } from "./apiClient";
import { useEffect } from "react";
import { configureApiAuth } from "./apiClient";
import useSessionAccessToken from "./useSessionAccessToken";
import { DomainContext } from "../domainContext";
// Store the current API URL globally
let currentApiUrl: string | null = null;
// Set up base URL middleware once
const baseUrlMiddlewareSetup = () => {
client.use({
onRequest({ request }) {
if (currentApiUrl) {
// Update the base URL for all requests
const url = new URL(request.url);
const apiUrl = new URL(currentApiUrl);
url.protocol = apiUrl.protocol;
url.host = apiUrl.host;
url.port = apiUrl.port;
return new Request(url.toString(), request);
}
return request;
},
});
};
// Initialize base URL middleware once
if (typeof window !== "undefined") {
baseUrlMiddlewareSetup();
}
// Note: Base URL is now configured directly in apiClient.tsx
export function ApiAuthProvider({ children }: { children: React.ReactNode }) {
const { accessToken } = useSessionAccessToken();
const { api_url } = useContext(DomainContext);
const initialized = useRef(false);
// Initialize middleware once on client side
useEffect(() => {
if (!initialized.current && typeof window !== "undefined") {
baseUrlMiddlewareSetup();
initialized.current = true;
}
}, []);
useEffect(() => {
// Update the global API URL
currentApiUrl = api_url;
}, [api_url]);
useEffect(() => {
// Configure authentication