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() {
9 loadFromLocalStorage: function() {
11 return JSON.parse(window.localStorage.getItem('sessions')) || {}
16 var all = db.loadFromLocalStorage()
17 if (window.defaultSession) {
18 window.defaultSession.isFromRails = true
19 all[window.defaultSession.user.uuid.slice(0, 5)] = window.defaultSession
23 save: function(k, v) {
24 var sessions = db.loadAll()
26 Object.keys(sessions).forEach(function(key) {
27 if (sessions[key].isFromRails)
30 window.localStorage.setItem('sessions', JSON.stringify(sessions))
33 var sessions = db.loadAll()
35 window.localStorage.setItem('sessions', JSON.stringify(sessions))
37 login: function(host) {
38 // Initiate login procedure with given API host (which can
39 // optionally include scheme://).
41 // Any page that has a button that invokes login() must
42 // also call checkForNewToken() on (at least) its first
43 // render. Otherwise, the login procedure can't be
46 if (baseURL.indexOf('://') < 0)
47 baseURL = 'https://' + baseURL
48 if (!baseURL.endsWith('/'))
49 baseURL = baseURL + '/'
50 document.location = baseURL + 'login?return_to=' + encodeURIComponent(document.location.href+'?baseURL='+encodeURIComponent(baseURL))
53 checkForNewToken: function() {
54 // If there's a token and baseURL in the location bar (i.e.,
55 // we just landed here after a successful login), save it and
56 // scrub the location bar.
57 if (!document.location.search.startsWith('?'))
60 document.location.search.slice(1).split('&').map(function(kv) {
61 var e = kv.indexOf('=')
64 params[decodeURIComponent(kv.slice(0, e))] = decodeURIComponent(kv.slice(e+1))
66 if (!params.baseURL || !params.api_token)
67 // Have a query string, but it's not a login callback.
69 params.token = params.api_token
70 delete params.api_token
71 db.save(params.baseURL, params)
72 history.replaceState({}, '', document.location.origin + document.location.pathname)
74 fillMissingUUIDs: function() {
75 var sessions = db.loadAll()
76 Object.keys(sessions).map(function(key) {
77 if (key.indexOf('://') < 0)
79 // key is the baseURL placeholder. We need to get our user
80 // record to find out the cluster's real uuid prefix.
81 var session = sessions[key]
82 m.request(session.baseURL+'arvados/v1/users/current', {
84 authorization: 'OAuth2 '+session.token,
86 }).then(function(user) {
88 db.save(user.uuid.slice(0, 5), session)
92 // m.request(session.baseURL + 'discovery/v1/apis/arvados/v1/rest').then(function(dd) {})
94 request: function(session, path, opts) {
96 opts.headers = opts.headers || {}
97 opts.headers.authorization = 'OAuth2 '+ session.token
98 return m.request(session.baseURL + path, opts)