aboutsummaryrefslogtreecommitdiffstats
path: root/src/routes/(app)/register/+page.svelte
blob: 5783059a4dc5210d7dfe0ac4a26e0f8042b5c521 (plain) (blame)
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
<script>
  import punks from "$lib/punks";
  import { upload } from "$lib/upload";
  import { afterNavigate, invalidateAll } from "$app/navigation";
  import { applyAction, deserialize } from "$app/forms";
  import { tick } from "svelte";
  import { fly } from "svelte/transition";
  import { enhance } from "$app/forms";

  import Pin from "$comp/Pin.svelte";
  import Icon from "$comp/Icon.svelte";
  import Spinner from "$comp/Spinner.svelte";

  import { focus, fail } from "$lib/utils";
  import { avatar, password, loginRedirect } from "$lib/store";
  import { t } from "$lib/translations";
  import { page } from "$app/stores";
  import { generate } from "$lib/nostr";
  import {
    NumberDictionary,
    uniqueNamesGenerator,
    colors,
    adjectives,
    animals,
  } from "unique-names-generator";

  export let form;
  export let data;

  $: data && ($avatar = undefined);
  let username;
  let { index } = data;

  let cleared;
  let clear = () => {
    if (!cleared) {
      cleared = true;
      username = "";
      $password = "";
      revealPassword = false;
    }
  };

  let refresh = async () => {
    username = uniqueNamesGenerator({
      dictionaries: [animals, NumberDictionary.generate({ min: 10, max: 99 })],
      length: 2,
      separator: "",
    });

    $password = uniqueNamesGenerator({
      dictionaries: [colors, NumberDictionary.generate({ min: 100, max: 999 })],
      length: 2,
      separator: "",
    });

    revealPassword = true;
  };

  afterNavigate(async () => {
    try {
      await invalidateAll();
    } catch (e) {
      console.log(e);
    }
  });

  let token, formElement;
  let code = [];
  let redirect;

  $: need2fa = form?.message === "2fa";
  let cancel = () => (need2fa = false);
  $: if (form?.message === "2fa" && form.token === token) token = "";

  let email, btn;

  $: update(form);
  let update = (form) => form && ({ username, password: $password } = form);

  $: token && token?.length === 6 && tick().then(() => btn.click());

  let revealPassword;

  let loading;
  async function handleSubmit(e) {
    loading = true;

    let data = new FormData(this);
    let user = Object.fromEntries(data);
    await generate(user);

    for (let k in user) {
      data.set(k, user[k]);
    }

    data.set("profile", punks[index]);
    if ($avatar) {
      try {
        let { hash } = JSON.parse(
          await upload($avatar.file, $avatar.type, $avatar.progress, token)
        );

        data.set("profile", hash);
        await fetch(`/api/public/${hash}.webp`, {
          cache: "reload",
          mode: "no-cors",
        });
      } catch (e) {
        console.log("problem uploading avatar", e);
      }
    }

    const response = await fetch("/register", {
      method: "POST",
      body: data,
    });

    const result = deserialize(await response.text());

    if (result.type === "success") {
      await invalidateAll();
    }

    applyAction(result);
    loading = false;
  }

  let avatarInput;
  $: src = `/api/public/${punks[index]}.webp`;
  let decr = () => (index = index <= 0 ? 63 : index - 1);
  let incr = () => (index = index >= 63 ? 0 : index + 1);
  let selectAvatar = () => avatarInput.click();

  let progress;
  let handleFile = async ({ target }) => {
    let type = "profile";
    let file = target.files[0];
    if (!file) return;

    if (file.size > 10000000) form.error = "File too large";
    $avatar = { file, type, progress };

    var reader = new FileReader();
    reader.onload = async (e) => {
      src = e.target.result;
    };

    reader.readAsDataURL(file);
  };
</script>

{#if need2fa}
  <Pin bind:value={token} title="Enter 2FA Code" {cancel} notify={false} />
{/if}

<div class="pt-4">
  <div class="w-[243px] mx-auto">
    <a href="/">
      <Icon icon="logo" />
    </a>
  </div>

  <div class="flex justify-center items-center">
    <div
      class="shadow-xl rounded-3xl p-4 pt-0 space-y-5 w-full mx-5 md:mx-0 md:w-[400px]"
    >
      <input
        type="file"
        class="hidden"
        bind:this={avatarInput}
        on:change={(e) => handleFile(e, "profile")}
      />

      <div class="relative">
        <button
          class="absolute w-8 h-12 left-12 bg-white rounded top-12"
          on:click={decr}
        >
          <Icon icon="chevron-left" style="w-8 " />
        </button>
        <div class="relative w-32 mx-auto" on:click={selectAvatar}>
          <button
            class="w-32 h-32 rounded-full border-4 border-white overflow-hidden flex mx-auto relative"
          >
            <img
              {src}
              class="w-full h-full object-cover object-center overflow-hidden"
              alt={username}
            />
          </button>
          <button
            class="absolute bg-white rounded-full p-2 mx-auto right-0 bottom-0 z-10 bg-opacity-80"
          >
            <Icon icon="upload" style="w-8" />
          </button>
        </div>
        <button
          class="absolute w-8 h-12 right-12 bg-white rounded top-12"
          on:click={incr}
        >
          <Icon icon="chevron-left" style="w-8 rotate-180" />
        </button>
      </div>

      {#if form?.error}
        <div class="text-red-600 text-center" in:fly>
          {form.error}
        </div>
      {/if}

      <form
        class="space-y-5"
        on:submit|preventDefault={handleSubmit}
        method="POST"
      >
        <input
          type="hidden"
          name="loginRedirect"
          value={$loginRedirect || $page.url.searchParams.get("redirect")}
        />
        <input type="hidden" name="token" value={token} />

        <div class="relative">
          <label for="username" class="font-semibold"
            >{$t("login.username")}</label
          >
          <input
            use:focus
            tabindex="1"
            name="username"
            type="text"
            required
            class="bg-primary"
            bind:value={username}
            on:focus={clear}
            autocapitalize="none"
          />
          <button
            type="button"
            on:click={refresh}
            class="absolute right-0 top-4"
            tabindex="5"
          >
            <Icon icon="random" style="w-10 m-4" />
          </button>
        </div>

        <div class="relative">
          <label for="password" class="block font-semibold"
            >{$t("login.password")}</label
          >
          {#if revealPassword}
            <input
              tabindex="2"
              name="password"
              type="text"
              required
              class="bg-primary"
              bind:value={$password}
              autocapitalize="none"
            />
          {:else}
            <input
              tabindex="2"
              name="password"
              type="password"
              required
              class="bg-primary"
              bind:value={$password}
              autocapitalize="none"
              on:focus={clear}
            />
          {/if}
          <button
            type="button"
            tabindex="4"
            on:click={() => (revealPassword = !revealPassword)}
            class="absolute right-0 top-4"
          >
            <Icon icon={revealPassword ? "eye" : "eye-off"} style="m-6" />
          </button>
        </div>

        <p class="text-secondary text-sm">
          {$t("login.passwordRecommendation")}
        </p>

        <button
          tabindex="3"
          type="submit"
          class="bg-black text-white w-full rounded-2xl p-4 font-semibold hover:opacity-80"
          disabled={loading}
          bind:this={btn}
        >
          {#if loading}
            <Spinner />
          {:else}
            {$t("login.register")}
          {/if}
        </button>
      </form>

      <p class="text-secondary text-center font-medium">
        {$t("login.haveAccount")}
        <a
          href={"/login"}
          class="block md:inline text-black underline underline-offset-4 hover:opacity-80"
        >
          {$t("login.signIn")}
        </a>
      </p>
    </div>
  </div>
</div>