diff options
| author | Doog <157747121+doogongithub@users.noreply.github.com> | 2024-02-24 20:08:35 -0500 |
|---|---|---|
| committer | Doog <157747121+doogongithub@users.noreply.github.com> | 2024-02-24 20:08:35 -0500 |
| commit | e37c73e33a4aaf7fb8d25b5af03627f20bcda19f (patch) | |
| tree | 277a534e826325e25f881e61e322b4e2e7ec94f9 /fe/src/stores | |
| parent | 3eafb413a48cde60dea8a7355ee621c6acca952f (diff) | |
add gitignore
Diffstat (limited to 'fe/src/stores')
| -rw-r--r-- | fe/src/stores/auth.ts | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/fe/src/stores/auth.ts b/fe/src/stores/auth.ts new file mode 100644 index 0000000..7e70cda --- /dev/null +++ b/fe/src/stores/auth.ts | |||
| @@ -0,0 +1,48 @@ | |||
| 1 | import type { Invalidator, Subscriber, Unsubscriber } from 'svelte/store'; | ||
| 2 | import { writable, derived } from 'svelte/store'; | ||
| 3 | |||
| 4 | type Nullable<T> = T | null; | ||
| 5 | |||
| 6 | interface User { | ||
| 7 | uuid: string; | ||
| 8 | username: string; | ||
| 9 | } | ||
| 10 | |||
| 11 | interface TokenStore { | ||
| 12 | subscribe: (run: Subscriber<Nullable<string>>, invalidate: Invalidator<Nullable<string>>) => Unsubscriber, | ||
| 13 | authenticate: (newToken: string) => void, | ||
| 14 | unauthenticate: () => void | ||
| 15 | } | ||
| 16 | |||
| 17 | function createTokenStore(): TokenStore { | ||
| 18 | const storedToken = localStorage.getItem("token"); | ||
| 19 | const { subscribe, set } = writable<string | null>(storedToken); | ||
| 20 | |||
| 21 | function authenticate(newToken: string): void { | ||
| 22 | try { | ||
| 23 | localStorage.setItem("token", newToken); | ||
| 24 | set(newToken); | ||
| 25 | } catch (e) { | ||
| 26 | console.error('error', e); | ||
| 27 | } | ||
| 28 | } | ||
| 29 | |||
| 30 | function unauthenticate(): void { | ||
| 31 | localStorage.removeItem("token"); | ||
| 32 | set(null); | ||
| 33 | } | ||
| 34 | |||
| 35 | return { | ||
| 36 | subscribe, | ||
| 37 | authenticate, | ||
| 38 | unauthenticate | ||
| 39 | }; | ||
| 40 | } | ||
| 41 | |||
| 42 | function onTokenChange ($token: Nullable<string>): boolean { | ||
| 43 | return $token ? true : false; | ||
| 44 | } | ||
| 45 | |||
| 46 | export const token = createTokenStore(); | ||
| 47 | export const authenticated = derived(token, onTokenChange); | ||
| 48 | export const user = writable<User | null>(null); | ||
