hackathon/web_src/lib/stores.ts

71 lines
1.4 KiB
TypeScript

2022-04-28 23:31:09 +07:00
import { goto } from '$app/navigation';
import { browser } from '$app/env';
import { writable } from 'svelte/store';
import type { Info } from '$lib/pb/all.pb';
import { UserService } from '$lib/pb/all.pb';
import { withToken } from '$lib/pb/pbutil';
const token = browser ? window.localStorage.getItem('authToken') : null;
export class Data {
readonly info?: Info;
readonly token?: string;
constructor(token?: string, info?: Info) {
this.info = info;
this.token = token;
}
loggedIn(): boolean {
return this.token !== null;
}
login(newToken: string) {
window.localStorage.setItem('authToken', newToken);
}
logout() {
window.localStorage.removeItem('authToken');
}
refresh() {
UserService.Info({}, withToken(this.token))
.then((info) => {
auth.set(new Data(token, info));
})
.catch(() => {
this.logout();
auth.set(new Data());
goto('/');
});
}
}
export const auth = writable<Data>(new Data(token));
auth.subscribe(async (newAuth) => {
if (!browser) return;
// user is already set
if (newAuth.info || !newAuth.token) return;
if (!newAuth.token) {
newAuth.logout();
auth.set(new Data());
return;
}
// token just got added
window.localStorage.setItem('authToken', newAuth.token);
UserService.Info({}, withToken(newAuth.token))
.then((info) => {
auth.set(new Data(newAuth.token, info));
})
.catch(() => {
newAuth.logout();
auth.set(new Data());
goto('/');
});
});