85 lines
2.4 KiB
Plaintext
85 lines
2.4 KiB
Plaintext
---
|
|
import Layout from '../layouts/Layout.astro';
|
|
import NavBar from '../components/NavBar.astro';
|
|
|
|
import { getUserByNickOrEmail, updateLastLogin } from '../lib/db/users';
|
|
|
|
import { verify } from 'argon2';
|
|
|
|
let error = "";
|
|
|
|
if(Astro.request.method === "POST") {
|
|
const data = await Astro.request.formData();
|
|
const username = data.get("username") as string | "";
|
|
const password = data.get("password") as string | "";
|
|
|
|
if(username === "") {
|
|
error = "username is required";
|
|
Astro.redirect("/login");
|
|
}
|
|
|
|
if(password === "") {
|
|
error = "password is required";
|
|
Astro.redirect("/login");
|
|
}
|
|
|
|
const user = await getUserByNickOrEmail(username as string);
|
|
|
|
if(user !== null && await verify(user.password, password as string)) {
|
|
const sessionTime = import.meta.env.SESSION_TIME_MINUTES * 60;
|
|
|
|
const res = await fetch(`${Astro.url.origin}/api/auth/generateAccessToken`, {
|
|
method: 'POST',
|
|
body: JSON.stringify({
|
|
username,
|
|
createdFrom: 'loginForm',
|
|
duration: sessionTime
|
|
}),
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': 'Bearer ' + import.meta.env.MASTER_ACCESSTOKEN
|
|
}
|
|
});
|
|
|
|
const token = (await res.json()).accessToken;
|
|
|
|
await updateLastLogin(user);
|
|
|
|
Astro.cookies.set("sessionToken", token, {
|
|
path: "/",
|
|
maxAge: sessionTime,
|
|
sameSite: "lax",
|
|
secure: true
|
|
});
|
|
|
|
Astro.cookies.set("username", username, {
|
|
path: "/",
|
|
maxAge: sessionTime,
|
|
sameSite: "lax",
|
|
secure: true
|
|
});
|
|
|
|
Astro.cookies.set("userid", user._id?.toString() as string, {
|
|
path: "/",
|
|
maxAge: sessionTime,
|
|
sameSite: "lax",
|
|
secure: true
|
|
});
|
|
|
|
return Astro.redirect("/game");
|
|
} else {
|
|
error = "invalid username or password";
|
|
return Astro.redirect("/login");
|
|
}
|
|
}
|
|
---
|
|
|
|
<Layout title="Login">
|
|
<NavBar loggedIn="false" active="login" />
|
|
<form method="POST">
|
|
<input type="text" name="username" placeholder="username" /><br />
|
|
<input type="password" name="password" placeholder="password" /><br />
|
|
<input type="submit" value="login" />
|
|
{ error !== "" ? <p style="color: red;">{error}</p> : "" }
|
|
</form>
|
|
</Layout> |