Class: Idsimple::Rack::ValidatorMiddleware

Inherits:
Object
  • Object
show all
Includes:
Helper
Defined in:
lib/idsimple/rack/validator_middleware.rb

Constant Summary collapse

DECODED_ACCESS_TOKEN_ENV_KEY =
"idsimple.decoded_access_token"

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helper

#api, #configuration, #decode_access_token, #get_access_token, #logger, #redirect_to_authenticate_or_unauthorized_response, #remove_access_token, #set_access_token, #signing_secret, #unauthorized_response

Constructor Details

#initialize(app) ⇒ ValidatorMiddleware

Returns a new instance of ValidatorMiddleware.



14
15
16
# File 'lib/idsimple/rack/validator_middleware.rb', line 14

def initialize(app)
  @app = app
end

Instance Attribute Details

#appObject (readonly)

Returns the value of attribute app.



12
13
14
# File 'lib/idsimple/rack/validator_middleware.rb', line 12

def app
  @app
end

Instance Method Details

#call(env) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/idsimple/rack/validator_middleware.rb', line 18

def call(env)
  return app.call(env) unless configuration.enabled?

  req = ::Rack::Request.new(env)

  if req.path == configuration.authenticate_path
    logger.debug("Attempting to authenticate. Skipping validation.")
    return app.call(env)
  end

  if configuration.skip_on && configuration.skip_on.call(req)
    logger.debug("Skipping validator due to skip_on rules")
    return app.call(env)
  end

  access_token = get_access_token(req)

  return redirect_to_authenticate_or_unauthorized_response(req) unless access_token

  logger.debug("Retrieved access token from store")
  decoded_access_token = decode_access_token(access_token, signing_secret)
  logger.debug("Decoded access token")

  validation_result = AccessTokenValidator.validate_used_token_custom_claims(decoded_access_token, req)
  if validation_result.invalid?
    logger.warn("Attempted to access with invalid used token: #{validation_result.full_error_message}")
    return redirect_to_authenticate_or_unauthorized_response(req)
  end

  if (refresh_at = decoded_access_token[0]["idsimple.refresh_at"]) && refresh_at < Time.now.to_i
    logger.debug("Refreshing access token")
    jti = decoded_access_token[0]["jti"]
    handle_refresh_access_token(jti, req)
  else
    env[DECODED_ACCESS_TOKEN_ENV_KEY] = decoded_access_token
    app.call(env)
  end
rescue JWT::DecodeError => e
  logger.warn("Error while decoding token: #{e.class} - #{e.message}")
  redirect_to_authenticate_or_unauthorized_response(req)
end