12627: Set current_user from first valid reader_token
[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     if request.get?
36       reader_tokens = params["reader_tokens"]
37       if reader_tokens.is_a? String
38         reader_tokens = SafeJSON.load(reader_tokens)
39       end
40     else
41       reader_tokens = nil
42     end
43
44     # Set current_user etc. based on the primary session token if a
45     # valid one is present. Otherwise, use the first valid token in
46     # reader_tokens.
47     [params["api_token"],
48      params["oauth_token"],
49      env["HTTP_AUTHORIZATION"].andand.match(/OAuth2 ([a-zA-Z0-9]+)/).andand[1],
50      *reader_tokens,
51     ].each do |supplied|
52       next if !supplied
53       try_auth = ApiClientAuthorization.
54         includes(:api_client, :user).
55         where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', supplied).
56         first
57       if try_auth.andand.user
58         api_client_auth = try_auth
59         user = api_client_auth.user
60         api_client = api_client_auth.api_client
61         break
62       end
63     end
64     Thread.current[:api_client_ip_address] = remote_ip
65     Thread.current[:api_client_authorization] = api_client_auth
66     Thread.current[:api_client_uuid] = api_client.andand.uuid
67     Thread.current[:api_client] = api_client
68     Thread.current[:user] = user
69
70     @app.call env if @app
71   end
72 end