Skip to content

Commit

Permalink
Revert "Openid Connect Core support - Round 2 (#859)"
Browse files Browse the repository at this point in the history
This reverts commit 4655c03.
  • Loading branch information
n2ygk committed Oct 6, 2020
1 parent 295c065 commit fcfc318
Show file tree
Hide file tree
Showing 28 changed files with 259 additions and 2,897 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Expand Up @@ -25,7 +25,7 @@ __pycache__
pip-log.txt

# Unit test / coverage reports
.pytest_cache
.cache
.coverage
.tox
.pytest_cache/
Expand Down
9 changes: 1 addition & 8 deletions oauth2_provider/admin.py
Expand Up @@ -2,7 +2,7 @@

from .models import (
get_access_token_model, get_application_model,
get_grant_model, get_id_token_model, get_refresh_token_model
get_grant_model, get_refresh_token_model
)


Expand All @@ -26,11 +26,6 @@ class AccessTokenAdmin(admin.ModelAdmin):
raw_id_fields = ("user", "source_refresh_token")


class IDTokenAdmin(admin.ModelAdmin):
list_display = ("token", "user", "application", "expires")
raw_id_fields = ("user", )


class RefreshTokenAdmin(admin.ModelAdmin):
list_display = ("token", "user", "application")
raw_id_fields = ("user", "access_token")
Expand All @@ -39,11 +34,9 @@ class RefreshTokenAdmin(admin.ModelAdmin):
Application = get_application_model()
Grant = get_grant_model()
AccessToken = get_access_token_model()
IDToken = get_id_token_model()
RefreshToken = get_refresh_token_model()

admin.site.register(Application, ApplicationAdmin)
admin.site.register(Grant, GrantAdmin)
admin.site.register(AccessToken, AccessTokenAdmin)
admin.site.register(IDToken, IDTokenAdmin)
admin.site.register(RefreshToken, RefreshTokenAdmin)
1 change: 0 additions & 1 deletion oauth2_provider/forms.py
Expand Up @@ -5,7 +5,6 @@ class AllowForm(forms.Form):
allow = forms.BooleanField(required=False)
redirect_uri = forms.CharField(widget=forms.HiddenInput())
scope = forms.CharField(widget=forms.HiddenInput())
nonce = forms.CharField(required=False, widget=forms.HiddenInput())
client_id = forms.CharField(widget=forms.HiddenInput())
state = forms.CharField(required=False, widget=forms.HiddenInput())
response_type = forms.CharField(widget=forms.HiddenInput())
Expand Down
2 changes: 2 additions & 0 deletions oauth2_provider/migrations/0002_auto_20190406_1805.py
@@ -1,3 +1,5 @@
# Generated by Django 2.2 on 2019-04-06 18:05

from django.db import migrations, models


Expand Down
48 changes: 0 additions & 48 deletions oauth2_provider/migrations/0003_auto_20200902_2022.py

This file was deleted.

114 changes: 0 additions & 114 deletions oauth2_provider/models.py
@@ -1,4 +1,3 @@
import json
import logging
from datetime import timedelta
from urllib.parse import parse_qsl, urlparse
Expand All @@ -10,7 +9,6 @@
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from jwcrypto import jwk, jwt

from .generators import generate_client_id, generate_client_secret
from .scopes import get_scopes_backend
Expand Down Expand Up @@ -52,20 +50,11 @@ class AbstractApplication(models.Model):
GRANT_IMPLICIT = "implicit"
GRANT_PASSWORD = "password"
GRANT_CLIENT_CREDENTIALS = "client-credentials"
GRANT_OPENID_HYBRID = "openid-hybrid"
GRANT_TYPES = (
(GRANT_AUTHORIZATION_CODE, _("Authorization code")),
(GRANT_IMPLICIT, _("Implicit")),
(GRANT_PASSWORD, _("Resource owner password-based")),
(GRANT_CLIENT_CREDENTIALS, _("Client credentials")),
(GRANT_OPENID_HYBRID, _("OpenID connect hybrid")),
)

RS256_ALGORITHM = "RS256"
HS256_ALGORITHM = "HS256"
ALGORITHM_TYPES = (
(RS256_ALGORITHM, _("RSA with SHA-2 256")),
(HS256_ALGORITHM, _("HMAC with SHA-2 256")),
)

id = models.BigAutoField(primary_key=True)
Expand Down Expand Up @@ -93,7 +82,6 @@ class AbstractApplication(models.Model):

created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
algorithm = models.CharField(max_length=5, choices=ALGORITHM_TYPES, default=RS256_ALGORITHM)

class Meta:
abstract = True
Expand Down Expand Up @@ -294,10 +282,6 @@ class AbstractAccessToken(models.Model):
related_name="refreshed_access_token"
)
token = models.CharField(max_length=255, unique=True, )
id_token = models.OneToOneField(
oauth2_settings.ID_TOKEN_MODEL, on_delete=models.CASCADE, blank=True, null=True,
related_name="access_token"
)
application = models.ForeignKey(
oauth2_settings.APPLICATION_MODEL, on_delete=models.CASCADE, blank=True, null=True,
)
Expand Down Expand Up @@ -431,99 +415,6 @@ class Meta(AbstractRefreshToken.Meta):
swappable = "OAUTH2_PROVIDER_REFRESH_TOKEN_MODEL"


class AbstractIDToken(models.Model):
"""
An IDToken instance represents the actual token to
access user's resources, as in :openid:`2`.
Fields:
* :attr:`user` The Django user representing resources' owner
* :attr:`token` ID token
* :attr:`application` Application instance
* :attr:`expires` Date and time of token expiration, in DateTime format
* :attr:`scope` Allowed scopes
"""
id = models.BigAutoField(primary_key=True)
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True,
related_name="%(app_label)s_%(class)s"
)
token = models.TextField(unique=True)
application = models.ForeignKey(
oauth2_settings.APPLICATION_MODEL, on_delete=models.CASCADE, blank=True, null=True,
)
expires = models.DateTimeField()
scope = models.TextField(blank=True)

created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

def is_valid(self, scopes=None):
"""
Checks if the access token is valid.
:param scopes: An iterable containing the scopes to check or None
"""
return not self.is_expired() and self.allow_scopes(scopes)

def is_expired(self):
"""
Check token expiration with timezone awareness
"""
if not self.expires:
return True

return timezone.now() >= self.expires

def allow_scopes(self, scopes):
"""
Check if the token allows the provided scopes
:param scopes: An iterable containing the scopes to check
"""
if not scopes:
return True

provided_scopes = set(self.scope.split())
resource_scopes = set(scopes)

return resource_scopes.issubset(provided_scopes)

def revoke(self):
"""
Convenience method to uniform tokens' interface, for now
simply remove this token from the database in order to revoke it.
"""
self.delete()

@property
def scopes(self):
"""
Returns a dictionary of allowed scope names (as keys) with their descriptions (as values)
"""
all_scopes = get_scopes_backend().get_all_scopes()
token_scopes = self.scope.split()
return {name: desc for name, desc in all_scopes.items() if name in token_scopes}

@property
def claims(self):
key = jwk.JWK.from_pem(oauth2_settings.OIDC_RSA_PRIVATE_KEY.encode("utf8"))
jwt_token = jwt.JWT(key=key, jwt=self.token)
return json.loads(jwt_token.claims)

def __str__(self):
return self.token

class Meta:
abstract = True


class IDToken(AbstractIDToken):
class Meta(AbstractIDToken.Meta):
swappable = "OAUTH2_PROVIDER_ID_TOKEN_MODEL"


def get_application_model():
""" Return the Application model that is active in this project. """
return apps.get_model(oauth2_settings.APPLICATION_MODEL)
Expand All @@ -539,11 +430,6 @@ def get_access_token_model():
return apps.get_model(oauth2_settings.ACCESS_TOKEN_MODEL)


def get_id_token_model():
""" Return the AccessToken model that is active in this project. """
return apps.get_model(oauth2_settings.ID_TOKEN_MODEL)


def get_refresh_token_model():
""" Return the RefreshToken model that is active in this project. """
return apps.get_model(oauth2_settings.REFRESH_TOKEN_MODEL)
Expand Down
26 changes: 5 additions & 21 deletions oauth2_provider/oauth2_backends.py
Expand Up @@ -104,16 +104,15 @@ def validate_authorization_request(self, request):
except oauth2.OAuth2Error as error:
raise OAuthToolkitError(error=error)

def create_authorization_response(self, uri, request, scopes, credentials, body, allow):
def create_authorization_response(self, request, scopes, credentials, allow):
"""
A wrapper method that calls create_authorization_response on `server_class`
instance.
:param request: The current django.http.HttpRequest object
:param scopes: A list of provided scopes
:param credentials: Authorization credentials dictionary containing
`client_id`, `state`, `redirect_uri` and `response_type`
:param body: Other body parameters not used in credentials dictionary
`client_id`, `state`, `redirect_uri`, `response_type`
:param allow: True if the user authorize the client, otherwise False
"""
try:
Expand All @@ -125,10 +124,10 @@ def create_authorization_response(self, uri, request, scopes, credentials, body,
credentials["user"] = request.user

headers, body, status = self.server.create_authorization_response(
uri=uri, scopes=scopes, credentials=credentials, body=body)
redirect_uri = headers.get("Location", None)
uri=credentials["redirect_uri"], scopes=scopes, credentials=credentials)
uri = headers.get("Location", None)

return redirect_uri, headers, body, status
return uri, headers, body, status

except oauth2.FatalClientError as error:
raise FatalClientError(
Expand Down Expand Up @@ -167,21 +166,6 @@ def create_revocation_response(self, request):

return uri, headers, body, status

def create_userinfo_response(self, request):
"""
A wrapper method that calls create_userinfo_response on a
`server_class` instance.
:param request: The current django.http.HttpRequest object
"""
uri, http_method, body, headers = self._extract_params(request)
headers, body, status = self.server.create_userinfo_response(
uri, http_method, body, headers
)
uri = headers.get("Location", None)

return uri, headers, body, status

def verify_request(self, request, scopes):
"""
A wrapper method that calls verify_request on `server_class` instance.
Expand Down

0 comments on commit fcfc318

Please sign in to comment.