100 lines
2.7 KiB
TypeScript
100 lines
2.7 KiB
TypeScript
"use client";
|
|
|
|
import { useState } from "react";
|
|
import { useAuth } from "@/app/hooks/useAuth";
|
|
import { Input } from "../../component/ui/input";
|
|
import { Button } from "../../component/ui/button";
|
|
import Link from "next/link";
|
|
import { useRouter } from "next/navigation";
|
|
|
|
export default function LoginPage() {
|
|
const { setToken } = useAuth();
|
|
const router = useRouter();
|
|
const [isLoading, setIsLoading] = useState(false);
|
|
const [error, setError] = useState("");
|
|
|
|
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
|
e.preventDefault();
|
|
setIsLoading(true);
|
|
setError("");
|
|
|
|
const formData = new FormData(e.currentTarget);
|
|
const email = formData.get("email");
|
|
const password = formData.get("password");
|
|
|
|
try {
|
|
const response = await fetch("http://localhost:3000/api/auth/login", {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({ email, password }),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error("Invalid credentials");
|
|
}
|
|
|
|
const data = await response.json();
|
|
console.log(data);
|
|
setToken(data.access_token);
|
|
router.push("/dashboard");
|
|
router.refresh();
|
|
} catch (err) {
|
|
setError("Invalid email or password");
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
return (
|
|
<div className="min-h-screen flex items-center justify-center px-4">
|
|
<div className="w-full max-w-md space-y-8">
|
|
<div className="text-center">
|
|
<h2 className="text-3xl font-bold">Welcome back</h2>
|
|
<p className="mt-2 text-gray-600 dark:text-gray-400">
|
|
Sign in to your account
|
|
</p>
|
|
</div>
|
|
|
|
<form onSubmit={handleSubmit} className="mt-8 space-y-6">
|
|
{error && (
|
|
<div className="p-3 text-sm text-red-500 bg-red-100 rounded-lg dark:bg-red-900/30">
|
|
{error}
|
|
</div>
|
|
)}
|
|
|
|
<Input
|
|
label="Email address"
|
|
name="email"
|
|
type="email"
|
|
required
|
|
placeholder="Enter your email"
|
|
/>
|
|
|
|
<Input
|
|
label="Password"
|
|
name="password"
|
|
type="password"
|
|
required
|
|
placeholder="Enter your password"
|
|
/>
|
|
|
|
<Button type="submit" isLoading={isLoading}>
|
|
Sign in
|
|
</Button>
|
|
|
|
<p className="text-center text-sm text-gray-600 dark:text-gray-400">
|
|
Dont have an account?{" "}
|
|
<Link
|
|
href="/register"
|
|
className="font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400"
|
|
>
|
|
Sign up
|
|
</Link>
|
|
</p>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|