mirror of
https://github.com/donpat1to/Schichtenplaner.git
synced 2025-11-30 22:45:46 +01:00
added init files
This commit is contained in:
69
frontend/src/contexts/AuthContext.tsx
Normal file
69
frontend/src/contexts/AuthContext.tsx
Normal file
@@ -0,0 +1,69 @@
|
||||
// frontend/src/contexts/AuthContext.tsx
|
||||
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||
import { authService, User, LoginRequest, RegisterRequest } from '../services/authService';
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
login: (credentials: LoginRequest) => Promise<void>;
|
||||
register: (userData: RegisterRequest) => 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(() => {
|
||||
// Beim Start User aus localStorage laden
|
||||
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) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
const register = async (userData: RegisterRequest) => {
|
||||
try {
|
||||
const response = await authService.register(userData);
|
||||
setUser(response.user);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
authService.logout();
|
||||
setUser(null);
|
||||
};
|
||||
|
||||
const hasRole = (roles: string[]) => {
|
||||
return user ? roles.includes(user.role) : false;
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, login, register, logout, hasRole, loading }}>
|
||||
{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;
|
||||
};
|
||||
Reference in New Issue
Block a user