simple-fs-server/routes/api/login.ts

67 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-01-05 18:18:07 +09:00
import { HandlerContext } from "$fresh/server.ts";
import { setCookie } from "http/cookie.ts";
import { Status } from "http/http_status.ts";
import { connectDB } from "../../src/user/db.ts";
import { getUser, verifyUser } from "../../src/user/user.ts";
import { create as createJWT } from "djwt";
import { prepareSecretKey } from "../../util/secret.ts";
2023-01-06 23:22:00 +09:00
async function POST(req: Request, _ctx: HandlerContext): Promise<Response> {
2023-01-06 18:24:27 +09:00
const url = new URL(req.url);
const form = await req.formData();
const username = form.get("username");
const password = form.get("password");
if (username && password) {
2023-01-06 23:22:00 +09:00
const DB = await connectDB();
2023-01-06 18:24:27 +09:00
const user = await getUser(DB, username.toString());
if (user) {
2023-01-06 23:22:00 +09:00
const SECRET_KEY = await prepareSecretKey();
2023-01-06 18:24:27 +09:00
if (await verifyUser(user, password.toString())) {
const headers = new Headers();
const jwt = await createJWT({ alg: "HS512", typ: "JWT" }, {
username: user.name,
}, SECRET_KEY);
setCookie(headers, {
name: "auth",
value: jwt,
httpOnly: true,
sameSite: "Strict",
maxAge: 60 * 60 * 24 * 7,
domain: url.hostname,
path: "/",
secure: url.protocol === "https:",
});
2023-01-05 18:18:07 +09:00
2023-01-06 18:24:27 +09:00
headers.set("Location", "/");
return new Response(null, {
status: Status.SeeOther, // See Other
headers: headers,
});
}
2023-01-05 18:18:07 +09:00
}
2023-01-06 18:24:27 +09:00
}
2023-01-05 18:18:07 +09:00
2023-01-06 18:24:27 +09:00
return new Response(
`<!DOCTYPE html><html>
2023-01-05 18:18:07 +09:00
<head> <title> Login Failed </title> </head>
<body>
<h1> Login Failed </h1>
<p> <a href="/"> Back to Home </a> </p>
<script>
document.location.href = "/login";
</script>
</body>
2023-01-06 18:24:27 +09:00
</html>`,
{
headers: {
"Content-Type": "text/html",
},
status: Status.Forbidden,
},
);
2023-01-05 18:18:07 +09:00
}
export const handler = {
2023-01-06 18:24:27 +09:00
POST,
};