now login page waiting for the request answer instead of redirecting

This commit is contained in:
Hikmet 2023-03-27 20:04:30 +03:00
parent de14f8cdbf
commit 9eb4ecfbda
2 changed files with 20 additions and 4 deletions

View File

@ -10,9 +10,24 @@ import { useState } from "react";
export default function LoginPage() {
const [password, setPassword] = useState("");
const [error, setError] = useState(false);
return (
<form method="POST" action="/api/admin/login">
<form
onSubmit={(e) => {
e.preventDefault();
fetch("/api/admin/login", { method: "POST", body: password }).then(
(res) =>
res.json().then((j) => {
if (j.error) {
setError(true);
} else {
location.href = "/admin/temalar";
}
})
);
}}
>
<Paper
elevation={5}
sx={{
@ -40,6 +55,7 @@ export default function LoginPage() {
</Stack>
<Stack flexDirection="row" columnGap="1rem">
<OutlinedInput
error={error}
name="password"
onChange={(e) => setPassword(e.target.value)}
value={password}

View File

@ -5,7 +5,7 @@ import * as jose from "jose";
async function handler(req: NextApiRequest, res: NextApiResponse) {
switch (req.method) {
case "POST":
const password = req.body.password;
const password = req.body;
if (password === process.env.ADMIN_PASSWORD!) {
const secret = new TextEncoder().encode(process.env.JWT_SECRET_KEY!);
@ -16,10 +16,10 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
setCookie("token", jwt, { req, res, maxAge: 60 * 60 * 24 * 360 });
return res.redirect(307, "/admin/temalar");
return res.status(200).send({ error: null });
}
return res.redirect(307, "/admin/login");
return res.status(200).send({ error: "Wrong password" });
default:
return res.status(405).json({ error: "Unsopported request method" });