blob: 5c29cd639dffab1303bdff1eff061081eacaef93 (
plain) (
blame)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
|
import { log_error, log_info } from "$lib/logger";
import { Temporal } from "temporal-polyfill";
import { http_account } from "$lib/api/account";
import { is_guid, session_storage_get_json, session_storage_set_json } from "./helpers";
import { SECONDS_BETWEEN_SESSION_CHECK, StorageKeys } from "./configuration";
import type { Session } from "$lib/models/internal/ISession";
export async function is_active(forceRefresh: boolean = false): Promise<boolean> {
const nowEpoch = Temporal.Now.instant().epochSeconds;
const data = session_storage_get_json(StorageKeys.session) as Session;
const expiryEpoch = data?.lastChecked + SECONDS_BETWEEN_SESSION_CHECK;
const lastCheckIsStaleOrNone = !is_guid(data?.profile?.id) || (expiryEpoch < nowEpoch);
if (forceRefresh || lastCheckIsStaleOrNone) {
return await call_api();
} else {
const sessionIsValid = data.profile && is_guid(data.profile.id);
if (!sessionIsValid) {
clear_session_data();
log_info("Session data is not valid");
}
return sessionIsValid;
}
}
export async function end_session(cb: Function): Promise<void> {
await http_account.logout_async();
clear_session_data();
if (typeof cb === "function") cb();
}
async function call_api(): Promise<boolean> {
log_info("Getting profile data while checking session state");
try {
const response = await http_account.get_profile_async(true);
if (response.ok) {
const userData = await response.json();
if (is_guid(userData.id) && userData.username) {
const session = {
profile: userData,
lastChecked: Temporal.Now.instant().epochSeconds
} as Session;
session_storage_set_json(StorageKeys.session, session);
log_info("Successfully got profile data while checking session state");
return true;
} else {
log_error("Api returned invalid data while getting profile data");
clear_session_data();
return false;
}
} else {
log_error("Api returned unsuccessfully while getting profile data");
clear_session_data();
return false;
}
} catch (e) {
log_error(e);
clear_session_data();
return false;
}
}
export function clear_session_data() {
session_storage_set_json(StorageKeys.session, {});
log_info("Cleared session data.");
}
export function get_session_data(): Session {
return session_storage_get_json(StorageKeys.session) as Session;
}
|