From f21182ecdf33d19e0bd39bcae7ed3af243f703a5 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Sat, 9 Apr 2022 10:50:17 +0200 Subject: show login errors --- web/pw-server/src/lib/auth.ts | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) (limited to 'web/pw-server/src/lib/auth.ts') diff --git a/web/pw-server/src/lib/auth.ts b/web/pw-server/src/lib/auth.ts index 3f77c58..5796096 100644 --- a/web/pw-server/src/lib/auth.ts +++ b/web/pw-server/src/lib/auth.ts @@ -1,3 +1,5 @@ +import { currentUser } from "./stores/current_user"; + export function set_session_token(token: string) { window.localStorage.setItem("session", token); } @@ -5,3 +7,35 @@ export function set_session_token(token: string) { export function get_session_token(): string | null { return window.localStorage.getItem("session"); } + +export function clear_session_token() { + window.localStorage.removeItem("session"); +} + +export type Credentials = { + username: string; + password: string; +}; + +export async function login(credentials: Credentials) { + let response = await fetch("/api/login", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(credentials), + }); + + if (response.status == 403) { + throw new Error("invalid credentials"); + } + if (!response.ok) { + throw new Error(response.statusText); + } + + let token = response.headers.get("Token"); + set_session_token(token); + + const user = await response.json(); + currentUser.set(user); +} -- cgit v1.2.3