SurfSense/surfsense_web/components/TokenHandler.tsx

67 lines
2.4 KiB
TypeScript
Raw Normal View History

2025-07-27 10:05:37 -07:00
"use client";
2025-04-07 23:47:06 -07:00
2025-07-27 10:05:37 -07:00
import { useRouter, useSearchParams } from "next/navigation";
2025-07-27 10:41:15 -07:00
import { useEffect } from "react";
import { getAndClearRedirectPath, setBearerToken } from "@/lib/auth-utils";
2025-04-07 23:47:06 -07:00
interface TokenHandlerProps {
redirectPath?: string; // Default path to redirect after storing token (if no saved path)
2025-07-27 10:05:37 -07:00
tokenParamName?: string; // Name of the URL parameter containing the token
storageKey?: string; // Key to use when storing in localStorage (kept for backwards compatibility)
2025-04-07 23:47:06 -07:00
}
/**
* Client component that extracts a token from URL parameters and stores it in localStorage
* After storing the token, it redirects the user back to the page they were on before
* being redirected to login (if available), or to the default redirectPath.
2025-07-27 10:05:37 -07:00
*
* @param redirectPath - Default path to redirect after storing token (default: '/dashboard')
2025-04-07 23:47:06 -07:00
* @param tokenParamName - Name of the URL parameter containing the token (default: 'token')
* @param storageKey - Key to use when storing in localStorage (default: 'surfsense_bearer_token')
2025-04-07 23:47:06 -07:00
*/
const TokenHandler = ({
redirectPath = "/dashboard",
2025-07-27 10:05:37 -07:00
tokenParamName = "token",
storageKey = "surfsense_bearer_token",
2025-04-07 23:47:06 -07:00
}: TokenHandlerProps) => {
2025-07-27 10:05:37 -07:00
const router = useRouter();
const searchParams = useSearchParams();
useEffect(() => {
// Only run on client-side
if (typeof window === "undefined") return;
// Get token from URL parameters
const token = searchParams.get(tokenParamName);
if (token) {
try {
// Store token in localStorage using both methods for compatibility
2025-07-27 10:05:37 -07:00
localStorage.setItem(storageKey, token);
setBearerToken(token);
2025-07-27 10:05:37 -07:00
// Check if there's a saved redirect path from before the auth flow
const savedRedirectPath = getAndClearRedirectPath();
// Use the saved path if available, otherwise use the default redirectPath
const finalRedirectPath = savedRedirectPath || redirectPath;
// Redirect to the appropriate path
router.push(finalRedirectPath);
2025-07-27 10:05:37 -07:00
} catch (error) {
console.error("Error storing token in localStorage:", error);
// Even if there's an error, try to redirect to the default path
router.push(redirectPath);
2025-07-27 10:05:37 -07:00
}
}
}, [searchParams, tokenParamName, storageKey, redirectPath, router]);
return (
<div className="flex items-center justify-center min-h-[200px]">
<p className="text-gray-500">Processing authentication...</p>
</div>
);
2025-04-07 23:47:06 -07:00
};
2025-07-27 10:05:37 -07:00
export default TokenHandler;