Merge branch 'master' into 9998-unsigned_manifest
[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 && !api_client_auth.user.uuid.match(/-000000000000000$/)
18           raise "Token already exists but is not a superuser token."
19         end
20       end
21
22       # need to create a token
23       if !api_client_auth
24         # Get (or create) trusted api client
25         apiClient =  ApiClient.find_or_create_by_url_prefix_and_is_trusted("ssh://root@localhost/", true)
26
27         # Check if there is an unexpired superuser token corresponding to this api client
28         api_client_auth = ApiClientAuthorization.where(
29                 'user_id = (?) AND
30                  api_client_id = (?) AND
31                  (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
32                system_user.id, apiClient.id).first
33
34         # none exist; create one with the supplied token
35         if !api_client_auth
36           api_client_auth = ApiClientAuthorization.
37             new(user: system_user,
38               api_client_id: apiClient.id,
39               created_by_ip_address: '::1',
40               api_token: supplied_token)
41           api_client_auth.save!
42         end
43       end
44
45       api_client_auth.api_token
46     end
47   end
48 end