Haystack/frontend/src/Login.tsx
Dmytro Kondakov e1857bd532 feat(login): implement logout functionality and redirect after login
- Added a logout function in the Settings component to clear user session data and redirect to the login page.
- Updated the Login component to redirect to the home page upon successful login.
- Adjusted styling in the Search component for better spacing in the "No results found" message.
2025-04-14 10:36:55 +02:00

65 lines
2.0 KiB
TypeScript

import { Button } from "@kobalte/core/button";
import { TextField } from "@kobalte/core/text-field";
import { Navigate } from "@solidjs/router";
import { type Component, Show, createSignal } from "solid-js";
import { isTokenValid } from "./ProtectedRoute";
import { base, postCode, postLogin } from "./network";
export const Login: Component = () => {
let form: HTMLFormElement | undefined;
const [submitted, setSubmitted] = createSignal(false);
const onSubmit: HTMLFormElement["onsubmit"] = async (e) => {
e.preventDefault();
const formData = new FormData(form);
const email = formData.get("email");
if (email == null) {
throw new Error("bruh, no email");
}
if (!submitted()) {
await postLogin(email.toString());
setSubmitted(true);
} else {
const code = formData.get("code");
if (code == null) {
throw new Error("bruh, no code");
}
const { access, refresh } = await postCode(
email.toString(),
code.toString(),
);
localStorage.setItem("access", access);
localStorage.setItem("refresh", refresh);
window.location.href = "/";
}
};
const isAuthorized = isTokenValid();
return (
<>
{base}
<Show when={!isAuthorized} fallback={<Navigate href="/" />}>
<form ref={form} onSubmit={onSubmit}>
<TextField name="email">
<TextField.Label>Email</TextField.Label>
<TextField.Input />
</TextField>
<Show when={submitted()}>
<TextField name="code">
<TextField.Label>Code</TextField.Label>
<TextField.Input />
</TextField>
</Show>
<Button type="submit">Submit</Button>
</form>
</Show>
</>
);
};