Skip to content

Commit

Permalink
Add Client.is_expired
Browse files Browse the repository at this point in the history
Fixes #754
  • Loading branch information
wilbertom committed Aug 24, 2023
1 parent 7637284 commit 74e3386
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
6 changes: 5 additions & 1 deletion oauthlib/oauth2/rfc6749/clients/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,12 +213,16 @@ def add_token(self, uri, http_method='GET', body=None, headers=None,
if not (self.access_token or self.token.get('access_token')):
raise ValueError("Missing access token.")

if self._expires_at and self._expires_at < time.time():
if self.is_expired():
raise TokenExpiredError()

return case_insensitive_token_types[self.token_type.lower()](uri, http_method, body,
headers, token_placement, **kwargs)

def is_expired(self):
"""Returns true when the access token is expired."""
return self._expires_at and self._expires_at < time.time()

def prepare_authorization_request(self, authorization_url, state=None,
redirect_url=None, scope=None, **kwargs):
"""Prepare the authorization request.
Expand Down
12 changes: 12 additions & 0 deletions tests/oauth2/rfc6749/clients/test_base.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
import datetime
from unittest.mock import patch
import time

from oauthlib import common
from oauthlib.oauth2 import Client, InsecureTransportError, TokenExpiredError
Expand Down Expand Up @@ -135,6 +136,17 @@ def test_add_bearer_token(self):
self.assertRaises(ValueError, client.add_token, self.uri, body=self.body,
headers=self.headers)

def test_is_expired(self):
expired = 523549800
expired_token = {'expires_at': expired}
client = Client(self.client_id, token=expired_token, access_token=self.access_token, token_type="Bearer")
self.assertTrue(client.is_expired())

not_expired = time.time() + 60 * 10
token = {'expires_at': not_expired}
client = Client(self.client_id, token=token, access_token=self.access_token, token_type="Bearer")
self.assertFalse(client.is_expired())

def test_add_mac_token(self):
# Missing access token
client = Client(self.client_id, token_type="MAC")
Expand Down

0 comments on commit 74e3386

Please sign in to comment.