This repository was archived by the owner on Jul 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbackground.js
More file actions
337 lines (284 loc) · 7.93 KB
/
Copy pathbackground.js
File metadata and controls
337 lines (284 loc) · 7.93 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// custom exception class which adds some extra fields and detail when
// returning errors from server -- feel free to use this in your code
const key = //haha nope.
class APIError extends Error {
constructor(message, status, detail) {
super(message);
this.status = status;
this.detail = detail;
}
}
// Please do not use any of these methods below directly in your code! Instead, create
// methods that use them, as is done elsewhere in this directory. This will make
// it easier to switch to different authentication methods or otherwise change
// the implementation of the API in the future.
const JWT_ACCESS_TOKEN_ID = "jwt-access-token";
const JWT_ACCESS_TOKEN_REFRESH_INTERVAL = 4 * 60; // 4 minutes
const JWT_REFRESH_TOKEN_ID = "jwt-refresh-token";
const JWT_REFRESH_TOKEN_REFRESH_INTERVAL = 23 * 60 * 60; // 23 hours
function getCookie(name) {
if (!document.cookie) {
return null;
}
const token = document.cookie
.split(";")
.map(c => c.trim())
.filter(c => c.startsWith(`${name}=`));
if (token.length === 0) {
return null;
}
return decodeURIComponent(token[0].split("=")[1]);
}
// exported for unit testing only
function setCookie(name, value, maxAge) {
const maxAgeStr = maxAge ? `;max-age=${maxAge}` : "";
document.cookie = `${name}=${value}${maxAgeStr}`;
}
async function getResultError(result) {
// figure out what type of error it is, then let the client
// know
let status;
switch (result.status) {
case 400:
status = "BAD_REQUEST";
break;
case 403:
status = "FORBIDDEN";
break;
default:
status = "UNKNOWN_ERROR";
break;
}
const errorObj = await result.json();
return new APIError(
result.statusText,
status,
errorObj.detail ? errorObj.detail : errorObj
);
}
// this adds a csrf token to requests, when available, so django
// can figure out which user the request is coming from
function fetchWithCSRFToken(url, otherParts, headers = {}) {
const csrfToken = getCookie("csrftoken");
const defaultHeaders = {
"X-CSRFToken": csrfToken
};
const combinedHeaders = Object.assign({}, defaultHeaders, headers);
return fetch(
url,
Object.assign({}, otherParts, { headers: combinedHeaders })
);
}
async function getJWTAuthToken() {
const result = await fetchWithCSRFToken("/token/", { method: "POST" });
if (!result.ok) {
throw getResultError(result);
}
const tokenData = await result.json();
setCookie(
JWT_ACCESS_TOKEN_ID,
tokenData.access,
JWT_ACCESS_TOKEN_REFRESH_INTERVAL
);
setCookie(
JWT_REFRESH_TOKEN_ID,
tokenData.refresh,
JWT_REFRESH_TOKEN_REFRESH_INTERVAL
);
}
async function fetchWithJWTToken(url, otherParts, headers = {}) {
//const accessToken = getCookie(JWT_ACCESS_TOKEN_ID);
const accessToken = key;
console.log( Object.assign({}, otherParts, {
credentials: "omit",
headers: Object.assign(
{},
{
Accept: "application/json",
Authorization: `Token ${accessToken}`
},
headers
)
}))
if (accessToken) {
console.log(headers)
return fetch(
url,
Object.assign({}, otherParts, {
credentials: "include",
headers: Object.assign(
{},
{
Accept: "application/json",
Authorization: `Token ${accessToken}`
},
headers
)
})
);
}
console.log(headers)
// access token seems to have expired, do we have a refresh token we can use?
const refresh = getCookie(JWT_REFRESH_TOKEN_ID);
let tokenRefreshed = false;
if (refresh) {
try {
const result = await fetch("/api/v1/token/refresh/", {
headers: {
"Content-Type": "application/json"
},
method: "POST",
body: JSON.stringify({ refresh })
});
if (!result.ok) {
const error = await getResultError(result);
throw error;
} else {
const newAccessTokenData = await result.json();
if (!newAccessTokenData || !newAccessTokenData.access) {
throw Error("Unknown error getting new access token");
}
// otherwise, almost certainly our new auth token is ok
setCookie(
JWT_ACCESS_TOKEN_ID,
newAccessTokenData.access,
JWT_ACCESS_TOKEN_REFRESH_INTERVAL
);
tokenRefreshed = true;
}
} catch (err) {
// if we have some kind of error getting the refresh token, clear it
// and assume we just have to get it again
setCookie(JWT_ACCESS_TOKEN_ID, "", -1);
}
}
if (!tokenRefreshed) {
// no refresh token, get both a refresh token and an auth one
await getJWTAuthToken();
}
// try recursively calling this function again (this should happen at most
// once, since the refresh token functions above will throw if they encounter
// an error)
return fetchWithJWTToken(url, otherParts, headers);
}
async function signedAPIRequest(
url,
otherParts,
headers = {},
jsonResponseExpected = true
) {
const result = await fetchWithJWTToken(url, otherParts, headers);
if (!result.ok) {
const error = await getResultError(result);
throw error;
}
if (jsonResponseExpected) {
return result.json();
}
return result.text();
}
// for POST, DELETE of notebooks and revisions,
// we need to assign a Content-Type when sending the CSRFToken for deleting.
function signedAPIRequestWithJSONContent(
url,
otherParts,
jsonResponseExpected = true
) {
return signedAPIRequest(
url,
otherParts,
{
"Content-Type": "application/json"
},
jsonResponseExpected
);
}
// A request which accesses a read-only json endpoint, will use
// logged in credentials if available
async function readJSONAPIRequest(url, loggedIn) {
const result = loggedIn ? await fetchWithJWTToken(url) : await fetch(url);
if (!result.ok) {
const error = await getResultError(result);
console.log(error);
throw error;
}
return result.json();
}
function getNotebookRequest(notebookId) {
return signedAPIRequest(`/api/v1/notebooks/${notebookId}/`);
}
function createNotebookRequestPayload(title, content, options) {
const postRequestOptions = {
body: JSON.stringify({
title,
content,
...options
}),
method: "POST"
};
return postRequestOptions;
}
function createNotebookRequest(title, iomd, options) {
return signedAPIRequestWithJSONContent(
"https://alpha.iodide.io/api/v1/notebooks/",
createNotebookRequestPayload(title, iomd, options)
);
}
function updateNotebookRequest(
notebookId,
currentRevisionId,
newTitle,
newIomd
) {
return signedAPIRequestWithJSONContent(
`/api/v1/notebooks/${notebookId}/revisions/`,
createNotebookRequestPayload(
newTitle,
newIomd,
currentRevisionId ? { parent_revision_id: currentRevisionId } : {}
)
);
}
function deleteNotebookRequest(notebookId) {
return signedAPIRequestWithJSONContent(
`/api/v1/notebooks/${notebookId}/`,
{
method: "DELETE"
},
false
);
}
function deleteNotebookRevisionRequest(notebookId, revisionId) {
return signedAPIRequestWithJSONContent(
`/api/v1/notebooks/${notebookId}/revisions/${revisionId}/`,
{
method: "DELETE"
},
false
);
}
browser.contextMenus.create({
id: "open-csv-link",
title: "Open link in Iodide",
contexts: ["link"]
});
browser.contextMenus.create({
id: "open-csv-select",
title: "Explore selected text in Iodide",
contexts: ["selection"]
});
browser.contextMenus.onClicked.addListener(
async function(info, tab) {
console.log(info)
if(info.menuItemId === "open-csv-link" ){
const file = await fetch(info.linkUrl).then(r => r.text())
}
if(info.menuItemId === "open-csv-select" ){
const file = info.selectionText
try{
const response = await createNotebookRequest("blah", file).then(r => r.json())
console.log(response)
} catch(err){console.log(err)}
}
}
);