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 params["api_token"] ||
37 params["oauth_token"] ||
38 env["HTTP_AUTHORIZATION"].andand.match(/OAuth2 ([a-zA-Z0-9]+)/).andand[1]
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).
44 if api_client_auth.andand.user
45 user = api_client_auth.user
46 api_client = api_client_auth.api_client
48 # Token seems valid, but points to a non-existent (deleted?) user.
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
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