-
-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathauth.svelte.ts
More file actions
56 lines (50 loc) · 1.36 KB
/
Copy pathauth.svelte.ts
File metadata and controls
56 lines (50 loc) · 1.36 KB
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
import { browser } from '$app/environment';
import { goto } from '$app/navigation';
import { env } from '$env/dynamic/public';
import { apiClient } from '$lib/helper/api.helper';
import type { ApiResponse } from '@tracktor/common';
import { toast } from 'svelte-sonner';
class AuthStore {
pin = $state<string>();
isLoggedIn = $state<boolean>(false);
constructor() {
this.isLoggedIn = env.TRACKTOR_DISABLE_AUTH === 'true';
if (browser && !this.isLoggedIn) {
const pin = localStorage.getItem('userPin');
if (pin) {
this.login(pin);
}
}
}
isPinConfigured = async () => {
return apiClient
.get<ApiResponse>('/auth/status', { skipInterceptors: true })
.then(({ data: res }) => res.data.exists as boolean)
.catch(() => false);
};
login = async (pin: string) => {
return apiClient
.post<ApiResponse>('/auth/verify', { pin }, { skipInterceptors: true })
.then(({ data: res }) => {
if (res.success) {
this.pin = pin;
if (browser) {
localStorage.setItem('userPin', pin);
}
this.isLoggedIn = true;
}
})
.catch((err) => {
this.pin = undefined;
console.log(err);
toast.error(`Error while logging in. ${err.message}.`);
});
};
logout = () => {
localStorage.removeItem('userPin');
this.pin = undefined;
this.isLoggedIn = false;
goto('/');
};
}
export const authStore = new AuthStore();