16306: Move nginx temp dirs into a subdir.
[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
33   # If token is supplied, see if it exists
34   if supplied_token
35     api_client_auth = ApiClientAuthorization.
36       where(api_token: supplied_token).
37       first
38     if !api_client_auth
39       # fall through to create a token
40     else
41       raise "Token exists, aborting!"
42     end
43   end
44
45   api_client_auth = ApiClientAuthorization.
46     new(user: anonymous_user,
47         api_client_id: 0,
48         expires_at: Time.now + 100.years,
49         scopes: ['GET /'],
50         api_token: supplied_token)
51   api_client_auth.save!
52   api_client_auth.reload
53   api_client_auth
54 end
55
56 if get_existing
57   api_client_auth = ApiClientAuthorization.
58     where('user_id=?', anonymous_user.id.to_i).
59     where('expires_at>?', Time.now).
60     select { |auth| auth.scopes == ['GET /'] }.
61     first
62 end
63
64 # either not a get or no api_client_auth was found
65 if !api_client_auth
66   api_client_auth = create_api_client_auth(supplied_token)
67 end
68
69 # print it to the console
70 puts api_client_auth.api_token