diff options
author | Ilion Beyst <ilion.beyst@gmail.com> | 2022-04-09 10:50:17 +0200 |
---|---|---|
committer | Ilion Beyst <ilion.beyst@gmail.com> | 2022-04-09 10:50:17 +0200 |
commit | f21182ecdf33d19e0bd39bcae7ed3af243f703a5 (patch) | |
tree | 3c49c806d330b41d34789da2ba93a5ae716b09de /web/pw-server/src/lib/auth.ts | |
parent | f59bf07d570c906ec796990c0674a0d7432df366 (diff) | |
download | planetwars.dev-f21182ecdf33d19e0bd39bcae7ed3af243f703a5.tar.xz planetwars.dev-f21182ecdf33d19e0bd39bcae7ed3af243f703a5.zip |
show login errors
Diffstat (limited to 'web/pw-server/src/lib/auth.ts')
-rw-r--r-- | web/pw-server/src/lib/auth.ts | 34 |
1 files changed, 34 insertions, 0 deletions
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); +} |