mirror of
https://github.com/donpat1to/Schichtenplaner.git
synced 2025-11-30 22:45:46 +01:00
68 lines
1.7 KiB
TypeScript
68 lines
1.7 KiB
TypeScript
// frontend/src/contexts/AuthContext.tsx
|
|
import React, { createContext, useContext, useState, useEffect } from 'react';
|
|
import { authService, User, LoginRequest } from '../services/authService';
|
|
|
|
interface AuthContextType {
|
|
user: User | null;
|
|
login: (credentials: LoginRequest) => Promise<void>;
|
|
logout: () => void;
|
|
hasRole: (roles: string[]) => boolean;
|
|
loading: boolean;
|
|
}
|
|
|
|
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
|
|
|
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
|
const [user, setUser] = useState<User | null>(null);
|
|
const [loading, setLoading] = useState(true);
|
|
|
|
useEffect(() => {
|
|
// User aus localStorage laden beim Start
|
|
const savedUser = authService.getCurrentUser();
|
|
if (savedUser) {
|
|
setUser(savedUser);
|
|
}
|
|
setLoading(false);
|
|
}, []);
|
|
|
|
const login = async (credentials: LoginRequest) => {
|
|
try {
|
|
const response = await authService.login(credentials);
|
|
setUser(response.user);
|
|
} catch (error) {
|
|
console.error('AuthContext: Login fehlgeschlagen', error);
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
const logout = () => {
|
|
authService.logout();
|
|
setUser(null);
|
|
};
|
|
|
|
const hasRole = (roles: string[]) => {
|
|
return user ? roles.includes(user.role) : false;
|
|
};
|
|
|
|
const value = {
|
|
user,
|
|
login,
|
|
logout,
|
|
hasRole,
|
|
loading
|
|
};
|
|
|
|
return (
|
|
<AuthContext.Provider value={value}>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
);
|
|
};
|
|
|
|
export const useAuth = () => {
|
|
const context = useContext(AuthContext);
|
|
if (context === undefined) {
|
|
throw new Error('useAuth must be used within an AuthProvider');
|
|
}
|
|
return context;
|
|
}; |