125 lines
3.1 KiB
JavaScript
125 lines
3.1 KiB
JavaScript
import React, { useState } from 'react';
|
|
import { useNavigate, useLocation } from 'react-router-dom';
|
|
import { useAuth } from '../context/useAuth';
|
|
import MainCard from '../components/MainCard';
|
|
import { CardContent } from '@/components/ui/card';
|
|
import { Input } from '@/components/ui/input';
|
|
import { Label } from '@/components/ui/label';
|
|
import { Button } from '@/components/ui/button';
|
|
import {
|
|
Alert,
|
|
AlertDescription,
|
|
} from '@/components/ui/alert';
|
|
import {KeyRound} from 'lucide-react';
|
|
const LoginPage = () => {
|
|
const [username, setUsername] = useState('');
|
|
const [password, setPassword] = useState('');
|
|
const [error, setError] = useState('');
|
|
const [loading, setLoading] = useState(false);
|
|
|
|
const { login } = useAuth();
|
|
const navigate = useNavigate();
|
|
const location = useLocation();
|
|
|
|
const from =
|
|
location.state?.from?.pathname || '/';
|
|
|
|
const handleSubmit = async (e) => {
|
|
e.preventDefault();
|
|
|
|
if (loading) {
|
|
return;
|
|
}
|
|
|
|
setError('');
|
|
setLoading(true);
|
|
|
|
try {
|
|
await login(username, password);
|
|
navigate(from, { replace: true });
|
|
} catch (err) {
|
|
setError(
|
|
'Nom d\'utilisateur ou mot de passe incorrect',
|
|
);
|
|
console.error(err);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<MainCard title="Connexion" icon={KeyRound}>
|
|
<CardContent>
|
|
{error && (
|
|
<Alert
|
|
variant="destructive"
|
|
className="mb-4"
|
|
>
|
|
<AlertDescription>
|
|
{error}
|
|
</AlertDescription>
|
|
</Alert>
|
|
)}
|
|
|
|
<form
|
|
onSubmit={handleSubmit}
|
|
className="space-y-4"
|
|
>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="username">
|
|
Nom d'utilisateur:
|
|
</Label>
|
|
|
|
<Input
|
|
id="username"
|
|
type="text"
|
|
autoComplete="username"
|
|
value={username}
|
|
onChange={(e) =>
|
|
setUsername(e.target.value)
|
|
}
|
|
disabled={loading}
|
|
required
|
|
/>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<Label htmlFor="password">
|
|
Mot de passe:
|
|
</Label>
|
|
|
|
<Input
|
|
className="current-password"
|
|
id="password"
|
|
type="password"
|
|
autoComplete="current-password"
|
|
value={password}
|
|
onChange={(e) =>
|
|
setPassword(e.target.value)
|
|
}
|
|
disabled={loading}
|
|
required
|
|
/>
|
|
</div>
|
|
|
|
<Button
|
|
type="submit"
|
|
className="w-full"
|
|
disabled={loading}
|
|
>
|
|
{loading ? (
|
|
<span className="flex items-center justify-center gap-2">
|
|
<span className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
|
|
Connexion...
|
|
</span>
|
|
) : (
|
|
'Se connecter'
|
|
)}
|
|
</Button>
|
|
</form>
|
|
</CardContent>
|
|
</MainCard>
|
|
);
|
|
};
|
|
|
|
export default LoginPage; |