1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
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.
8 module CreateSuperUserToken
9 require File.dirname(__FILE__) + '/../config/boot'
10 require File.dirname(__FILE__) + '/../config/environment'
12 include ApplicationHelper
14 def create_superuser_token supplied_token=nil
16 # If token is supplied, verify that it indeed is a superuser token
18 api_client_auth = ApiClientAuthorization.
19 where(api_token: supplied_token).
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}."
30 # need to create a token
32 # Get (or create) trusted api client
33 apiClient = ApiClient.
34 find_or_create_by(url_prefix: "ssh://root@localhost/",
37 # Check if there is an unexpired superuser token corresponding to this api client
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)').
46 # none exist; create one with the supplied token
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)
57 "v2/" + api_client_auth.uuid + "/" + api_client_auth.api_token