From f2fe368f5c0aa5ebd2f82eab91e6c582e4366e6d Mon Sep 17 00:00:00 2001 From: Sam Piper Date: Sat, 20 Apr 2024 13:52:01 +0100 Subject: [PATCH] fix: fix the auth hook --- apps/forge/src/hooks/useVerifyAuthentication.ts | 4 ++++ apps/forge/src/redux/auth.slice.ts | 14 ++++++++++++++ apps/forge/src/types/auth.ts | 2 ++ 3 files changed, 20 insertions(+) diff --git a/apps/forge/src/hooks/useVerifyAuthentication.ts b/apps/forge/src/hooks/useVerifyAuthentication.ts index 9bcc4b6..9fb5395 100644 --- a/apps/forge/src/hooks/useVerifyAuthentication.ts +++ b/apps/forge/src/hooks/useVerifyAuthentication.ts @@ -3,6 +3,7 @@ import { useDispatch } from "react-redux"; import { User } from "@ignis/types/users.ts"; import axiosInstance from "@/api/axiosInstance.ts"; import { userActions } from "@/redux/user.slice.ts"; +import { authActions } from "@/redux/auth.slice.ts"; export const useVerifyAuthentication = () => { const [loading, setLoading] = useState(true); @@ -15,12 +16,15 @@ export const useVerifyAuthentication = () => { const response = await axiosInstance.get("/users/me"); if (response.status === 200) { dispatch(userActions.setUser(response.data)); + dispatch(authActions.onLogin()); setUser(response.data); } else { + dispatch(authActions.onLogout()); setUser(null); } } catch (error) { setUser(null); + dispatch(authActions.onLogout()); } finally { setLoading(false); } diff --git a/apps/forge/src/redux/auth.slice.ts b/apps/forge/src/redux/auth.slice.ts index 15316c5..334e8b3 100644 --- a/apps/forge/src/redux/auth.slice.ts +++ b/apps/forge/src/redux/auth.slice.ts @@ -4,6 +4,8 @@ import { AuthState } from "@/types/auth.ts"; // Define initial state based on persisted state or default values const initialState: AuthState = { + is_authenticated: false, + is_loading: false, redirect: undefined, }; @@ -14,6 +16,18 @@ const authSlice = createSlice({ setRedirect: (state, action: PayloadAction) => { state.redirect = action.payload; }, + setIsLoading: (state, action: PayloadAction) => { + state.is_loading = action.payload; + }, + onLogin: (state) => { + state.is_authenticated = true; + state.is_loading = false; + }, + onLogout: (state) => { + state.is_authenticated = false; + state.is_loading = false; + state.redirect = undefined; + }, }, extraReducers: (builder) => { builder.addCase(RESET_APP, () => initialState); diff --git a/apps/forge/src/types/auth.ts b/apps/forge/src/types/auth.ts index 7e1867c..21aae6a 100644 --- a/apps/forge/src/types/auth.ts +++ b/apps/forge/src/types/auth.ts @@ -1,3 +1,5 @@ export interface AuthState { + is_authenticated: boolean; + is_loading: boolean; redirect?: string; }