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.
4 module CreateSuperUserToken
5 require File.dirname(__FILE__) + '/../config/boot'
6 require File.dirname(__FILE__) + '/../config/environment'
8 include ApplicationHelper
10 def create_superuser_token supplied_token=nil
12 # If token is supplied, verify that it indeed is a superuser token
14 api_client_auth = ApiClientAuthorization.
15 where(api_token: supplied_token).
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}."
26 # need to create a token
28 # Get (or create) trusted api client
29 apiClient = ApiClient.find_or_create_by_url_prefix_and_is_trusted("ssh://root@localhost/", true)
31 # Check if there is an unexpired superuser token corresponding to this api client
32 api_client_auth = ApiClientAuthorization.where(
36 (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
37 system_user.id, apiClient.id, ['all'].to_yaml).first
39 # none exist; create one with the supplied token
41 api_client_auth = ApiClientAuthorization.
42 new(user: system_user,
43 api_client_id: apiClient.id,
44 created_by_ip_address: '::1',
45 api_token: supplied_token)
50 api_client_auth.api_token