2 # Copyright (C) The Arvados Authors. All rights reserved.
4 # SPDX-License-Identifier: AGPL-3.0
6 # Get or Create an anonymous user token.
7 # If get option is used, an existing anonymous user token is returned. If none exist, one is created.
8 # If the get option is omitted, a new token is created and returned.
12 opts = Optimist::options do
14 banner "Usage: get_anonymous_user_token "
17 Get an existing anonymous user token. If no such token exists \
18 or if this option is omitted, a new token is created and returned.
20 opt :token, "token to create (optional)", :type => :string
23 get_existing = opts[:get]
24 supplied_token = opts[:token]
26 require File.dirname(__FILE__) + '/../config/environment'
28 include ApplicationHelper
31 def create_api_client_auth(supplied_token=nil)
32 supplied_token = Rails.configuration.Users["AnonymousUserToken"]
34 if supplied_token.nil? or supplied_token.empty?
35 puts "Users.AnonymousUserToken is empty. Destroying tokens that belong to anonymous."
36 # Token is empty. Destroy any anonymous tokens.
37 ApiClientAuthorization.where(user: anonymous_user).destroy_all
41 attr = {user: anonymous_user,
45 secret = supplied_token
47 if supplied_token[0..2] == 'v2/'
48 _, token_uuid, secret, optional = supplied_token.split('/')
49 if token_uuid[0..4] != Rails.configuration.ClusterID
50 # Belongs to a different cluster.
54 attr[:uuid] = token_uuid
57 attr[:api_token] = secret
59 api_client_auth = ApiClientAuthorization.where(attr).first
61 api_client_auth = ApiClientAuthorization.create!(attr)
67 api_client_auth = ApiClientAuthorization.
68 where('user_id=?', anonymous_user.id.to_i).
69 where('expires_at>?', Time.now).
70 select { |auth| auth.scopes == ['GET /'] }.
74 # either not a get or no api_client_auth was found
76 api_client_auth = create_api_client_auth(supplied_token)
79 # print it to the console
81 puts "v2/#{api_client_auth.uuid}/#{api_client_auth.api_token}"