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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
|
/**
* Authentication logic and token management
*/
import { getBaseUrl } from "./utils.js";
/**
* Wait for user to provide a security token
* @returns {Promise<{token: string, remember: boolean}>}
*/
async function waitForSecurityToken() {
let token = null;
let remember = null;
while (!token) {
let result = await getSecurityToken();
if (result) {
token = result.token;
remember = result.remember;
} else {
await showErrorModal(
"Error",
"Must provide security token in order to log in."
);
}
}
return { token, remember };
}
/**
* Get client ID from server after authentication
* @param {string} token - Authentication token
* @param {boolean} rememberMe - Remember login preference
* @param {boolean} hasAuthenticationCookie - Whether auth cookie exists
* @returns {Promise<string|null>} Client ID or null on failure
*/
export async function getClientId(token, rememberMe, hasAuthenticationCookie) {
const baseUrl = getBaseUrl();
if (!hasAuthenticationCookie) {
let login_res = await fetch(`${baseUrl}/command/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
auth_token: token,
remember_me: rememberMe ? true : false,
}),
credentials: "include",
});
if (login_res.status === 401) {
await showErrorModal(
"Error",
"Unauthorized or revoked login token."
);
return null;
} else if (!login_res.ok) {
await showErrorModal(
"Error",
`Error ${login_res.status} connecting to server.`
);
return null;
}
}
let data = await fetch(`${baseUrl}/session`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
});
if (data.status === 401) {
await showErrorModal("Error", "Unauthorized or revoked login token.");
return null;
} else if (!data.ok) {
await showErrorModal(
"Error",
`Error ${data.status} connecting to server.`
);
return null;
} else {
let body = await data.json();
return body.web_client_id;
}
}
/**
* Initialize authentication flow and return client ID
* @returns {Promise<string>} Client ID
*/
export async function initAuthentication() {
let token = null;
let remember = null;
let hasAuthenticationCookie = document.body.dataset.authenticated === "true";
if (!hasAuthenticationCookie) {
const tokenResult = await waitForSecurityToken();
token = tokenResult.token;
remember = tokenResult.remember;
}
let webClientId;
while (!webClientId) {
webClientId = await getClientId(
token,
remember,
hasAuthenticationCookie
);
if (!webClientId) {
hasAuthenticationCookie = false;
const tokenResult = await waitForSecurityToken();
token = tokenResult.token;
remember = tokenResult.remember;
}
}
return webClientId;
}
|