lydstyrke/src/routes/login/login-form.svelte

85 lines
2.9 KiB
Svelte
Raw Normal View History

2024-04-21 00:15:50 +00:00
<svelte:options runes={true} />
<script lang="ts">
import { Input } from "$lib/components/ui/input";
import * as Form from "$lib/components/ui/form";
import { formSchema, type FormSchema } from "./schema";
import {OpenSubsonic} from "$lib/opensubsonic";
import {
type SuperValidated,
type Infer,
superForm,
} from "sveltekit-superforms";
import { zodClient } from "sveltekit-superforms/adapters";
import {Circle2} from "svelte-loading-spinners";
import {Md5} from "ts-md5";
import Cookies from 'js-cookie'
import {goto} from "$app/navigation";
let { data }: SuperValidated<Infer<FormSchema>> = $props<{ data: SuperValidated<Infer<FormSchema>> }>();
const form = superForm(data, {
validators: zodClient(formSchema),
onUpdated() {
OpenSubsonic.username = previousForm.get("username");
OpenSubsonic.password = previousForm.get("password");
let path = OpenSubsonic.getApiPath("ping");
fetch(path).then(async (data) => {
let res = (await data.json())["subsonic-response"];
if (res.status === "ok") {
OpenSubsonic.storeCredentials();
loading = false;
let route = Cookies.get("preLoginRoute")
Cookies.remove("preLoginRoute", { path: "/login" })
goto(route);
}
else {
error = true;
loading = false;
}
});
},
onSubmit({ formData }) {
loading = true;
previousForm = formData;
}
});
let previousForm: FormData = $state({});
const { form: formData, enhance } = form;
let error = $state(false);
let loading = $state(false);
</script>
<form method="POST" use:enhance>
<Form.Field {form} name="username" class="px-3">
<Form.Control let:attrs>
<Form.Label>Username:</Form.Label>
<Input {...attrs} bind:value={$formData.username}></Input>
</Form.Control>
<Form.FieldErrors></Form.FieldErrors>
</Form.Field>
<Form.Field {form} name="password" class="px-3">
<Form.Control let:attrs>
<Form.Label>Password:</Form.Label>
<Input {...attrs} type="password" bind:value={$formData.password}></Input>
</Form.Control>
<Form.FieldErrors></Form.FieldErrors>
</Form.Field>
<div class="flex flex-row justify-center pt-2">
{#if loading}
<Circle2
size="40" unit="px"
colorOuter="#0892B4" durationOuter="1s"
colorCenter="white" durationCenter="3s"
colorInner="#9cc1c9" durationInner="2s"
/>
{:else}
<Form.Button>Login</Form.Button>
{/if}
</div>
{#if error}
<p class="pt-2 text-sm text-destructive">Username or Password incorrect</p>
{/if}
</form>