aboutsummaryrefslogtreecommitdiff
path: root/web/pw-server/src/routes/register.svelte
blob: f09ccad130355e00dd2fdab515821cdbd3a3c351 (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
<script lang="ts">
  import * as auth from "$lib/auth";
  import { goto } from "$app/navigation";

  let username: string | undefined;
  let password: string | undefined;

  let registrationErrors: string[] = [];

  const onSubmit = async () => {
    if (username === undefined || username.trim() === "") {
      return;
    }

    if (password === undefined || password.trim() === "") {
      return;
    }

    registrationErrors = [];

    const response = await fetch("/api/register", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        username,
        password,
      }),
    });

    if (response.ok) {
      await auth.login({ username, password });
      goto("/");
    } else {
      const resp = await response.json();
      const error = resp["error"];
      if (response.status == 422 && error["type"] === "validation_failed") {
        registrationErrors = error["validation_errors"];
      }
    }
  };
</script>

<div class="page-card">
  <div class="page-card-content">
    <h1 class="page-card-header">Create account</h1>
    {#if registrationErrors.length > 0}
      <ul class="error-message-list">
        {#each registrationErrors as errorMessage}
          <li class="error-message">{errorMessage}</li>
        {/each}
      </ul>
    {/if}

    <form class="account-form" on:submit|preventDefault={onSubmit}>
      <label for="username">Username</label>
      <input name="username" bind:value={username} />
      <label for="password">Password</label>
      <input type="password" name="password" bind:value={password} />
      <button type="submit">Submit</button>
    </form>
  </div>
</div>

<style lang="scss">
  @import "src/styles/account_forms.scss";

  .error-message-list {
    color: red;
  }
</style>