| 1 | import {
|
|---|
| 2 | createContext,
|
|---|
| 3 | useContext,
|
|---|
| 4 | createSignal,
|
|---|
| 5 | JSX,
|
|---|
| 6 | createEffect,
|
|---|
| 7 | } from "solid-js";
|
|---|
| 8 | import type { LoginResponse } from "@/api/auth";
|
|---|
| 9 |
|
|---|
| 10 | interface AuthContextType {
|
|---|
| 11 | user: () => LoginResponse | null;
|
|---|
| 12 | isAuthenticated: () => boolean;
|
|---|
| 13 | login: (userData: LoginResponse) => void;
|
|---|
| 14 | logout: () => void;
|
|---|
| 15 | }
|
|---|
| 16 |
|
|---|
| 17 | const AuthContext = createContext<AuthContextType>();
|
|---|
| 18 |
|
|---|
| 19 | export const AuthProvider = (props: { children: JSX.Element }) => {
|
|---|
| 20 | const [user, setUser] = createSignal<LoginResponse | null>(null);
|
|---|
| 21 |
|
|---|
| 22 | createEffect(() => {
|
|---|
| 23 | const token = localStorage.getItem("token");
|
|---|
| 24 | const userData = localStorage.getItem("user");
|
|---|
| 25 |
|
|---|
| 26 | if (token && userData) {
|
|---|
| 27 | try {
|
|---|
| 28 | setUser(JSON.parse(userData));
|
|---|
| 29 | } catch (e) {
|
|---|
| 30 | console.error("Failed to parse user data:", e);
|
|---|
| 31 | logout();
|
|---|
| 32 | }
|
|---|
| 33 | }
|
|---|
| 34 | });
|
|---|
| 35 |
|
|---|
| 36 | const login = (userData: LoginResponse) => {
|
|---|
| 37 | localStorage.setItem("token", userData.token);
|
|---|
| 38 | localStorage.setItem("user", JSON.stringify(userData));
|
|---|
| 39 | setUser(userData);
|
|---|
| 40 | };
|
|---|
| 41 |
|
|---|
| 42 | const logout = () => {
|
|---|
| 43 | localStorage.removeItem("token");
|
|---|
| 44 | localStorage.removeItem("user");
|
|---|
| 45 | setUser(null);
|
|---|
| 46 | };
|
|---|
| 47 |
|
|---|
| 48 | const isAuthenticated = () => user() !== null;
|
|---|
| 49 |
|
|---|
| 50 | return (
|
|---|
| 51 | <AuthContext.Provider value={{ user, isAuthenticated, login, logout }}>
|
|---|
| 52 | {props.children}
|
|---|
| 53 | </AuthContext.Provider>
|
|---|
| 54 | );
|
|---|
| 55 | };
|
|---|
| 56 |
|
|---|
| 57 | export const useAuth = () => {
|
|---|
| 58 | const context = useContext(AuthContext);
|
|---|
| 59 | if (!context) {
|
|---|
| 60 | throw new Error("useAuth must be used within an AuthProvider");
|
|---|
| 61 | }
|
|---|
| 62 | return context;
|
|---|
| 63 | };
|
|---|