Skip to content

Commit 81518c6

Browse files
committed
auth fix
1 parent d7de8dd commit 81518c6

5 files changed

Lines changed: 80 additions & 51 deletions

File tree

src/App.tsx

Lines changed: 76 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,85 @@
1-
import { Routes, Route } from "react-router-dom";
1+
import { Routes, Route, useNavigate } from "react-router-dom";
22
import Login from "./routes/Login/Login.tsx";
33
import { AuthenticationGuard } from "./providers/AuthGuard.tsx";
4-
import { lazy, Suspense } from "react";
4+
import { lazy, Suspense, useEffect, useState } from "react";
5+
import { useAuth0 } from "@auth0/auth0-react";
6+
import { ACCESS_TOKEN, REFRESH_TOKEN } from "./lib/constants.ts";
7+
import { useMutation } from "@tanstack/react-query";
8+
import axiosInstance from "./config/axios-config.ts";
59
const Text = lazy(() => import("./routes/Text/Text.tsx"));
610
const Instance = lazy(() => import("./routes/Instance/Instance.tsx"));
711

12+
type Auth0UserType = {
13+
getIdTokenClaims: () => Promise<any>;
14+
isAuthenticated: boolean;
15+
logout: (options?: { logoutParams?: { returnTo: string } }) => Promise<void>;
16+
};
17+
818
function App() {
19+
const navigate = useNavigate();
20+
const tokenRefreshIntervalMs = Number(60000) || 0;
21+
22+
const [intervalId, setIntervalId] = useState<ReturnType<
23+
typeof setInterval
24+
> | null>(null);
25+
const { getIdTokenClaims, isAuthenticated, logout }: Auth0UserType =
26+
useAuth0() as Auth0UserType;
27+
28+
useEffect(() => {
29+
if (isAuthenticated) {
30+
const getToken = async () => {
31+
try {
32+
const claims = await getIdTokenClaims();
33+
const idToken = claims.__raw;
34+
if (Date.now() >= claims.exp * 1000) {
35+
sessionStorage.removeItem(ACCESS_TOKEN);
36+
localStorage.removeItem(REFRESH_TOKEN);
37+
isAuthenticated &&
38+
(await logout({
39+
logoutParams: {
40+
returnTo: globalThis.location.origin,
41+
},
42+
}));
43+
} else {
44+
sessionStorage.setItem(ACCESS_TOKEN, idToken);
45+
}
46+
} catch (error) {
47+
console.error("Error fetching token:", error);
48+
}
49+
};
50+
getToken().then();
51+
}
52+
}, [isAuthenticated]);
53+
54+
const loginMutation = useMutation({
55+
mutationFn: async (refreshToken: string) => {
56+
const response = await axiosInstance.post("/api/v1/auth/refresh-token", {
57+
token: refreshToken,
58+
});
59+
return response.data;
60+
},
61+
onSuccess: (data: { access_token: string }) => {
62+
sessionStorage.setItem(ACCESS_TOKEN, data.access_token);
63+
if (!intervalId) {
64+
startTokenRefreshCounter();
65+
}
66+
},
67+
onError: () => {
68+
sessionStorage.removeItem(ACCESS_TOKEN);
69+
localStorage.removeItem(REFRESH_TOKEN);
70+
navigate("/login");
71+
},
72+
});
73+
74+
const startTokenRefreshCounter = () => {
75+
const interval = setInterval(() => {
76+
const refreshToken = localStorage.getItem(REFRESH_TOKEN);
77+
if (refreshToken) {
78+
loginMutation.mutate(refreshToken);
79+
}
80+
}, tokenRefreshIntervalMs);
81+
setIntervalId(interval);
82+
};
983
return (
1084
<div className="flex w-full">
1185
<div className="flex-1 overflow-auto">

src/components/ui/molecules/user-profile/UserProfile.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { useAuth0 } from "@auth0/auth0-react";
22
import { LogOut } from "lucide-react";
3-
import { clearAccessToken } from "@/lib/auth-utils";
43

54
import {
65
DropdownMenu,
@@ -10,12 +9,13 @@ import {
109
DropdownMenuSeparator,
1110
DropdownMenuTrigger,
1211
} from "@/components/ui/atoms/dropdown-menu";
12+
import { ACCESS_TOKEN } from "@/lib/constants";
1313

1414
const UserProfile = () => {
1515
const { user, logout } = useAuth0();
1616

1717
const handleLogout = () => {
18-
clearAccessToken();
18+
sessionStorage.removeItem(ACCESS_TOKEN);
1919
logout({
2020
logoutParams: {
2121
returnTo: window.location.origin + "/login",

src/lib/auth-utils.ts

Lines changed: 0 additions & 39 deletions
This file was deleted.

src/lib/constants.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export const ACCESS_TOKEN = "accessToken";
2+
export const REFRESH_TOKEN = "refreshToken";
23

34
export const LanguageMap = {
45
bo: "Tibetan",

src/providers/AuthGuard.tsx

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1-
import React, { useEffect } from "react";
1+
import React from "react";
22
import { useAuth0 } from "@auth0/auth0-react";
33
import { Navigate } from "react-router-dom";
4-
import { syncAuth0TokenToSessionStorage } from "@/lib/auth-utils";
54

65
export const AuthenticationGuard = ({
76
component: Component,
@@ -10,12 +9,6 @@ export const AuthenticationGuard = ({
109
}) => {
1110
const { isAuthenticated, isLoading } = useAuth0();
1211

13-
useEffect(() => {
14-
if (isAuthenticated) {
15-
syncAuth0TokenToSessionStorage();
16-
}
17-
}, [isAuthenticated]);
18-
1912
if (isLoading) {
2013
return (
2114
<div className="flex flex-col items-center justify-center h-screen">

0 commit comments

Comments
 (0)