| 1 | import { useState } from "react";
|
|---|
| 2 | import { useNavigate } from "react-router-dom";
|
|---|
| 3 | import axiosInstance, { scheduleTokenRefresh } from "../api/axiosInstance";
|
|---|
| 4 | import { useAuth } from "../context/authContext";
|
|---|
| 5 | import type { User } from "../utils/types";
|
|---|
| 6 |
|
|---|
| 7 | const Login = () => {
|
|---|
| 8 | const [username, setUsername] = useState("");
|
|---|
| 9 | const [password, setPassword] = useState("");
|
|---|
| 10 | const [error, setError] = useState<string | null>(null);
|
|---|
| 11 | const { setUser } = useAuth();
|
|---|
| 12 | const navigate = useNavigate();
|
|---|
| 13 |
|
|---|
| 14 | const handleLogin = async (e: React.FormEvent) => {
|
|---|
| 15 | e.preventDefault();
|
|---|
| 16 | try {
|
|---|
| 17 | const response = await axiosInstance.post<{
|
|---|
| 18 | user: User;
|
|---|
| 19 | tokenExpiresIn: number;
|
|---|
| 20 | }>("/auth/login", { username, password });
|
|---|
| 21 | scheduleTokenRefresh(response.data.tokenExpiresIn);
|
|---|
| 22 | setUser(response.data.user);
|
|---|
| 23 | navigate("/");
|
|---|
| 24 | } catch (error) {
|
|---|
| 25 | setError("Login failed. Please check your credentials.");
|
|---|
| 26 | }
|
|---|
| 27 | };
|
|---|
| 28 | return (
|
|---|
| 29 | <div className="flex flex-col items-center justify-center min-h-[90vh] bg-gray-100">
|
|---|
| 30 | <h2 className="text-2xl mb-4">Login</h2>
|
|---|
| 31 | <form
|
|---|
| 32 | onSubmit={handleLogin}
|
|---|
| 33 | className="bg-white p-6 rounded shadow-md w-80"
|
|---|
| 34 | >
|
|---|
| 35 | {error && <p className="text-red-500 mb-4">{error}</p>}
|
|---|
| 36 | <div className="mb-4">
|
|---|
| 37 | <label className="block text-gray-700 mb-2" htmlFor="username">
|
|---|
| 38 | Username
|
|---|
| 39 | </label>
|
|---|
| 40 | <input
|
|---|
| 41 | type="text"
|
|---|
| 42 | id="username"
|
|---|
| 43 | className="w-full p-2 border border-gray-300 rounded"
|
|---|
| 44 | value={username}
|
|---|
| 45 | onChange={(e) => setUsername(e.target.value)}
|
|---|
| 46 | />
|
|---|
| 47 | </div>
|
|---|
| 48 | <div className="mb-4">
|
|---|
| 49 | <label className="block text-gray-700 mb-2" htmlFor="password">
|
|---|
| 50 | Password
|
|---|
| 51 | </label>
|
|---|
| 52 | <input
|
|---|
| 53 | type="password"
|
|---|
| 54 | id="password"
|
|---|
| 55 | className="w-full p-2 border border-gray-300 rounded"
|
|---|
| 56 | value={password}
|
|---|
| 57 | onChange={(e) => setPassword(e.target.value)}
|
|---|
| 58 | />
|
|---|
| 59 | </div>
|
|---|
| 60 | <button
|
|---|
| 61 | type="submit"
|
|---|
| 62 | className="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors duration-200 w-full cursor-pointer"
|
|---|
| 63 | >
|
|---|
| 64 | Login
|
|---|
| 65 | </button>
|
|---|
| 66 | </form>
|
|---|
| 67 | </div>
|
|---|
| 68 | );
|
|---|
| 69 | };
|
|---|
| 70 |
|
|---|
| 71 | export default Login;
|
|---|