blob: 7e70cdac9876fb7857feb898275121ac407bafc9 (
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
|
import type { Invalidator, Subscriber, Unsubscriber } from 'svelte/store';
import { writable, derived } from 'svelte/store';
type Nullable<T> = T | null;
interface User {
uuid: string;
username: string;
}
interface TokenStore {
subscribe: (run: Subscriber<Nullable<string>>, invalidate: Invalidator<Nullable<string>>) => Unsubscriber,
authenticate: (newToken: string) => void,
unauthenticate: () => void
}
function createTokenStore(): TokenStore {
const storedToken = localStorage.getItem("token");
const { subscribe, set } = writable<string | null>(storedToken);
function authenticate(newToken: string): void {
try {
localStorage.setItem("token", newToken);
set(newToken);
} catch (e) {
console.error('error', e);
}
}
function unauthenticate(): void {
localStorage.removeItem("token");
set(null);
}
return {
subscribe,
authenticate,
unauthenticate
};
}
function onTokenChange ($token: Nullable<string>): boolean {
return $token ? true : false;
}
export const token = createTokenStore();
export const authenticated = derived(token, onTokenChange);
export const user = writable<User | null>(null);
|