Class: YallaAuthRubyClient::AuthTokenMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/yalla_auth_ruby_client/middleware/auth_token_middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ AuthTokenMiddleware

Returns a new instance of AuthTokenMiddleware.



6
7
8
# File 'lib/yalla_auth_ruby_client/middleware/auth_token_middleware.rb', line 6

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/yalla_auth_ruby_client/middleware/auth_token_middleware.rb', line 10

def call(env)
  request = Rack::Request.new(env)

  if (token = request.params["token"])
    api_client = OpenapiClient::AuthApi.new
    begin
      response = api_client.auth_validate_token_get(token)

      if response && response.success
        request_env = ActionDispatch::Request.new(env)
        request_env.cookie_jar.signed[:auth_token] = { value: token, httponly: true }
      end
    rescue OpenapiClient::ApiError => e
      Rails.logger.error "Authentication failed: #{e.message}"
    end

    clean_url = request.fullpath.gsub(/[\?&]token=[^&]*/, "").sub(/\?$/, "")
    return [302, { "Location" => clean_url, "Content-Type" => "text/html" }, ["Redirecting..."]] unless clean_url == request.fullpath
  end

  @app.call(env)
end