From ca308dfed88f5773a73fc4bb9be060de301b9044 Mon Sep 17 00:00:00 2001 From: mahdavi Date: Thu, 25 Jul 2024 23:51:50 +0330 Subject: [PATCH] cleanup --- apps/gooyal_oauth2/validators.py | 59 +++++++++----------------------- apps/users/models.py | 7 ++-- apps/users/urls.py | 2 +- apps/users/views.py | 5 ++- wallet/settings.py | 1 + 5 files changed, 27 insertions(+), 47 deletions(-) diff --git a/apps/gooyal_oauth2/validators.py b/apps/gooyal_oauth2/validators.py index 92f5dd1..e8de68e 100755 --- a/apps/gooyal_oauth2/validators.py +++ b/apps/gooyal_oauth2/validators.py @@ -1,52 +1,21 @@ -import base64 -import binascii -import logging -from datetime import datetime, timedelta -from urllib.parse import unquote_plus - -import requests # import service_clients -from django.contrib.auth import get_user_model -from django.utils.timezone import make_aware -from oauth2_provider.models import get_access_token_model -from oauth2_provider.oauth2_validators import OAuth2Validator as BaseOAuth2Validator import base64 -import binascii import http.client -import inspect -import json import logging -import uuid -from collections import OrderedDict from datetime import datetime, timedelta -from urllib.parse import unquote_plus import requests from django.conf import settings -from django.contrib.auth import authenticate, get_user_model -from django.contrib.auth.hashers import check_password, identify_hasher -from django.core.exceptions import ObjectDoesNotExist -from django.db import transaction -from django.db.models import Q -from django.http import HttpRequest -from django.utils import dateformat, timezone -from django.utils.crypto import constant_time_compare +from django.contrib.auth import get_user_model from django.utils.timezone import make_aware -from django.utils.translation import gettext_lazy as _ -from jwcrypto import jws, jwt -from jwcrypto.common import JWException -from jwcrypto.jwt import JWTExpired -from oauthlib.oauth2.rfc6749 import utils -from oauthlib.openid import RequestValidator - from oauth2_provider.models import ( - AbstractApplication, get_access_token_model, get_application_model, get_grant_model, get_id_token_model, get_refresh_token_model, ) +from oauth2_provider.oauth2_validators import OAuth2Validator as BaseOAuth2Validator from oauth2_provider.settings import oauth2_settings from oauth2_provider.utils import get_timezone @@ -146,15 +115,17 @@ class OAuth2Validator(BaseOAuth2Validator): # pylint: disable=w0223 log.exception("Introspection: Failed to parse response as json") return None - client_owner_value = None + owner_value = None + application_uuid = None if "active" in application_introspection_content and application_introspection_content["active"] is True: - if "client_owner" in application_introspection_content: - client_owner_value = application_introspection_content["client_owner"] + if "owner" in application_introspection_content: + owner_value = application_introspection_content["owner"] + application_uuid = application_introspection_content.get("uuid") - if client_owner_value: - client_owner, _ = UserModel.objects.get_or_create(pk=client_owner_value) + if owner_value: + owner, _ = UserModel.objects.get_or_create(pk=owner_value) else: - client_owner = None + owner = None if "username" in content: user = self.get_or_create_user_from_content(content) @@ -180,13 +151,17 @@ class OAuth2Validator(BaseOAuth2Validator): # pylint: disable=w0223 ) # TODO: get application owner and put it here + application, _created = Application.objects.get_or_create( + client_id=content["client_id"], + uuid=application_introspection_content["uuid"] + ) access_token, _created = AccessToken.objects.update_or_create( token=token, defaults={ "user": user, - "client_id": content.get("client_id", ""), - "client_owner": client_owner, - "application": None, + "client_id": content["client_id"], + "client_owner": owner, + "application_id": application_uuid, "scope": scope, "expires": expires, }, diff --git a/apps/users/models.py b/apps/users/models.py index e5826bb..f954eb6 100644 --- a/apps/users/models.py +++ b/apps/users/models.py @@ -96,10 +96,11 @@ class OAuthCode(models.Model): return code_challenge def generate_login_url(self): - url = f'''{settings.BASE_OAUTH2_PROVIDER_URL}/oauth2/authorize/?response_type=code&code_challenge={self.generate_code_challenge()}&code_challenge_method=S256&client_id={settings.CLIENT_ID}&scope=wallet.wallet:get_balance+wallet.transaction:list&state={self.uuid}''' + redirect_uri = 'http://127.0.0.1:8000/users/login/callback/' + url = f'{settings.BASE_OAUTH2_PROVIDER_URL}/oauth2/authorize/?response_type=code&code_challenge={self.generate_code_challenge()}&code_challenge_method=S256&client_id={settings.CLIENT_ID}&scope={settings.SCOPES}&state={self.uuid}&redirect_uri={self.redirect_uri}' return url - def validate_code(self): + def validate_code(self, redirect_uri): headers = { "Content-Type": "application/x-www-form-urlencoded", } @@ -108,7 +109,7 @@ class OAuthCode(models.Model): "client_secret": settings.CLIENT_SECRET, "code": self.code, "code_verifier": self.code_verifier, - # "redirect_uri=http://127.0.0.1:8000/noexist/callback", + "redirect_uri": redirect_uri, "grant_type": "authorization_code" } diff --git a/apps/users/urls.py b/apps/users/urls.py index fb5ffa6..cf6858f 100644 --- a/apps/users/urls.py +++ b/apps/users/urls.py @@ -5,7 +5,7 @@ app_name = "users" urlpatterns = [ path('login/request/', OAUTHLoginRequestView.as_view(), name='login_request'), - path('login/callback/', OAUTHLoginCallbackView.as_view(), name='login_calback'), + path('login/callback/', OAUTHLoginCallbackView.as_view(), name='login_callback'), path('account/', AccountDetailView.as_view(), name='account_detail'), path('account/update/', AccountUpdateView.as_view(), name='account_update'), ] diff --git a/apps/users/views.py b/apps/users/views.py index 4c4d579..1b770ae 100644 --- a/apps/users/views.py +++ b/apps/users/views.py @@ -25,7 +25,9 @@ class OAUTHLoginRequestView(CreateView): template_name = 'users/login_request.html' def form_valid(self, form): + redirect_uri = self.request.build_absolute_uri(reverse('users:login_callback')) self.object: OAuthCode = form.save(commit=False) + self.object.redirect_uri = redirect_uri self.object.generate_code_verifier() self.object.save() return HttpResponseRedirect(self.object.generate_login_url()) @@ -61,7 +63,8 @@ class OAUTHLoginCallbackView(DetailView): return access_token def get_context_data(self, **kwargs): - data = self.object.validate_code() + redirect_uri = self.request.build_absolute_uri(reverse('users:login_callback')) + data = self.object.validate_code(redirect_uri=redirect_uri) # {'access_token': 'WhnIAfci6yIyTsh63PPqM1HXfXqKvr', 'expires_in': 36000, 'token_type': 'Bearer', # 'scope': 'wallet.wallet:get_balance wallet.transaction:list', # 'refresh_token': 'qRHFXXc3R3EiQKUq5BcSY2b9xuTm0d'} diff --git a/wallet/settings.py b/wallet/settings.py index 18d59ef..a80a21f 100644 --- a/wallet/settings.py +++ b/wallet/settings.py @@ -79,6 +79,7 @@ OAUTH2_PROVIDER_REFRESH_TOKEN_MODEL = "gooyal_oauth2.RefreshToken" BASE_OAUTH2_PROVIDER_URL = "https://accounts.gooyal.com" CLIENT_ID = 'dCHm08iIoXvbRSgOI79SV6kIs0aoUzwJehtoczvJ' CLIENT_SECRET = 'QBGwaye4Mvr2JHAtn5lQpZhd3RfSVw4XZNrgt6P4UBuV7u6IhsJXUV5QYv3v6rQYEuzjZdKYMjDQuXPmjHeF5UI5fFx080E7FPxFfYHIYBr3ZyvuPi1u7zDRF0EQbzbH' +SCOPES = config('SCOPES', default='') OAUTH2_PROVIDER = { # this is the list of available scopes # 'SCOPES_BACKEND_CLASS': 'apps.gooyal_oauth2.scopes.Scopes',