aboutsummaryrefslogtreecommitdiff
path: root/web/pw-server/src/lib/auth.ts
blob: 5796096e1976c6bc2c67e8b5e1719558667d6324 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { currentUser } from "./stores/current_user";

export function set_session_token(token: string) {
  window.localStorage.setItem("session", token);
}

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);
}