-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathauth.js
More file actions
100 lines (77 loc) · 2.52 KB
/
Copy pathauth.js
File metadata and controls
100 lines (77 loc) · 2.52 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
const lichessHost = 'https://lichess.org';
const clientId = 'example.com';
const clientUrl = (() => {
const url = new URL(location.href);
url.search = '';
return url.href;
})();
const oauth = new OAuth2AuthCodePKCE.OAuth2AuthCodePKCE({
authorizationUrl: `${lichessHost}/oauth`,
tokenUrl: `${lichessHost}/api/token`,
clientId,
scopes: ['email:read','tournament:write'],
redirectUrl: clientUrl,
onAccessTokenExpiry: refreshAccessToken => refreshAccessToken(),
onInvalidGrant: _retry => {},
});
async function login() {
// Redirect to authentication prompt.
await oauth.fetchAuthorizationCode();
}
async function useApi() {
const res = await fetch(`${lichessHost}/api/account`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("LICHESS_TOKEN")}`
}
});
const username = (await res.json()).id;
console.log(username)
document.getElementById("showusernamediv").innerHTML = username || "-"
}
function updateToken(){
const token = localStorage.getItem("LICHESS_TOKEN")
console.log("update token to", token)
//document.getElementById("LICHESS_TOKEN").value = token
const buttonElements = ["logoutbutton"].map(id => document.getElementById(id))
buttonElements.forEach(e => token ? e.removeAttribute("disabled") : e.setAttribute("disabled", true))
}
let retries = 10
async function init() {
if(!document.getElementById("logoutbutton")){
console.log("oauth no ui detected, restarting")
if(retries--) {setTimeout(init, 2000)} else {console.error("oauth init timed out")}
return
}else{
console.log("oauth ui ready")
document.getElementById("loginbutton").addEventListener("click", login)
document.getElementById("logoutbutton").addEventListener("click", logout)
}
updateToken()
try {
const hasAuthCode = await oauth.isReturningFromAuthServer();
if (hasAuthCode) {
const accessContext = await oauth.getAccessToken();
console.log(accessContext)
localStorage.setItem("LICHESS_TOKEN", accessContext.token.value)
updateToken()
}
} catch (err) {
console.log(err)
}
useApi()
}
async function logout() {
const token = localStorage.getItem("LICHESS_TOKEN")
const response = await fetch(`${lichessHost}/api/token`, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${token}`,
},
});
console.log("logout status", response.status)
const text = await response.text()
console.log(text)
localStorage.removeItem("LICHESS_TOKEN")
document.location.href="/"
}
init()