Class: SimpleFCM::AuthorizationMiddleware
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- SimpleFCM::AuthorizationMiddleware
- Defined in:
- lib/simple_fcm/authorization_middleware.rb
Constant Summary collapse
- DEFAULT_EXPIRY_THRESHOLD =
Automatically refresh the access token when it is due to expire within the next 3 minutes.
180
Instance Method Summary collapse
-
#initialize(app, credentials, expiry_threshold: DEFAULT_EXPIRY_THRESHOLD) ⇒ AuthorizationMiddleware
constructor
A new instance of AuthorizationMiddleware.
- #on_request(env) ⇒ Object
-
#refresh! ⇒ Object
Force a refresh of the access token.
-
#refresh? ⇒ Boolean
Returns true when the access token should be fetched or refreshed.
Constructor Details
#initialize(app, credentials, expiry_threshold: DEFAULT_EXPIRY_THRESHOLD) ⇒ AuthorizationMiddleware
Returns a new instance of AuthorizationMiddleware.
11 12 13 14 15 16 17 18 19 20 |
# File 'lib/simple_fcm/authorization_middleware.rb', line 11 def initialize(app, credentials, expiry_threshold: DEFAULT_EXPIRY_THRESHOLD) @credentials = credentials @expiry_threshold = expiry_threshold if @expiry_threshold < 0 raise ArugmentError, "expiry_threshold must be greater than or equal to 0" end super(app) end |
Instance Method Details
#on_request(env) ⇒ Object
36 37 38 39 40 41 42 |
# File 'lib/simple_fcm/authorization_middleware.rb', line 36 def on_request(env) if refresh? refresh! end env.request_headers["Authorization"] = "#{@type} #{@token}" end |
#refresh! ⇒ Object
Force a refresh of the access token
23 24 25 26 27 28 29 |
# File 'lib/simple_fcm/authorization_middleware.rb', line 23 def refresh! fetched = @credentials.fetch_access_token! @token = fetched["access_token"] @type = fetched["token_type"] @expires_at = Time.now.utc + fetched["expires_in"] end |
#refresh? ⇒ Boolean
Returns true when the access token should be fetched or refreshed.
32 33 34 |
# File 'lib/simple_fcm/authorization_middleware.rb', line 32 def refresh? @expires_at.nil? || @expires_at <= (Time.now.utc - @expiry_threshold) end |