Skip to content

Commit

Permalink
Merge pull request #26 from luizalabs/ro-enable_oauth2_validator_exte…
Browse files Browse the repository at this point in the history
…nsibility

Add get_queryset to CachedOAuth2Validator to enable extensibility
  • Loading branch information
RomuloOliveira committed May 11, 2017
2 parents 7e4a873 + 0238a29 commit 8e70389
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 5 deletions.
8 changes: 4 additions & 4 deletions django_toolkit/oauth2/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@

class CachedOAuth2Validator(OAuth2Validator):

def get_queryset(self):
return AccessToken.objects.select_related('application', 'user')

def validate_bearer_token(self, token, scopes, request):
if not token:
return False
Expand All @@ -33,10 +36,7 @@ def _get_access_token(self, token):
access_token = cache.get(token)

if access_token is None:
access_token = AccessToken.objects.select_related(
'application',
'user'
).get(
access_token = self.get_queryset().get(
token=token
)
now = timezone.now()
Expand Down
26 changes: 25 additions & 1 deletion docs/oauth2.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,28 @@ CACHES = {
'KEY_PREFIX': 'token',
}
}
```
```

If you want to provide a custom queryset, you can subclass `CachedOAuth2Validator`
and override the `get_queryset` method.

Example (Python 3):

```python
# custom_validator.py
from oauth2_provider.models import AccessToken

from django_toolkit.oauth2.validators import CachedOAuth2Validator

class CustomOAuth2QuerySetValidator(CachedOAuth2Validator):

def get_queryset(self):
return super().get_queryset().prefetch_related(
'application__custom_table'
)

# settings
OAUTH2_PROVIDER = {
'OAUTH2_VALIDATOR_CLASS': 'custom_validator.CustomOAuth2QuerySetValidator',
}
```
11 changes: 11 additions & 0 deletions tests/oauth2/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@

import pytest
from django.db import connection
from django.db.models.query import QuerySet
from django.test.utils import CaptureQueriesContext
from django.utils import timezone
from oauth2_provider.models import AccessToken

from django_toolkit.oauth2.validators import CachedOAuth2Validator

Expand Down Expand Up @@ -127,3 +129,12 @@ def test_validate_bearer_returns_false_when_invalid_token_is_provided(
http_request
)
assert not is_valid

def test_get_queryset_should_return_an_access_token_queryset(
self,
validator,
):
queryset = validator.get_queryset()

assert isinstance(queryset, QuerySet)
assert queryset.model == AccessToken

0 comments on commit 8e70389

Please sign in to comment.