Merge branch 'master' into 5383-api-db-current-time
[arvados.git] / services / api / script / get_anonymous_user_token.rb
1 #!/usr/bin/env ruby
2
3 # Get or Create an anonymous user token.
4 # If get option is used, an existing anonymous user token is returned. If none exist, one is created.
5 # If the get option is omitted, a new token is created and returned.
6
7 require 'trollop'
8
9 opts = Trollop::options do
10   banner ''
11   banner "Usage: get_anonymous_user_token "
12   banner ''
13   opt :get, <<-eos
14 Get an existing anonymous user token. If no such token exists \
15 or if this option is omitted, a new token is created and returned.
16   eos
17 end
18
19 get_existing = opts[:get]
20
21 require File.dirname(__FILE__) + '/../config/environment'
22
23 include ApplicationHelper
24 include DbCurrentTime
25
26 act_as_system_user
27
28 def create_api_client_auth
29   api_client_auth = ApiClientAuthorization.
30     new(user: anonymous_user,
31         api_client_id: 0,
32         expires_at: db_current_time + 100.years,
33         scopes: ['GET /'])
34   api_client_auth.save!
35   api_client_auth.reload
36 end
37
38 if get_existing
39   api_client_auth = ApiClientAuthorization.
40     where('user_id=?', anonymous_user.id.to_i).
41     where('expires_at>?', db_current_time).
42     select { |auth| auth.scopes == ['GET /'] }.
43     first
44 end
45
46 # either not a get or no api_client_auth was found
47 if !api_client_auth
48   api_client_auth = create_api_client_auth
49 end
50
51 # print it to the console
52 puts api_client_auth.api_token