-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuserCreds.js
More file actions
74 lines (62 loc) · 1.94 KB
/
Copy pathuserCreds.js
File metadata and controls
74 lines (62 loc) · 1.94 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
;(async function replaceUserCreds() {
function traverseNodeChildren(node, callback) {
if (!node.childNodes.length) {
callback(node)
}
for (const child of node.childNodes) {
traverseNodeChildren(child, callback)
}
}
function replaceTextContent(node, replacers) {
const isTextNode = n => n.nodeType === Node.TEXT_NODE
traverseNodeChildren(node, (child) => {
if (isTextNode(child)) {
child.textContent = replacers.reduce(
(text, replace) => replace(text),
child.textContent
)
}
})
}
function updateUserCreds(username, apiKey = 'YOUR_API_KEY') {
const codeExampleNodes = document.querySelectorAll(
'[class*=gs-code-container]'
)
if (!codeExampleNodes.length) return
const replacers = [
str => str.replace(/YOUR_USERNAME/g, username),
str => str.replace(/YOUR_API_KEY/g, apiKey)
]
codeExampleNodes.forEach(node => {
replaceTextContent(node, replacers)
})
}
function enableNavButtons(authenticated) {
const navClass = authenticated ? 'show-auth-nav' : 'show-unauth-nav'
document.querySelector('.syn-page-header').classList.add(navClass)
}
async function getCurrentUser() {
const response = await fetch('/webapi/user', {
headers: {
accept: 'application/json, text/plain, */*',
}
})
const { user } = await response.json()
return user
}
try {
const { username, default_api_key: apiKey } = await getCurrentUser()
if (username) {
updateUserCreds(username, apiKey)
enableNavButtons(true)
} else {
// No username, show unauthenticated nav buttons.
enableNavButtons(false)
}
} catch (err) {
// User is logged out. Safe to ignore error since this is an enhancement
// and the page is perfectly useable without credentials replaced.
// We do, however, want to show the unauthenticated nav buttons.
enableNavButtons(false)
}
})()