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