Login integriert

This commit is contained in:
Marc Wieland
2025-04-21 17:46:44 +02:00
parent 8f9cd73e50
commit 8a92201b74
10 changed files with 500 additions and 102 deletions

View File

@@ -0,0 +1,58 @@
import { createContext, useContext, useState, useEffect, ReactNode } from "react";
import {jwtDecode} from "jwt-decode";
interface AuthContextType {
token: string | null;
username: string | null;
login: (token: string) => void;
logout: () => void;
isAuthenticated: boolean;
}
const AuthContext = createContext<AuthContextType>({
token: null,
login: () => {},
logout: () => {},
isAuthenticated: false,
username: null
});
export const AuthProvider = ({ children }: { children: ReactNode }) => {
const [token, setToken] = useState<string | null>(null);
const [username, setUsername] = useState<string | null>(null);
useEffect(() => {
const storedToken = localStorage.getItem("token");
if (storedToken) {
setToken(storedToken);
try {
const decoded: any = jwtDecode(storedToken);
setUsername(decoded.username); // <-- Username speichern
} catch (error) {
console.error("Token konnte nicht gelesen werden");
}
}
}, []);
const login = (newToken: string) => {
localStorage.setItem("token", newToken);
setToken(newToken);
};
const logout = () => {
localStorage.removeItem("token");
setToken(null);
};
const isAuthenticated = !!token;
return (
<AuthContext.Provider value={{ token, username, login, logout, isAuthenticated }}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => useContext(AuthContext);