diff --git a/docs/api_endpoints.rst b/docs/api_endpoints.rst index 48e475e..1f9660f 100644 --- a/docs/api_endpoints.rst +++ b/docs/api_endpoints.rst @@ -7,6 +7,7 @@ Basic - /rest-auth/login/ (POST) - username (string) + - email (string) - password (string) @@ -55,16 +56,6 @@ Registration - password2 - email - .. note:: This endpoint is based on ``allauth.account.views.SignupView`` and uses the same form as in this view. To override fields you have to create custom Signup Form and define it in django settings: - - .. code-block:: python - - ACCOUNT_FORMS = { - 'signup': 'path.to.custom.SignupForm' - } - - See allauth documentation for more details. - - /rest-auth/registration/verify-email/ (POST) - key diff --git a/docs/configuration.rst b/docs/configuration.rst index 282f326..079c710 100644 --- a/docs/configuration.rst +++ b/docs/configuration.rst @@ -29,6 +29,14 @@ Configuration ... } +- **REST_AUTH_REGISTRATION_SERIALIZERS** + + You can define your custom serializers for registration endpoint. + Possible key values: + + - REGISTER_SERIALIZER - serializer class in ``rest_auth.register.views.RegisterView``, default value ``rest_auth.register.serializers.RegisterSerializer`` + + - **REST_SESSION_LOGIN** - Enable session login in Login API view (default: True) diff --git a/rest_auth/registration/app_settings.py b/rest_auth/registration/app_settings.py new file mode 100644 index 0000000..227b45b --- /dev/null +++ b/rest_auth/registration/app_settings.py @@ -0,0 +1,11 @@ +from django.conf import settings + +from 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)) diff --git a/rest_auth/registration/serializers.py b/rest_auth/registration/serializers.py index 5f5efd6..b27d7bd 100644 --- a/rest_auth/registration/serializers.py +++ b/rest_auth/registration/serializers.py @@ -1,6 +1,15 @@ from django.http import HttpRequest from django.conf import settings +try: + from allauth.account import app_settings as allauth_settings + from allauth.utils import (email_address_exists, + get_username_max_length) + from allauth.account.adapter import get_adapter + from allauth.account.utils import setup_user_email +except ImportError: + raise ImportError('allauth needs to be added to INSTALLED_APPS.') + from rest_framework import serializers from requests.exceptions import HTTPError # Import is needed only if we are using social login, in which @@ -109,3 +118,57 @@ class SocialLoginSerializer(serializers.Serializer): attrs['user'] = login.account.user return attrs + + +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 + ) + email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED) + password1 = serializers.CharField(required=True, write_only=True) + password2 = serializers.CharField(required=True, write_only=True) + + def validate_username(self, username): + username = get_adapter().clean_username(username) + return username + + def validate_email(self, email): + email = get_adapter().clean_email(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.") + return email + + def validate_password1(self, password): + return get_adapter().clean_password(password) + + def validate(self, data): + if data['password1'] != data['password2']: + raise serializers.ValidationError("The two password fields didn't match.") + return data + + def custom_signup(self, request, user): + pass + + def get_cleaned_data(self): + return { + 'username': self.validated_data.get('username', ''), + 'password1': self.validated_data.get('password1', ''), + 'email': self.validated_data.get('email', '') + } + + def save(self, request): + adapter = get_adapter() + user = adapter.new_user(request) + self.cleaned_data = self.get_cleaned_data() + adapter.save_user(request, user, self) + self.custom_signup(request, user) + setup_user_email(request, user, []) + return user + + +class VerifyEmailSerializer(serializers.Serializer): + key = serializers.CharField() diff --git a/rest_auth/registration/views.py b/rest_auth/registration/views.py index e700706..81fd951 100644 --- a/rest_auth/registration/views.py +++ b/rest_auth/registration/views.py @@ -1,77 +1,42 @@ -from django.http import HttpRequest from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import AllowAny +from rest_framework.generics import CreateAPIView from rest_framework import status from rest_framework.authtoken.models import Token +from rest_framework.exceptions import MethodNotAllowed -from allauth.account.views import SignupView, ConfirmEmailView +from allauth.account.views import ConfirmEmailView from allauth.account.utils import complete_signup -from allauth.account import app_settings +from allauth.account import app_settings as allauth_settings from rest_auth.app_settings import TokenSerializer -from rest_auth.registration.serializers import SocialLoginSerializer +from rest_auth.registration.serializers import (SocialLoginSerializer, + VerifyEmailSerializer) +from .app_settings import RegisterSerializer from rest_auth.views import LoginView -class RegisterView(APIView, SignupView): - """ - Accepts the credentials and creates a new user - if user does not exist already - Return the REST Token if the credentials are valid and authenticated. - Calls allauth complete_signup method +class RegisterView(CreateAPIView): + serializer_class = RegisterSerializer + permission_classes = (AllowAny, ) - Accept the following POST parameters: username, email, password - Return the REST Framework Token Object's key. - """ + def create(self, request, *args, **kwargs): + serializer = self.get_serializer(data=request.data) + serializer.is_valid(raise_exception=True) + user = self.perform_create(serializer) + headers = self.get_success_headers(serializer.data) + return Response(TokenSerializer(user.auth_token).data, + status=status.HTTP_201_CREATED, + headers=headers) - permission_classes = (AllowAny,) - allowed_methods = ('POST', 'OPTIONS', 'HEAD') - token_model = Token - serializer_class = TokenSerializer - - def get(self, *args, **kwargs): - return Response({}, status=status.HTTP_405_METHOD_NOT_ALLOWED) - - def put(self, *args, **kwargs): - return Response({}, status=status.HTTP_405_METHOD_NOT_ALLOWED) - - def form_valid(self, form): - self.user = form.save(self.request) - self.token, created = self.token_model.objects.get_or_create( - user=self.user - ) - if isinstance(self.request, HttpRequest): - request = self.request - else: - request = self.request._request - return complete_signup(request, self.user, - app_settings.EMAIL_VERIFICATION, - self.get_success_url()) - - def get_form_kwargs(self, *args, **kwargs): - kwargs = super(RegisterView, self).get_form_kwargs(*args, **kwargs) - kwargs['data'] = self.request.data - return kwargs - - def post(self, request, *args, **kwargs): - self.initial = {} - form_class = self.get_form_class() - self.form = self.get_form(form_class) - if self.form.is_valid(): - self.form_valid(self.form) - return self.get_response() - else: - return self.get_response_with_errors() - - def get_response(self): - # serializer = self.user_serializer_class(instance=self.user) - serializer = self.serializer_class(instance=self.token, - context={'request': self.request}) - return Response(serializer.data, status=status.HTTP_201_CREATED) - - def get_response_with_errors(self): - return Response(self.form.errors, status=status.HTTP_400_BAD_REQUEST) + def perform_create(self, serializer): + user = serializer.save(self.request) + Token.objects.get_or_create(user=user) + complete_signup(self.request._request, user, + allauth_settings.EMAIL_VERIFICATION, + None) + return user class VerifyEmailView(APIView, ConfirmEmailView): @@ -80,10 +45,12 @@ class VerifyEmailView(APIView, ConfirmEmailView): allowed_methods = ('POST', 'OPTIONS', 'HEAD') def get(self, *args, **kwargs): - return Response({}, status=status.HTTP_405_METHOD_NOT_ALLOWED) + raise MethodNotAllowed('GET') def post(self, request, *args, **kwargs): - self.kwargs['key'] = self.request.data.get('key', '') + serializer = VerifyEmailSerializer(data=request.data) + serializer.is_valid(raise_exception=True) + self.kwargs['key'] = serializer.validated_data['key'] confirmation = self.get_object() confirmation.confirm(self.request) return Response({'message': 'ok'}, status=status.HTTP_200_OK) diff --git a/rest_auth/serializers.py b/rest_auth/serializers.py index 657a221..80fb254 100644 --- a/rest_auth/serializers.py +++ b/rest_auth/serializers.py @@ -19,43 +19,73 @@ class LoginSerializer(serializers.Serializer): email = serializers.EmailField(required=False, allow_blank=True) password = serializers.CharField(style={'input_type': 'password'}) + def _validate_email(self, email, password): + user = None + + if email and password: + user = authenticate(email=email, password=password) + else: + msg = _('Must include "email" and "password".') + raise exceptions.ValidationError(msg) + + return user + + def _validate_username(self, username, password): + user = None + + if username and password: + user = authenticate(username=username, password=password) + else: + msg = _('Must include "username" and "password".') + raise exceptions.ValidationError(msg) + + return user + + def _validate_username_email(self, username, email, password): + user = None + + if email and password: + user = authenticate(email=email, password=password) + elif username and password: + user = authenticate(username=username, password=password) + else: + msg = _('Must include either "username" or "email" and "password".') + raise exceptions.ValidationError(msg) + + return user + def validate(self, attrs): username = attrs.get('username') email = attrs.get('email') password = attrs.get('password') + user = None + if 'allauth' in settings.INSTALLED_APPS: from allauth.account import app_settings + # Authentication through email if app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.EMAIL: - if email and password: - user = authenticate(email=email, password=password) - else: - msg = _('Must include "email" and "password".') - raise exceptions.ValidationError(msg) + user = self._validate_email(email, password) + # Authentication through username - elif app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.USERNAME: - if username and password: - user = authenticate(username=username, password=password) - else: - msg = _('Must include "username" and "password".') - raise exceptions.ValidationError(msg) + if app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.USERNAME: + user = self._validate_username(username, password) + # Authentication through either username or email else: - if email and password: - user = authenticate(email=email, password=password) - elif username and password: - user = authenticate(username=username, password=password) - else: - msg = _('Must include either "username" or "email" and "password".') - raise exceptions.ValidationError(msg) - - elif username and password: - user = authenticate(username=username, password=password) + user = self._validate_username_email(username, email, password) else: - msg = _('Must include "username" and "password".') - raise exceptions.ValidationError(msg) + # Authentication without using allauth + if email: + try: + username = UserModel.objects.get(email__iexact=email).username + except UserModel.DoesNotExist: + pass + + if username: + user = self._validate_username_email(username, '', password) # Did we get back an active user? if user: diff --git a/rest_auth/tests/test_api.py b/rest_auth/tests/test_api.py index bb15e01..222b3a7 100644 --- a/rest_auth/tests/test_api.py +++ b/rest_auth/tests/test_api.py @@ -2,6 +2,7 @@ from django.core.urlresolvers import reverse from django.test import TestCase from django.contrib.auth import get_user_model from django.core import mail +from django.conf import settings from django.test.utils import override_settings from django.utils.encoding import force_text @@ -90,6 +91,51 @@ class APITestCase1(TestCase, BaseAPITestCase): # test empty payload self.post(self.login_url, data={}, status_code=400) + def test_login_by_email(self): + # starting test without allauth app + settings.INSTALLED_APPS.remove('allauth') + + payload = { + "email": self.EMAIL.lower(), + "password": self.PASS + } + # there is no users in db so it should throw error (400) + self.post(self.login_url, data=payload, status_code=400) + + self.post(self.password_change_url, status_code=403) + + # create user + user = get_user_model().objects.create_user(self.USERNAME, self.EMAIL, self.PASS) + + # test auth by email + self.post(self.login_url, data=payload, status_code=200) + self.assertEqual('key' in self.response.json.keys(), True) + self.token = self.response.json['key'] + + # test auth by email in different case + payload = { + "email": self.EMAIL.upper(), + "password": self.PASS + } + self.post(self.login_url, data=payload, status_code=200) + self.assertEqual('key' in self.response.json.keys(), True) + self.token = self.response.json['key'] + + # test inactive user + user.is_active = False + user.save() + self.post(self.login_url, data=payload, status_code=400) + + # test wrong email/password + payload = { + "email": 't' + self.EMAIL, + "password": self.PASS + } + self.post(self.login_url, data=payload, status_code=400) + + # test empty payload + self.post(self.login_url, data={}, status_code=400) + def test_password_change(self): login_payload = { "username": self.USERNAME, @@ -272,6 +318,12 @@ class APITestCase1(TestCase, BaseAPITestCase): self._login() self._logout() + def test_registration_with_invalid_password(self): + data = self.REGISTRATION_DATA.copy() + data['password2'] = 'foobar' + + self.post(self.register_url, data=data, status_code=400) + @override_settings( ACCOUNT_EMAIL_VERIFICATION='mandatory', ACCOUNT_EMAIL_REQUIRED=True diff --git a/rest_auth/tests/test_social.py b/rest_auth/tests/test_social.py index 0bb10f5..19509ef 100644 --- a/rest_auth/tests/test_social.py +++ b/rest_auth/tests/test_social.py @@ -99,7 +99,6 @@ class TestSocialAuth(TestCase, BaseAPITestCase): # test empty payload self.post(self.register_url, data={}, status_code=400) - self.post( self.register_url, data=self.REGISTRATION_DATA,