add token in auth

This commit is contained in:
AmirHossein Mahmoodi
2025-08-13 09:22:49 +03:30
parent fada14f0dd
commit 10179dc726
3 changed files with 39 additions and 13 deletions

View File

@@ -14,7 +14,7 @@ import { object, string } from "yup";
const LoginForm = () => { const LoginForm = () => {
const [showPassword, setShowPassword] = useState(false); const [showPassword, setShowPassword] = useState(false);
const requestServer = useRequest(); const requestServer = useRequest();
const { getUser } = useAuth(); const { setToken } = useAuth();
const defaultValues = { const defaultValues = {
username: "", username: "",
password: "", password: "",
@@ -42,11 +42,11 @@ const LoginForm = () => {
const formData = new FormData(); const formData = new FormData();
formData.append("username", data.username); formData.append("username", data.username);
formData.append("password", data.password); formData.append("password", data.password);
await requestServer(GET_USER_LOGIN_ROUTE, "post", { const response = await requestServer(GET_USER_LOGIN_ROUTE, "post", {
data: formData, data: formData,
}); });
getUser(); setToken(response.data.data.token);
} catch (error) {} } catch (error) { }
}; };
return ( return (

View File

@@ -6,6 +6,7 @@ import { createContext, useCallback, useContext, useEffect, useReducer, useState
const initAuth = { const initAuth = {
initAuthState: false, initAuthState: false,
isAuth: false, isAuth: false,
token: null,
user: {}, user: {},
}; };
@@ -19,6 +20,12 @@ const authReducer = (state, action) => {
return { ...state, isAuth: action.isAuth }; return { ...state, isAuth: action.isAuth };
case "CHANGE_INIT_AUTH": case "CHANGE_INIT_AUTH":
return { ...state, initAuthState: action.initAuthState }; return { ...state, initAuthState: action.initAuthState };
case "CLEAR_TOKEN":
localStorage.removeItem("_token");
return { ...state, token: null };
case "SET_TOKEN":
localStorage.setItem("_token", action.token);
return { ...state, token: action.token };
default: default:
return state; return state;
} }
@@ -46,7 +53,16 @@ export const AuthProvider = ({ children }) => {
dispatch({ type: "CHANGE_INIT_AUTH", initAuthState }); dispatch({ type: "CHANGE_INIT_AUTH", initAuthState });
}, []); }, []);
const clearToken = useCallback(() => {
dispatch({ type: "CLEAR_TOKEN" });
}, []);
const setToken = useCallback((token) => {
dispatch({ type: "SET_TOKEN", token });
}, []);
const logout = () => { const logout = () => {
clearToken()
clearUser(); clearUser();
changeAuthState(false); changeAuthState(false);
changeInitAuth(true); changeInitAuth(true);
@@ -55,7 +71,7 @@ export const AuthProvider = ({ children }) => {
const getUser = useCallback(async () => { const getUser = useCallback(async () => {
try { try {
const { data } = await axios.get(GET_USER_ROUTE, { const { data } = await axios.get(GET_USER_ROUTE, {
withCredentials: true, headers: { authorization: `Bearer ${state.token}` },
}); });
changeUser(data.data); changeUser(data.data);
changeAuthState(true); changeAuthState(true);
@@ -74,20 +90,33 @@ export const AuthProvider = ({ children }) => {
message: " مشکلی در احراز هویت رخ داده است . دقایقی بعد امتحان کنید!!!", message: " مشکلی در احراز هویت رخ داده است . دقایقی بعد امتحان کنید!!!",
}); });
} }
}, [clearUser, changeUser, changeAuthState, changeInitAuth]); }, [state.token, clearUser, changeUser, changeAuthState, changeInitAuth]);
useEffect(() => { useEffect(() => {
getUser(); const localToken = localStorage.getItem("_token");
if (localToken) dispatch({ type: "SET_TOKEN", token: localToken });
}, []); }, []);
useEffect(() => {
if (!state.token) {
clearUser();
changeAuthState(false);
changeInitAuth(true);
return;
}
getUser();
}, [state.token]);
return ( return (
<AuthContext.Provider <AuthContext.Provider
value={{ value={{
token: state.token,
user: state.user, user: state.user,
isAuth: state.isAuth, isAuth: state.isAuth,
initAuthState: state.initAuthState, initAuthState: state.initAuthState,
getUser, getUser,
logout, logout,
setToken,
errorState, errorState,
}} }}
> >

View File

@@ -6,9 +6,7 @@ import { useSidebarBadge } from "./useSidebarBadge";
const defaultOptions = { const defaultOptions = {
data: {}, data: {},
requestOptions: { headers: {},
headers: {},
},
notificationShow: true, notificationShow: true,
notificationSuccess: false, notificationSuccess: false,
notificationFailed: true, notificationFailed: true,
@@ -21,7 +19,7 @@ const useRequest = (initOptions) => {
const { mutate: sidebarUpdate } = useSidebarBadge({ const { mutate: sidebarUpdate } = useSidebarBadge({
enable: _options.hasSidebarUpdate, enable: _options.hasSidebarUpdate,
}); });
const { logout } = useAuth(); const { token, logout } = useAuth();
/** /**
* Performs an HTTP request. * Performs an HTTP request.
@@ -37,8 +35,7 @@ const useRequest = (initOptions) => {
url, url,
method, method,
data: method === "get" ? null : mergedOptions.data, data: method === "get" ? null : mergedOptions.data,
withCredentials: true, headers: { authorization: `Bearer ${token}`, ...mergedOptions.headers, },
...mergedOptions.requestOptions,
}); });
if (mergedOptions.hasSidebarUpdate) { if (mergedOptions.hasSidebarUpdate) {
if (method === "post" || method === "put" || method === "delete") sidebarUpdate(); if (method === "post" || method === "put" || method === "delete") sidebarUpdate();