Merge branch '8784-dir-listings'
[arvados.git] / services / api / lib / create_superuser_token.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 # Install the supplied string (or a randomly generated token, if none
6 # is given) as an API token that authenticates to the system user account.
7
8 module CreateSuperUserToken
9   require File.dirname(__FILE__) + '/../config/boot'
10   require File.dirname(__FILE__) + '/../config/environment'
11
12   include ApplicationHelper
13
14   def create_superuser_token supplied_token=nil
15     act_as_system_user do
16       # If token is supplied, verify that it indeed is a superuser token
17       if supplied_token
18         api_client_auth = ApiClientAuthorization.
19           where(api_token: supplied_token).
20           first
21         if !api_client_auth
22           # fall through to create a token
23         elsif !api_client_auth.user.uuid.match(/-000000000000000$/)
24           raise "Token exists but is not a superuser token."
25         elsif api_client_auth.scopes != ['all']
26           raise "Token exists but has limited scope #{api_client_auth.scopes.inspect}."
27         end
28       end
29
30       # need to create a token
31       if !api_client_auth
32         # Get (or create) trusted api client
33         apiClient =  ApiClient.
34           find_or_create_by(url_prefix: "ssh://root@localhost/",
35                             is_trusted: true)
36
37         # Check if there is an unexpired superuser token corresponding to this api client
38         api_client_auth =
39           ApiClientAuthorization.
40           where(user_id: system_user.id).
41           where(api_client_id: apiClient.id).
42           where_serialized(:scopes, ['all']).
43           where('(expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)').
44           first
45
46         # none exist; create one with the supplied token
47         if !api_client_auth
48           api_client_auth = ApiClientAuthorization.
49             new(user: system_user,
50               api_client_id: apiClient.id,
51               created_by_ip_address: '::1',
52               api_token: supplied_token)
53           api_client_auth.save!
54         end
55       end
56
57       api_client_auth.api_token
58     end
59   end
60 end