8784: Fix test for latest firefox.
[arvados.git] / services / api / app / middlewares / arvados_api_token.rb
1 # Perform api_token checking very early in the request process.  We want to do
2 # this in the Rack stack instead of in ApplicationController because
3 # websockets needs access to authentication but doesn't use any of the rails
4 # active dispatch infrastructure.
5 class ArvadosApiToken
6
7   # Create a new ArvadosApiToken handler
8   # +app+  The next layer of the Rack stack.
9   def initialize(app = nil, options = nil)
10     @app = app.respond_to?(:call) ? app : nil
11   end
12
13   def call env
14     # First, clean up just in case we have a multithreaded server and thread
15     # local variables are still set from a prior request.  Also useful for
16     # tests that call this code to set up the environment.
17     Thread.current[:api_client_ip_address] = nil
18     Thread.current[:api_client_authorization] = nil
19     Thread.current[:api_client_uuid] = nil
20     Thread.current[:api_client] = nil
21     Thread.current[:user] = nil
22
23     request = Rack::Request.new(env)
24     params = request.params
25     remote_ip = env["action_dispatch.remote_ip"]
26
27     Thread.current[:request_starttime] = Time.now
28     user = nil
29     api_client = nil
30     api_client_auth = nil
31     supplied_token =
32       params["api_token"] ||
33       params["oauth_token"] ||
34       env["HTTP_AUTHORIZATION"].andand.match(/OAuth2 ([a-zA-Z0-9]+)/).andand[1]
35     if supplied_token
36       api_client_auth = ApiClientAuthorization.
37         includes(:api_client, :user).
38         where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', supplied_token).
39         first
40       if api_client_auth.andand.user
41         user = api_client_auth.user
42         api_client = api_client_auth.api_client
43       else
44         # Token seems valid, but points to a non-existent (deleted?) user.
45         api_client_auth = nil
46       end
47     end
48     Thread.current[:api_client_ip_address] = remote_ip
49     Thread.current[:api_client_authorization] = api_client_auth
50     Thread.current[:api_client_uuid] = api_client.andand.uuid
51     Thread.current[:api_client] = api_client
52     Thread.current[:user] = user
53     if api_client_auth
54       api_client_auth.last_used_at = Time.now
55       api_client_auth.last_used_by_ip_address = remote_ip.to_s
56       api_client_auth.save validate: false
57     end
58
59     @app.call env if @app
60   end
61 end