forked from ScratchAddons/ScratchAddons
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuth.js
More file actions
103 lines (91 loc) · 2.21 KB
/
Copy pathAuth.js
File metadata and controls
103 lines (91 loc) · 2.21 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
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
import AuthCommon from "../common/Auth.js";
export default class Auth extends AuthCommon {
constructor(...args) {
super(...args);
this._refresh();
}
/**
* @private
*/
_getCookie(name) {
const cookies = document.cookie.split(";").map((c) => c.trim());
const cookie = cookies.find((c) => c.startsWith(`${name}=`));
if (!cookie) return null;
return cookie.slice(name.length + 1);
}
/**
* @private
*/
_refresh() {
this._lastUsername = undefined;
this._lastUserId = undefined;
this._lastIsLoggedIn = undefined;
this._lastXToken = undefined;
}
/**
* @private
*/
_waitUntilFetched() {
return new Promise((resolve) => this.addEventListener("session", resolve, { once: true }));
}
/**
* @private
*/
_update(d) {
this._lastUsername = d.user?.username || null;
this._lastUserId = d.user?.id || null;
this._lastIsLoggedIn = !!d.user;
this._lastXToken = d.user?.token || null;
this.dispatchEvent(new CustomEvent("session"));
this.dispatchEvent(new CustomEvent("change"));
}
/**
* @private
*/
_fetchProperty(prop) {
if (typeof this[prop] !== "undefined") return Promise.resolve(this[prop]);
return this._waitUntilFetched().then(() => this[prop]);
}
/**
* Fetch whether the user is logged in or not.
* @returns {Promise<boolean>} - whether the user is logged in or not.
*/
fetchIsLoggedIn() {
return this._fetchProperty("_lastIsLoggedIn");
}
/**
* Fetch current username.
* @returns {Promise<?string>} - the username.
*/
fetchUsername() {
return this._fetchProperty("_lastUsername");
}
/**
* Fetch current user ID.
* @returns {Promise<?number>} - the user ID.
*/
fetchUserId() {
return this._fetchProperty("_lastUserId");
}
/**
* Fetch X-Token used in new APIs.
* @returns {Promise<?string>} - the X-Token.
*/
fetchXToken() {
return this._fetchProperty("_lastXToken");
}
/**
* CSRF token used in APIs.
* @type {string}
*/
get csrfToken() {
return this._getCookie("scratchcsrftoken");
}
/**
* Language of the Scratch website.
* @type {string}
*/
get scratchLang() {
return this._getCookie("scratchlanguage");
}
}