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.
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 if app.respond_to?(:call)
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
23 request = Rack::Request.new(env)
24 params = request.params
25 remote_ip = env["action_dispatch.remote_ip"]
27 Thread.current[:request_starttime] = Time.now
32 params["api_token"] ||
33 params["oauth_token"] ||
34 env["HTTP_AUTHORIZATION"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
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).
40 if api_client_auth.andand.user
41 user = api_client_auth.user
42 api_client = api_client_auth.api_client
44 # Token seems valid, but points to a non-existent (deleted?) user.
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
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