diff options
Diffstat (limited to 'fe/src/stores/auth.ts')
-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); | ||