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