ADD:added decode jwt token and automated login to dashboard after login
This commit is contained in:
@@ -1,22 +1,35 @@
|
||||
import { useState } from 'react';
|
||||
import { useAuth } from './AuthContext';
|
||||
import { login as apiLogin } from './api';
|
||||
import { jwtDecode } from 'jwt-decode';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
export default function LoginPage() {
|
||||
const { login } = useAuth();
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const navigate = useNavigate(); // ← Navigation-Hook
|
||||
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const data = await apiLogin(email, password);
|
||||
console.log(data);
|
||||
// Token aus JWT extrahieren (hier: UserID im Token Payload)
|
||||
// Für Demo: Einfach Dummy UserID setzen, oder später JWT decode implementieren
|
||||
login(data.token, 'user-id-from-token');
|
||||
} catch {
|
||||
type MyJwtPayload = {
|
||||
userId: string
|
||||
email: string;
|
||||
role: string;
|
||||
} & object;
|
||||
const decodedData = jwtDecode<MyJwtPayload>(data.token);
|
||||
login(data.token, decodedData.userId, decodedData.role);
|
||||
// Nach dem Login zur Dashboard-Seite navigieren
|
||||
setTimeout(() => {
|
||||
navigate('/');
|
||||
}, 1000);
|
||||
} catch {
|
||||
setError('Login fehlgeschlagen');
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user