aboutsummaryrefslogtreecommitdiff
path: root/fe/src/lib/LoginForm.svelte
blob: cf5febf898a321967db6015c47ab9bc0c40a53eb (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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<script lang="ts">
  import { token, user, preferences } from "../stores/auth";
  import Card from "./Card.svelte";
  import { apiURL } from "../utils";

  let credentials: CredentialObject = {
    username: "",
    password: "",
  };

  let error: string | null = null;

  interface CredentialObject {
    username: string;
    password: string;
  }

  function prepareCredentials({
    username,
    password,
  }: CredentialObject): string {
    return btoa(`${username}:${password}`);
  }

  async function onSubmit(e: Event) {
    if (!credentials.username || !credentials.password) {
      error = "please enter your username and password";
      return;
    }
    const auth = prepareCredentials(credentials);

    const response = await fetch(apiURL("auth"), {
      method: "POST",
      headers: {
        Authorization: `Basic ${auth}`,
      },
    });

    if (response.status === 401) {
      error = "Your username or password is wrong";
      return;
    }

    if (response.ok) {
      const {
        token: apiToken,
        user: userData,
        preferences: userPreferences,
      } = await response.json();
      user.setUser(userData);
      preferences.setPreference(userPreferences);
      token.authenticate(apiToken);
    }

    error = null;
  }
</script>

<Card>
  <form class="form" on:submit|preventDefault={onSubmit}>
    <div class="form input group">
      <label for="username">Username</label>
      <input
        bind:value={credentials.username}
        id="username"
        name="username"
        type="text"
        autocomplete="username"
      />
    </div>
    <div class="form input group">
      <label for="password">Password</label>
      <input
        bind:value={credentials.password}
        id="password"
        name="password"
        type="password"
        autocomplete="current-password"
      />
    </div>
    {#if error}
      <p class="error">{error}</p>
    {/if}
    <button type="submit">Log in</button>
  </form>
</Card>