Userverwaltung integriert
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
import { createContext, useContext, useState, useEffect, ReactNode } from "react";
|
||||
import {jwtDecode} from "jwt-decode";
|
||||
|
||||
|
||||
import { jwtDecode } from "jwt-decode";
|
||||
|
||||
interface AuthContextType {
|
||||
token: string | null;
|
||||
username: string | null;
|
||||
role: string | null;
|
||||
isAdmin: boolean;
|
||||
login: (token: string) => void;
|
||||
logout: () => void;
|
||||
isAuthenticated: boolean;
|
||||
@@ -13,15 +13,22 @@ interface AuthContextType {
|
||||
|
||||
const AuthContext = createContext<AuthContextType>({
|
||||
token: null,
|
||||
username: null,
|
||||
role: null,
|
||||
isAdmin: false,
|
||||
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);
|
||||
const [role, setRole] = useState<string | null>(null);
|
||||
|
||||
const isAdmin = role === "admin";
|
||||
|
||||
const isAuthenticated = !!token;
|
||||
|
||||
useEffect(() => {
|
||||
const storedToken = localStorage.getItem("token");
|
||||
@@ -29,7 +36,8 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
||||
setToken(storedToken);
|
||||
try {
|
||||
const decoded: any = jwtDecode(storedToken);
|
||||
setUsername(decoded.username); // <-- Username speichern
|
||||
setUsername(decoded.username);
|
||||
setRole(decoded.role);
|
||||
} catch (error) {
|
||||
console.error("Token konnte nicht gelesen werden");
|
||||
}
|
||||
@@ -44,12 +52,12 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
||||
const logout = () => {
|
||||
localStorage.removeItem("token");
|
||||
setToken(null);
|
||||
setUsername(null);
|
||||
setRole(null);
|
||||
};
|
||||
|
||||
const isAuthenticated = !!token;
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ token, username, login, logout, isAuthenticated }}>
|
||||
<AuthContext.Provider value={{ token, username, role, isAdmin, login, logout, isAuthenticated }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user