jazzband / django-oauth-toolkit

OAuth2 goodies for the Djangonauts!
https://django-oauth-toolkit.readthedocs.io
Other
3.06k stars 777 forks source link

Generate token after autorization #1415

Closed Kanellaman closed 2 months ago

Kanellaman commented 2 months ago

I have setup my applicaiton using a public client and authorization code.

I also have expanded the model of AccessToken to add an addition foreign key like this: models.py

class AccessToken(AbstractAccessToken):
    subscription = models.ForeignKey(
        Subscription,
        on_delete=models.CASCADE,
        related_name="SUBSCRIPTION",
        blank=True,
        null=True,
    )

class Application(AbstractApplication):
    pass

class Grant(AbstractGrant):
    pass

class RefreshToken(AbstractRefreshToken):
    pass

settings.py

OAUTH2_PROVIDER_ACCESS_TOKEN_MODEL = 'api.AccessToken'
OAUTH2_PROVIDER_APPLICATION_MODEL = 'api.Application'
OAUTH2_PROVIDER_REFRESH_TOKEN_MODEL = 'api.RefreshToken'
OAUTH2_PROVIDER_GRANT_MODEL = "api.Grant"
OAUTH2_PROVIDER_ID_TOKEN_MODEL = 'oauth2_provider.IDToken'

Is there a way to modify how the o/token operates to initialize the subscription foreign key?

Kanellaman commented 2 months ago

I resolved it by expanding the validator

from oauth2_provider.oauth2_validators import OAuth2Validator
from .models import AccessToken, RefreshToken
from store.models import Subscription
from django.http import JsonResponse

class CustomOAuth2Validator(OAuth2Validator):
    def save_bearer_token(self, token, request, *args, **kwargs):
        super().save_bearer_token(token, request, *args, **kwargs)
        # Assuming the header for subscription is 'X-Subscription'
        subscription_id = request.headers.get('HTTP_SUBSCRIPTION')
        if subscription_id:
            try:
                subscription = Subscription.objects.get(uuid=subscription_id)
                # Update the AccessToken with the subscription
                access_token = AccessToken.objects.get(token=token['access_token'])
                access_token.subscription = subscription
                access_token.save()
            except Subscription.DoesNotExist:
                return JsonResponse({"error": "Wrong subscription ID"}, status=400)