mirror of
https://github.com/Tria-plc/emaui.git
synced 2026-08-26 19:12:50 +00:00
feat: implement useAuthToken hook for consistent auth token retrieval across components.comment from nati
This commit is contained in:
@@ -25,6 +25,7 @@ export {
|
||||
resetSignup,
|
||||
} from "./lib/store/signup.slice";
|
||||
export { usePermissions } from "./lib/hooks/usePermissions";
|
||||
export { useAuthToken } from "./lib/hooks/useAuthToken";
|
||||
export type { PermissionSet } from "./lib/hooks/usePermissions";
|
||||
export { RequirePermission } from "./lib/components/RequirePermission";
|
||||
export {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import Cookies from 'js-cookie';
|
||||
import { Navigate, Outlet, useLocation } from 'react-router-dom';
|
||||
import type { ReactNode } from 'react';
|
||||
import { authStorage } from '../utils/auth-storage';
|
||||
import { useAuthToken } from '../hooks/useAuthToken';
|
||||
|
||||
interface ProtectedRouteProps {
|
||||
children?: ReactNode;
|
||||
@@ -10,7 +9,7 @@ interface ProtectedRouteProps {
|
||||
|
||||
export function ProtectedRoute({ children, loginPath = '/login' }: ProtectedRouteProps) {
|
||||
const location = useLocation();
|
||||
const token = authStorage.getToken() ?? Cookies.get('auth-token');
|
||||
const token = useAuthToken();
|
||||
|
||||
if (!token) {
|
||||
return <Navigate to={loginPath} state={{ from: location }} replace />;
|
||||
|
||||
15
libs/auth/src/lib/hooks/useAuthToken.ts
Normal file
15
libs/auth/src/lib/hooks/useAuthToken.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { useSelector } from 'react-redux';
|
||||
import { authStorage } from '../utils/auth-storage';
|
||||
import type { AuthState } from '../types/auth.types';
|
||||
|
||||
/**
|
||||
* The current auth token, preferring Redux so components re-render on login
|
||||
* and logout. Falls back to storage for the one case Redux misses: both
|
||||
* `hydrateAuth` and the stores' `preloadedState` only populate `auth.token`
|
||||
* when a token *and* a cached user are present, so a session with a token but
|
||||
* no cached user would otherwise read as signed out.
|
||||
*/
|
||||
export function useAuthToken(): string | undefined {
|
||||
const token = useSelector((state: { auth: AuthState }) => state.auth.token);
|
||||
return token ?? authStorage.getToken();
|
||||
}
|
||||
Reference in New Issue
Block a user