Spaces:
Sleeping
Sleeping
File size: 4,772 Bytes
34af792 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | /* eslint-disable react-refresh/only-export-components */
/**
* AuthContext - Authentication state management.
*
* Manages:
* - User authentication state
* - Login/Logout operations
* - Token persistence
* - Current user data
*/
import { createContext, useReducer, useEffect, useCallback, useContext } from "react";
import PropTypes from "prop-types";
import storage from "@utils/storage";
import { STORAGE_KEYS } from "@utils/constants";
// ---------------------------------------------------------------------------
// Initial State
// ---------------------------------------------------------------------------
function loadPersistedAuth() {
const user = storage.get(STORAGE_KEYS.AUTH_USER, null);
const token = storage.get(STORAGE_KEYS.AUTH_TOKEN, null);
return {
user,
token,
isAuthenticated: Boolean(user && token),
};
}
function buildInitialState() {
const persisted = loadPersistedAuth();
return {
...persisted,
loading: false,
error: null,
};
}
// ---------------------------------------------------------------------------
// Action Types
// ---------------------------------------------------------------------------
const ACTION_TYPES = {
SET_LOADING: "SET_LOADING",
LOGIN_SUCCESS: "LOGIN_SUCCESS",
LOGOUT: "LOGOUT",
SET_ERROR: "SET_ERROR",
CLEAR_ERROR: "CLEAR_ERROR",
UPDATE_USER: "UPDATE_USER",
};
// ---------------------------------------------------------------------------
// Reducer
// ---------------------------------------------------------------------------
function authReducer(state, action) {
switch (action.type) {
case ACTION_TYPES.SET_LOADING:
return { ...state, loading: action.payload, error: null };
case ACTION_TYPES.LOGIN_SUCCESS:
return {
...state,
user: action.payload.user,
token: action.payload.token,
isAuthenticated: true,
loading: false,
error: null,
};
case ACTION_TYPES.LOGOUT:
return {
...state,
user: null,
token: null,
isAuthenticated: false,
loading: false,
error: null,
};
case ACTION_TYPES.SET_ERROR:
return { ...state, error: action.payload, loading: false };
case ACTION_TYPES.CLEAR_ERROR:
return { ...state, error: null };
case ACTION_TYPES.UPDATE_USER:
return { ...state, user: { ...state.user, ...action.payload } };
default:
return state;
}
}
// ---------------------------------------------------------------------------
// Context
// ---------------------------------------------------------------------------
export const AuthContext = createContext(null);
// ---------------------------------------------------------------------------
// Provider
// ---------------------------------------------------------------------------
export function AuthProvider({ children }) {
const [state, dispatch] = useReducer(authReducer, null, buildInitialState);
// Persist auth data whenever it changes
useEffect(() => {
if (state.user && state.token) {
storage.set(STORAGE_KEYS.AUTH_USER, state.user);
storage.set(STORAGE_KEYS.AUTH_TOKEN, state.token);
} else {
storage.remove(STORAGE_KEYS.AUTH_USER);
storage.remove(STORAGE_KEYS.AUTH_TOKEN);
}
}, [state.user, state.token]);
// --- Actions ---------------------------------------------------------------
const setLoading = useCallback((loading) => {
dispatch({ type: ACTION_TYPES.SET_LOADING, payload: loading });
}, []);
const loginSuccess = useCallback((user, token) => {
dispatch({
type: ACTION_TYPES.LOGIN_SUCCESS,
payload: { user, token },
});
}, []);
const logout = useCallback(() => {
dispatch({ type: ACTION_TYPES.LOGOUT });
}, []);
const setError = useCallback((error) => {
dispatch({ type: ACTION_TYPES.SET_ERROR, payload: error });
}, []);
const clearError = useCallback(() => {
dispatch({ type: ACTION_TYPES.CLEAR_ERROR });
}, []);
const updateUser = useCallback((userData) => {
dispatch({ type: ACTION_TYPES.UPDATE_USER, payload: userData });
}, []);
const value = {
...state,
setLoading,
loginSuccess,
logout,
setError,
clearError,
updateUser,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
AuthProvider.propTypes = {
children: PropTypes.node.isRequired,
};
// ---------------------------------------------------------------------------
// Hook
// ---------------------------------------------------------------------------
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
}
|