16726: Initialize anonymous user token in arvados-boot
[arvados.git] / services / api / script / get_anonymous_user_token.rb
1 #!/usr/bin/env ruby
2 # Copyright (C) The Arvados Authors. All rights reserved.
3 #
4 # SPDX-License-Identifier: AGPL-3.0
5
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.
9
10 require 'optimist'
11
12 opts = Optimist::options do
13   banner ''
14   banner "Usage: get_anonymous_user_token "
15   banner ''
16   opt :get, <<-eos
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.
19   eos
20   opt :token, "token to create (optional)", :type => :string
21 end
22
23 get_existing = opts[:get]
24 supplied_token = opts[:token]
25
26 require File.dirname(__FILE__) + '/../config/environment'
27
28 include ApplicationHelper
29 act_as_system_user
30
31 def create_api_client_auth(supplied_token=nil)
32   supplied_token = Rails.configuration.Users["AnonymousUserToken"]
33
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
38     return nil
39   end
40
41   attr = {user: anonymous_user,
42           api_client_id: 0,
43           scopes: ['GET /']}
44
45   secret = supplied_token
46
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.
51       puts supplied_token
52       return nil
53     end
54     attr[:uuid] = token_uuid
55   end
56
57   attr[:api_token] = secret
58
59   api_client_auth = ApiClientAuthorization.where(attr).first
60   if !api_client_auth
61     api_client_auth = ApiClientAuthorization.create!(attr)
62   end
63   api_client_auth
64 end
65
66 if get_existing
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 /'] }.
71     first
72 end
73
74 # either not a get or no api_client_auth was found
75 if !api_client_auth
76   api_client_auth = create_api_client_auth(supplied_token)
77 end
78
79 # print it to the console
80 if api_client_auth
81   puts "v2/#{api_client_auth.uuid}/#{api_client_auth.api_token}"
82 end