Skip to content

Commit

Permalink
Formatting and clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
iMerica committed May 17, 2021
1 parent acff9eb commit acf2136
Show file tree
Hide file tree
Showing 20 changed files with 515 additions and 427 deletions.
2 changes: 1 addition & 1 deletion dj_rest_auth/__version__.py
@@ -1,7 +1,7 @@
__title__ = 'dj-rest-auth'
__description__ = 'Authentication and Registration in Django Rest Framework.'
__url__ = 'http://github.com/iMerica/dj-rest-auth'
__version__ = '2.1.4'
__version__ = '2.1.5'
__author__ = '@iMerica https://github.com/iMerica'
__author_email__ = 'imichael@pm.me'
__license__ = 'MIT'
Expand Down
46 changes: 29 additions & 17 deletions dj_rest_auth/app_settings.py
@@ -1,19 +1,27 @@
from django.conf import settings

from dj_rest_auth.serializers import JWTSerializer as DefaultJWTSerializer
from dj_rest_auth.serializers import JWTSerializerWithExpiration as DefaultJWTSerializerWithExpiration
from dj_rest_auth.serializers import (
JWTSerializerWithExpiration as DefaultJWTSerializerWithExpiration,
)
from dj_rest_auth.serializers import LoginSerializer as DefaultLoginSerializer
from dj_rest_auth.serializers import \
PasswordChangeSerializer as DefaultPasswordChangeSerializer
from dj_rest_auth.serializers import \
PasswordResetConfirmSerializer as DefaultPasswordResetConfirmSerializer
from dj_rest_auth.serializers import \
PasswordResetSerializer as DefaultPasswordResetSerializer
from dj_rest_auth.serializers import (
PasswordChangeSerializer as DefaultPasswordChangeSerializer,
)
from dj_rest_auth.serializers import (
PasswordResetConfirmSerializer as DefaultPasswordResetConfirmSerializer,
)
from dj_rest_auth.serializers import (
PasswordResetSerializer as DefaultPasswordResetSerializer,
)
from dj_rest_auth.serializers import TokenSerializer as DefaultTokenSerializer
from dj_rest_auth.serializers import \
UserDetailsSerializer as DefaultUserDetailsSerializer
from django.conf import settings
from dj_rest_auth.serializers import (
UserDetailsSerializer as DefaultUserDetailsSerializer,
)

from .utils import default_create_token, import_callable


create_token = import_callable(getattr(settings, 'REST_AUTH_TOKEN_CREATOR', default_create_token))

serializers = getattr(settings, 'REST_AUTH_SERIALIZERS', {})
Expand All @@ -28,16 +36,20 @@

LoginSerializer = import_callable(serializers.get('LOGIN_SERIALIZER', DefaultLoginSerializer))

PasswordResetSerializer = import_callable(serializers.get(
'PASSWORD_RESET_SERIALIZER', DefaultPasswordResetSerializer
))
PasswordResetSerializer = import_callable(
serializers.get(
'PASSWORD_RESET_SERIALIZER', DefaultPasswordResetSerializer,
),
)

PasswordResetConfirmSerializer = import_callable(serializers.get(
'PASSWORD_RESET_CONFIRM_SERIALIZER', DefaultPasswordResetConfirmSerializer
))
PasswordResetConfirmSerializer = import_callable(
serializers.get(
'PASSWORD_RESET_CONFIRM_SERIALIZER', DefaultPasswordResetConfirmSerializer,
),
)

PasswordChangeSerializer = import_callable(
serializers.get('PASSWORD_CHANGE_SERIALIZER', DefaultPasswordChangeSerializer)
serializers.get('PASSWORD_CHANGE_SERIALIZER', DefaultPasswordChangeSerializer),
)

JWT_AUTH_COOKIE = getattr(settings, 'JWT_AUTH_COOKIE', None)
Expand Down
12 changes: 6 additions & 6 deletions dj_rest_auth/jwt_auth.py
Expand Up @@ -21,7 +21,7 @@ def set_jwt_access_cookie(response, access_token):
expires=access_token_expiration,
secure=cookie_secure,
httponly=cookie_httponly,
samesite=cookie_samesite
samesite=cookie_samesite,
)


Expand All @@ -42,7 +42,7 @@ def set_jwt_refresh_cookie(response, refresh_token):
secure=cookie_secure,
httponly=cookie_httponly,
samesite=cookie_samesite,
path=refresh_cookie_path
path=refresh_cookie_path,
)


Expand All @@ -63,7 +63,7 @@ def unset_jwt_cookies(response):


class CookieTokenRefreshSerializer(TokenRefreshSerializer):
refresh = serializers.CharField(required=False, help_text="WIll override cookie.")
refresh = serializers.CharField(required=False, help_text='WIll override cookie.')

def extract_refresh_token(self):
request = self.context['request']
Expand All @@ -85,7 +85,7 @@ def get_refresh_view():
""" Returns a Token Refresh CBV without a circular import """
from rest_framework_simplejwt.settings import api_settings as jwt_settings
from rest_framework_simplejwt.views import TokenRefreshView

class RefreshViewWithCookieSupport(TokenRefreshView):
serializer_class = CookieTokenRefreshSerializer

Expand Down Expand Up @@ -115,15 +115,15 @@ def enforce_csrf(self, request):
reason = check.process_view(request, None, (), {})
if reason:
# CSRF failed, bail with explicit error message
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
raise exceptions.PermissionDenied(f'CSRF Failed: {reason}')

def authenticate(self, request):
cookie_name = getattr(settings, 'JWT_AUTH_COOKIE', None)
header = self.get_header(request)
if header is None:
if cookie_name:
raw_token = request.COOKIES.get(cookie_name)
if getattr(settings, 'JWT_AUTH_COOKIE_ENFORCE_CSRF_ON_UNAUTHENTICATED', False): #True at your own risk
if getattr(settings, 'JWT_AUTH_COOKIE_ENFORCE_CSRF_ON_UNAUTHENTICATED', False): #True at your own risk
self.enforce_csrf(request)
elif raw_token is not None and getattr(settings, 'JWT_AUTH_COOKIE_USE_CSRF', False):
self.enforce_csrf(request)
Expand Down
1 change: 1 addition & 0 deletions dj_rest_auth/models.py
@@ -1,4 +1,5 @@
from django.conf import settings
from django.utils.module_loading import import_string


TokenModel = import_string(getattr(settings, 'REST_AUTH_TOKEN_MODEL', 'rest_framework.authtoken.models.Token'))
11 changes: 7 additions & 4 deletions dj_rest_auth/registration/app_settings.py
@@ -1,17 +1,20 @@
from dj_rest_auth.registration.serializers import \
RegisterSerializer as DefaultRegisterSerializer
from django.conf import settings
from rest_framework.permissions import AllowAny

from dj_rest_auth.registration.serializers import (
RegisterSerializer as DefaultRegisterSerializer,
)

from ..utils import import_callable


serializers = getattr(settings, 'REST_AUTH_REGISTER_SERIALIZERS', {})

RegisterSerializer = import_callable(serializers.get('REGISTER_SERIALIZER', DefaultRegisterSerializer))


def register_permission_classes():
permission_classes = [AllowAny, ]
for klass in getattr(settings, 'REST_AUTH_REGISTER_PERMISSION_CLASSES', tuple()):
permission_classes = [AllowAny]
for klass in getattr(settings, 'REST_AUTH_REGISTER_PERMISSION_CLASSES', ()):
permission_classes.append(import_callable(klass))
return tuple(permission_classes)
35 changes: 19 additions & 16 deletions dj_rest_auth/registration/serializers.py
Expand Up @@ -6,6 +6,7 @@
from rest_framework import serializers
from rest_framework.reverse import reverse


try:
from allauth.account import app_settings as allauth_settings
from allauth.account.adapter import get_adapter
Expand All @@ -15,7 +16,7 @@
from allauth.socialaccount.providers.base import AuthProcess
from allauth.utils import email_address_exists, get_username_max_length
except ImportError:
raise ImportError("allauth needs to be added to INSTALLED_APPS.")
raise ImportError('allauth needs to be added to INSTALLED_APPS.')


class SocialAccountSerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -68,11 +69,11 @@ def set_callback_url(self, view, adapter_class):
try:
self.callback_url = reverse(
viewname=adapter_class.provider_id + '_callback',
request=self._get_request()
request=self._get_request(),
)
except NoReverseMatch:
raise serializers.ValidationError(
_("Define callback_url in view")
_('Define callback_url in view'),
)

def validate(self, attrs):
Expand All @@ -81,12 +82,12 @@ def validate(self, attrs):

if not view:
raise serializers.ValidationError(
_("View is not defined, pass it as a context variable")
_('View is not defined, pass it as a context variable'),
)

adapter_class = getattr(view, 'adapter_class', None)
if not adapter_class:
raise serializers.ValidationError(_("Define adapter_class in view"))
raise serializers.ValidationError(_('Define adapter_class in view'))

adapter = adapter_class(request)
app = adapter.get_provider().get_app(request)
Expand All @@ -112,7 +113,7 @@ def validate(self, attrs):

if not self.client_class:
raise serializers.ValidationError(
_("Define client_class in view")
_('Define client_class in view'),
)

provider = adapter.get_provider()
Expand All @@ -127,19 +128,20 @@ def validate(self, attrs):
scope,
scope_delimiter=adapter.scope_delimiter,
headers=adapter.headers,
basic_auth=adapter.basic_auth
basic_auth=adapter.basic_auth,
)
token = client.get_access_token(code)
access_token = token['access_token']
tokens_to_parse = {'access_token': access_token}

# If available we add additional data to the dictionary
for key in ["refresh_token", "id_token", adapter.expires_in_key]:
for key in ['refresh_token', 'id_token', adapter.expires_in_key]:
if key in token:
tokens_to_parse[key] = token[key]
else:
raise serializers.ValidationError(
_("Incorrect input. access_token or code is required."))
_('Incorrect input. access_token or code is required.'),
)

social_token = adapter.parse_token(tokens_to_parse)
social_token.app = app
Expand All @@ -148,7 +150,7 @@ def validate(self, attrs):
login = self.get_social_login(adapter, app, social_token, token)
complete_social_login(request, login)
except HTTPError:
raise serializers.ValidationError(_("Incorrect value"))
raise serializers.ValidationError(_('Incorrect value'))

if not login.is_existing:
# We have an account already signed up in a different flow
Expand All @@ -162,7 +164,7 @@ def validate(self, attrs):
).exists()
if account_exists:
raise serializers.ValidationError(
_("User is already registered with this e-mail address.")
_('User is already registered with this e-mail address.'),
)

login.lookup()
Expand All @@ -173,14 +175,14 @@ def validate(self, attrs):
return attrs


class SocialConnectMixin(object):
class SocialConnectMixin:
def get_social_login(self, *args, **kwargs):
"""
Set the social login process state to connect rather than login
Refer to the implementation of get_social_login in base class and to the
allauth.socialaccount.helpers module complete_social_login function.
"""
social_login = super(SocialConnectMixin, self).get_social_login(*args, **kwargs)
social_login = super().get_social_login(*args, **kwargs)
social_login.state['process'] = AuthProcess.CONNECT
return social_login

Expand All @@ -193,7 +195,7 @@ class RegisterSerializer(serializers.Serializer):
username = serializers.CharField(
max_length=get_username_max_length(),
min_length=allauth_settings.USERNAME_MIN_LENGTH,
required=allauth_settings.USERNAME_REQUIRED
required=allauth_settings.USERNAME_REQUIRED,
)
email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED)
password1 = serializers.CharField(write_only=True)
Expand All @@ -208,7 +210,8 @@ def validate_email(self, email):
if allauth_settings.UNIQUE_EMAIL:
if email and email_address_exists(email):
raise serializers.ValidationError(
_("A user is already registered with this e-mail address."))
_('A user is already registered with this e-mail address.'),
)
return email

def validate_password1(self, password):
Expand All @@ -226,7 +229,7 @@ def get_cleaned_data(self):
return {
'username': self.validated_data.get('username', ''),
'password1': self.validated_data.get('password1', ''),
'email': self.validated_data.get('email', '')
'email': self.validated_data.get('email', ''),
}

def save(self, request):
Expand Down
7 changes: 5 additions & 2 deletions dj_rest_auth/registration/urls.py
Expand Up @@ -3,6 +3,7 @@

from .views import RegisterView, VerifyEmailView


urlpatterns = [
path('', RegisterView.as_view(), name='rest_register'),
path('verify-email/', VerifyEmailView.as_view(), name='rest_verify_email'),
Expand All @@ -18,6 +19,8 @@
# If you don't want to use API on that step, then just use ConfirmEmailView
# view from:
# django-allauth https://github.com/pennersr/django-allauth/blob/master/allauth/account/views.py
re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$', TemplateView.as_view(),
name='account_confirm_email'),
re_path(
r'^account-confirm-email/(?P<key>[-:\w]+)/$', TemplateView.as_view(),
name='account_confirm_email',
),
]

0 comments on commit acf2136

Please sign in to comment.