1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 window.models = window.models || {}
6 window.models.SessionDB = function() {
11 return JSON.parse(window.localStorage.getItem('sessions')) || {}
15 save: function(k, v) {
16 var sessions = db.loadAll()
18 window.localStorage.setItem('sessions', JSON.stringify(sessions))
21 var sessions = db.loadAll()
23 window.localStorage.setItem('sessions', JSON.stringify(sessions))
25 login: function(host) {
26 // Initiate login procedure with given API host (which can
27 // optionally include scheme://).
29 // Any page that has a button that invokes login() must
30 // also call checkForNewToken() on (at least) its first
31 // render. Otherwise, the login procedure can't be
34 if (baseURL.indexOf('://') < 0)
35 baseURL = 'https://' + baseURL
36 if (!baseURL.endsWith('/'))
37 baseURL = baseURL + '/'
38 document.location = baseURL + 'login?return_to=' + encodeURIComponent(document.location.href+'?baseURL='+encodeURIComponent(baseURL))
41 checkForNewToken: function() {
42 // If there's a token and baseURL in the location bar (i.e.,
43 // we just landed here after a successful login), save it and
44 // scrub the location bar.
45 if (!document.location.search.startsWith('?'))
48 document.location.search.slice(1).split('&').map(function(kv) {
49 var e = kv.indexOf('=')
52 params[decodeURIComponent(kv.slice(0, e))] = decodeURIComponent(kv.slice(e+1))
54 if (!params.baseURL || !params.api_token)
55 // Have a query string, but it's not a login callback.
57 params.token = params.api_token
58 delete params.api_token
59 db.save(params.baseURL, params)
60 history.replaceState({}, '', document.location.origin + document.location.pathname)
62 fillMissingUUIDs: function() {
63 var sessions = db.loadAll()
64 Object.keys(sessions).map(function(key) {
65 if (key.indexOf('://') < 0)
67 // key is the baseURL placeholder. We need to get our user
68 // record to find out the cluster's real uuid prefix.
69 var session = sessions[key]
70 m.request(session.baseURL+'arvados/v1/users/current', {
72 authorization: 'OAuth2 '+session.token,
74 }).then(function(user) {
76 db.save(user.uuid.slice(0, 5), session)
80 // m.request(session.baseURL + 'discovery/v1/apis/arvados/v1/rest').then(function(dd) {})
82 request: function(session, path, opts) {
84 opts.headers = opts.headers || {}
85 opts.headers.authorization = 'OAuth2 '+ session.token
86 return m.request(session.baseURL + path, opts)