Files
KeepNote/dev/auth.html
T

76 lines
2.8 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Log In / Register</title>
<link rel="stylesheet" href="main.css">
<script src="./cookies.js"></script>
<script src="./jwt.js"></script>
</head>
<body>
<h1>KeepNote</h1>
<div id="error"></div>
<form id="login">
<h2>Log in</h2>
<input name="username" type="text" placeholder="username" />
<input name="password" type="password" placeholder="password" />
<button>Log In</button>
</form>
<form id="register">
<h2>Register</h2>
<input name="username" type="text" placeholder="username" />
<input name="email" type="text" placeholder="email" />
<input name="password" type="password" placeholder="password" />
<button>Register</button>
</form>
<script>
const API = "http://127.0.0.1:8081";
const errorBox = document.getElementById("error");
function showError(msg) {
errorBox.textContent = msg;
}
async function loginAction(event) {
event.preventDefault();
showError("");
const data = Object.fromEntries(new FormData(event.target).entries());
const res = await fetch(`${API}/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
if (!res.ok) {
showError(`login failed: ${res.status} ${await res.text()}`);
return;
}
const resp = await res.json();
cookieBaker("accessToken", resp.accessToken, new Date(new Date().getTime() + 10 * 60000), "/", null, null, null, null);
window.location.replace("./notes.html");
}
async function registerAction(event) {
event.preventDefault();
showError("");
const data = Object.fromEntries(new FormData(event.target).entries());
const res = await fetch(`${API}/auth/register`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
if (!res.ok) {
showError(`register failed: ${res.status} ${await res.text()}`);
return;
}
const resp = await res.json();
cookieBaker("accessToken", resp.accessToken, new Date(new Date().getTime() + 10 * 60000), "/", null, null, null, null);
window.location.replace("./notes.html");
}
document.getElementById("login").addEventListener("submit", loginAction);
document.getElementById("register").addEventListener("submit", registerAction);
</script>
</body>
</html>