aboutsummaryrefslogtreecommitdiff
path: root/web/pw-server/src/lib/components/navbar/UserControls.svelte
blob: e9dbab1f6c51f329c117eb8625b646633d3d56bc (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
<script lang="ts">
  import { get_session_token } from "$lib/auth";

  import { onMount } from "svelte";

  let user = null;

  onMount(async () => {
    const session_token = get_session_token();
    if (!session_token) {
      return;
    }

    let response = await fetch("/api/users/me", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${session_token}`,
      },
    });

    if (!response.ok) {
      throw response.statusText;
    }

    user = await response.json();
  });

  function signOut() {
    // TODO: destroy session on server
    user = null;
  }
</script>

<div class="user-controls">
  {#if user}
    <div class="current-user-name">
      {user["username"]}
    </div>
    <div class="sign-out" on:click={signOut}>Sign out</div>
  {:else}
    <a class="account-href" href="login">Sign in</a>
    <a class="account-href" href="register">Sign up</a>
  {/if}
</div>

<style lang="scss">
  @mixin navbar-item {
    font-size: 18px;
    font-family: Helvetica, sans-serif;
    padding: 4px 8px;
  }

  .account-href {
    @include navbar-item;
    color: #eee;
    text-decoration: none;
  }

  .current-user-name {
    @include navbar-item;
    color: #fff;
  }

  .sign-out {
    @include navbar-item;
    color: #ccc;
    cursor: pointer;
  }

  .user-controls {
    display: flex;
    align-items: center;
  }
</style>