| 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369 |
1×
1×
1×
1×
1×
1×
2×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
6×
6×
9×
6×
1×
7×
7×
7×
48×
7×
48×
15×
7×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
19×
19×
19×
19×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
3×
14×
14×
14×
1×
3×
5×
5×
5×
1×
1×
1×
5×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
19×
2×
17×
17×
147×
1×
1×
1×
1×
1×
1×
| 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.build = build;
var _axios = require('axios');
var _axios2 = _interopRequireDefault(_axios);
var _monologue = require('monologue.js');
var _monologue2 = _interopRequireDefault(_monologue);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { Iif (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// ----------------------------------------------------------------------------
var AUTH_CHANGE_TOPIC = 'girder.auth.change';
var BUSY_TOPIC = 'girder.busy';
var PROGRESS_TOPIC = 'girder.progress';
var EVENT_TOPIC = 'girder.notification';
var Observable = function Observable() {
_classCallCheck(this, Observable);
};
_monologue2.default.mixInto(Observable);
var _LOGIN_PROMISE = function _LOGIN_PROMISE() {
return Promise.resolve('login');
};
var _LOGOUT_PROMISE = function _LOGOUT_PROMISE() {
return Promise.reject('logout');
};
// ----------------------------------------------------------------------------
function encodeQueryAsString() {
var query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var params = Object.keys(query).map(function (name) {
return [encodeURIComponent(name), encodeURIComponent(query[name])].join('=');
});
return params.length ? '?' + params.join('&') : '';
}
// ----------------------------------------------------------------------------
function filterQuery() {
var query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var out = {};
for (var _len = arguments.length, keys = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
keys[_key - 1] = arguments[_key];
}
keys.forEach(function (key) {
if (query[key] !== undefined && query[key] !== null) {
out[key] = query[key];
}
});
return out;
}
// ----------------------------------------------------------------------------
function mustContain() {
var object = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var missingKeys = [];
var promise = void 0;
for (var _len2 = arguments.length, keys = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
keys[_key2 - 1] = arguments[_key2];
}
keys.forEach(function (key) {
if (object[key] === undefined) {
missingKeys.push(key);
}
});
if (missingKeys.length === 0) {
missingKeys = undefined;
promise = Promise.resolve(true);
} else {
promise = Promise.reject('Missing keys ' + missingKeys.join(', '));
}
return {
missingKeys: missingKeys,
promise: promise
};
}
// ----------------------------------------------------------------------------
function build() {
var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.location;
var userData = void 0;
var token = void 0;
var loginPromise = void 0;
var isAuthenticated = false;
var eventSource = null;
var busyCounter = 0;
var client = {}; // Must be const otherwise the created closure will fail
var notification = new Observable();
var idle = function idle() {
busyCounter -= 1;
notification.emit(BUSY_TOPIC, busyCounter);
};
var busy = function busy(promise) {
busyCounter += 1;
notification.emit(BUSY_TOPIC, busyCounter);
promise.then(idle);
return promise;
};
var protocol = config.protocol,
hostname = config.hostname,
port = config.port,
_config$basepath = config.basepath,
basepath = _config$basepath === undefined ? '/api/v1' : _config$basepath;
var baseURL = protocol + '//' + hostname + ':' + port + basepath;
var connectToNotificationStream = function connectToNotificationStream() {
if (EventSource) {
eventSource = new EventSource(baseURL + '/notification/stream');
eventSource.onmessage = function (e) {
var parsed = JSON.parse(e.data);
notification.emit(EVENT_TOPIC, parsed);
};
eventSource.onerror = function (e) {
// Wait 2 seconds if the browser hasn't reconnected then reinitialize.
setTimeout(function () {
if (eventSource && eventSource.readyState === EventSource.CLOSED) {
connectToNotificationStream();
} else {
eventSource.close();
eventSource = null;
connectToNotificationStream();
}
}, 2000);
};
}
};
function extractLocalToken() {
try {
return document.cookie.split('girderToken=')[1].split(';')[0].trim();
} catch (e) {
return undefined;
}
}
function updateGirderInstance() {
var timeout = 60000;
var headers = {};
Iif (token) {
headers['Girder-Token'] = token;
}
client._ = {};
var methods = _axios2.default.create({
baseURL: baseURL,
timeout: timeout,
headers: headers
});
// wrap xhr requests so we can give a cancel to each,
// we need to make a new cancel token for each request.
['get', 'delete', 'head'].forEach(function (req) {
client._[req] = function (url, conf) {
var cSource = _axios.CancelToken.source();
client.cancel = cSource.cancel;
return methods[req](url, Object.assign({}, conf, {
cancelToken: cSource.token
}));
};
});
['post', 'put', 'patch'].forEach(function (req) {
client._[req] = function (url, data, conf) {
var cSource = _axios.CancelToken.source();
client.cancel = cSource.cancel;
return methods[req](url, data, Object.assign({}, conf, {
cancelToken: cSource.token
}));
};
});
}
function updateAuthenticationState(state) {
if (isAuthenticated !== !!state) {
// Clear cache data if not logged-in
if (!state) {
userData = undefined;
token = undefined;
// Update userData for external modules
client.user = userData;
client.token = undefined;
}
// Update internal state
isAuthenticated = !!state;
updateGirderInstance();
// Broadcast information
/* eslint-disable babel/new-cap */
loginPromise = state ? _LOGIN_PROMISE() : _LOGOUT_PROMISE();
/* eslint-enable babel/new-cap */
notification.emit(AUTH_CHANGE_TOPIC, isAuthenticated);
if (isAuthenticated && eventSource === null) {
connectToNotificationStream();
}
}
}
function progress(id, current) {
var total = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
notification.emit(PROGRESS_TOPIC, {
id: id,
current: current,
total: total
});
}
// Fill up public object
var publicObject = {
login: function login(username, password) {
var auth = {
username: username,
password: password
};
return new Promise(function (accept, reject) {
busy(client._.get('/user/authentication', { auth: auth }).then(function (resp) {
token = resp.data.authToken.token;
userData = resp.data.user;
// Update userData for external modules
client.user = userData;
client.token = token;
updateAuthenticationState(true);
accept();
}).catch(function (err) {
updateAuthenticationState(false);
reject(err);
}));
});
},
logout: function logout() {
return busy(client._.delete('/user/authentication').then(function (ok) {
updateAuthenticationState(false);
if (document && document.cookie) {
document.cookie = 'Girder-Token=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
}, function (ko) {
console.log('loggout error', ko);
}));
},
me: function me() {
return busy(client._.get('/user/me'));
},
isLoggedIn: function isLoggedIn() {
return loginPromise;
},
getLoggedInUser: function getLoggedInUser() {
return userData;
},
onAuthChange: function onAuthChange(callback) {
return notification.on(AUTH_CHANGE_TOPIC, callback);
},
onBusy: function onBusy(callback) {
return notification.on(BUSY_TOPIC, callback);
},
onProgress: function onProgress(callback) {
return notification.on(PROGRESS_TOPIC, callback);
},
onEvent: function onEvent(callback) {
return notification.on(EVENT_TOPIC, callback);
},
destroy: function destroy() {
notification.off();
},
cancel: function cancel() {
if (client.cancel) {
client.cancel('request was canceled');
}
}
};
// Try to extract token from
loginPromise = new Promise(function (accept, reject) {
token = config.token || extractLocalToken();
updateGirderInstance();
Iif (token) {
publicObject.me().then(function (resp) {
if (!resp.data) {
updateAuthenticationState(false);
userData = null;
reject(resp);
return;
}
// Update userData for external modules
userData = resp.data;
client.user = userData;
client.token = token;
updateAuthenticationState(true);
accept();
}).catch(function (errResp) {
updateAuthenticationState(false);
reject(errResp);
});
} else {
reject('No token');
}
});
// Expend client
client.baseURL = baseURL;
client.cancel = null;
// Add extensions
var spec = {
busy: busy,
client: client,
encodeQueryAsString: encodeQueryAsString,
filterQuery: filterQuery,
mustContain: mustContain,
notification: notification,
progress: progress
};
function processExtension(ext) {
if (Array.isArray(ext)) {
ext.forEach(processExtension);
} else {
var obj = ext(spec);
Object.keys(obj).forEach(function (key) {
publicObject[key] = obj[key];
});
}
}
for (var _len3 = arguments.length, extensions = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
extensions[_key3 - 1] = arguments[_key3];
}
processExtension(extensions);
// Return the newly composed object
// if karma, return an unfrozen version so we can spy on it
/* global KARMA_TEST_RUNNER */
Eif (KARMA_TEST_RUNNER) {
return publicObject;
}
return Object.freeze(publicObject);
}
exports.default = {
build: build
};
|