1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
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.
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
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
27 request = Rack::Request.new(env)
28 params = request.params
29 remote_ip = env["action_dispatch.remote_ip"]
31 Thread.current[:request_starttime] = Time.now
36 reader_tokens = params["reader_tokens"]
37 if reader_tokens.is_a? String
38 reader_tokens = SafeJSON.load(reader_tokens)
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
48 params["oauth_token"],
49 env["HTTP_AUTHORIZATION"].andand.match(/OAuth2 ([a-zA-Z0-9]+)/).andand[1],
53 try_auth = ApiClientAuthorization.
54 includes(:api_client, :user).
55 where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', supplied).
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
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