Merge branch '8784-dir-listings'
[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 'trollop'
11
12 opts = Trollop::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 end
21
22 get_existing = opts[:get]
23
24 require File.dirname(__FILE__) + '/../config/environment'
25
26 include ApplicationHelper
27 act_as_system_user
28
29 def create_api_client_auth
30   api_client_auth = ApiClientAuthorization.
31     new(user: anonymous_user,
32         api_client_id: 0,
33         expires_at: Time.now + 100.years,
34         scopes: ['GET /'])
35   api_client_auth.save!
36   api_client_auth.reload
37 end
38
39 if get_existing
40   api_client_auth = ApiClientAuthorization.
41     where('user_id=?', anonymous_user.id.to_i).
42     where('expires_at>?', Time.now).
43     select { |auth| auth.scopes == ['GET /'] }.
44     first
45 end
46
47 # either not a get or no api_client_auth was found
48 if !api_client_auth
49   api_client_auth = create_api_client_auth
50 end
51
52 # print it to the console
53 puts api_client_auth.api_token