How to authenticate user with Django AllAuth using either email or username in one field?












0















Is there any way in Django AllAuth with configuration ACCOUNT_AUTHENTICATION_METHOD = 'username_email' to send text from input "USERNAME OR EMAIL" and authenticate it automatically? I don't mean frontend logic, just AllAuth authentication. So it would get a JSON with fields for instance "username_email" : "myusername", "password" : "password" or "username_email" : "myemail@gmail.com", "password" : "password" and it would automatically check whether a user with nick or email myusername exists and his password is password. In the second case it would also check whether a user with nick or email myemail@gmail.com exists and his password is password. If so the user would be authenticated. Any ideas?










share|improve this question



























    0















    Is there any way in Django AllAuth with configuration ACCOUNT_AUTHENTICATION_METHOD = 'username_email' to send text from input "USERNAME OR EMAIL" and authenticate it automatically? I don't mean frontend logic, just AllAuth authentication. So it would get a JSON with fields for instance "username_email" : "myusername", "password" : "password" or "username_email" : "myemail@gmail.com", "password" : "password" and it would automatically check whether a user with nick or email myusername exists and his password is password. In the second case it would also check whether a user with nick or email myemail@gmail.com exists and his password is password. If so the user would be authenticated. Any ideas?










    share|improve this question

























      0












      0








      0








      Is there any way in Django AllAuth with configuration ACCOUNT_AUTHENTICATION_METHOD = 'username_email' to send text from input "USERNAME OR EMAIL" and authenticate it automatically? I don't mean frontend logic, just AllAuth authentication. So it would get a JSON with fields for instance "username_email" : "myusername", "password" : "password" or "username_email" : "myemail@gmail.com", "password" : "password" and it would automatically check whether a user with nick or email myusername exists and his password is password. In the second case it would also check whether a user with nick or email myemail@gmail.com exists and his password is password. If so the user would be authenticated. Any ideas?










      share|improve this question














      Is there any way in Django AllAuth with configuration ACCOUNT_AUTHENTICATION_METHOD = 'username_email' to send text from input "USERNAME OR EMAIL" and authenticate it automatically? I don't mean frontend logic, just AllAuth authentication. So it would get a JSON with fields for instance "username_email" : "myusername", "password" : "password" or "username_email" : "myemail@gmail.com", "password" : "password" and it would automatically check whether a user with nick or email myusername exists and his password is password. In the second case it would also check whether a user with nick or email myemail@gmail.com exists and his password is password. If so the user would be authenticated. Any ideas?







      python django django-models django-rest-framework django-allauth






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 25 '18 at 3:25









      thedboghthedbogh

      9510




      9510
























          1 Answer
          1






          active

          oldest

          votes


















          0














          You need a custom authentication backend doc



          Something like this:



          class MyAuthenticationBackend:

          def authenticate(self, email_username=None, password=None):
          if "@" in email_username:
          try:
          user = User.objects.get(email=email_username)
          except User.DoesNotExist:
          return None
          else:
          try:
          user = User.objects.get(username=email_username)
          except User.DoesNotExist:
          return None
          if getattr(user, 'is_active', False) and user.check_password(password):
          return user
          return None

          def get_user(self, user_id):
          try:
          return User.objects.get(pk=user_id)
          except User.DoesNotExist:
          return None


          Then in your form view:



          from django.contrib.auth import authenticate
          from django.contrib.auth import login
          from django.shortcuts import redirect

          class LoginView(FormView):
          template_name = 'my-auth/login.html'
          form_class = LoginForm

          def form_valid(self, form):
          data = form.cleaned_data
          user = authenticate(email_username=data['email_username'], password=data['password'])
          if user is None:
          form.add_error(None, _('Wrong email/username'))
          return self.form_invalid(form)
          login(self.request, user)
          return redirect('somewhere')





          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53464381%2fhow-to-authenticate-user-with-django-allauth-using-either-email-or-username-in-o%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            You need a custom authentication backend doc



            Something like this:



            class MyAuthenticationBackend:

            def authenticate(self, email_username=None, password=None):
            if "@" in email_username:
            try:
            user = User.objects.get(email=email_username)
            except User.DoesNotExist:
            return None
            else:
            try:
            user = User.objects.get(username=email_username)
            except User.DoesNotExist:
            return None
            if getattr(user, 'is_active', False) and user.check_password(password):
            return user
            return None

            def get_user(self, user_id):
            try:
            return User.objects.get(pk=user_id)
            except User.DoesNotExist:
            return None


            Then in your form view:



            from django.contrib.auth import authenticate
            from django.contrib.auth import login
            from django.shortcuts import redirect

            class LoginView(FormView):
            template_name = 'my-auth/login.html'
            form_class = LoginForm

            def form_valid(self, form):
            data = form.cleaned_data
            user = authenticate(email_username=data['email_username'], password=data['password'])
            if user is None:
            form.add_error(None, _('Wrong email/username'))
            return self.form_invalid(form)
            login(self.request, user)
            return redirect('somewhere')





            share|improve this answer






























              0














              You need a custom authentication backend doc



              Something like this:



              class MyAuthenticationBackend:

              def authenticate(self, email_username=None, password=None):
              if "@" in email_username:
              try:
              user = User.objects.get(email=email_username)
              except User.DoesNotExist:
              return None
              else:
              try:
              user = User.objects.get(username=email_username)
              except User.DoesNotExist:
              return None
              if getattr(user, 'is_active', False) and user.check_password(password):
              return user
              return None

              def get_user(self, user_id):
              try:
              return User.objects.get(pk=user_id)
              except User.DoesNotExist:
              return None


              Then in your form view:



              from django.contrib.auth import authenticate
              from django.contrib.auth import login
              from django.shortcuts import redirect

              class LoginView(FormView):
              template_name = 'my-auth/login.html'
              form_class = LoginForm

              def form_valid(self, form):
              data = form.cleaned_data
              user = authenticate(email_username=data['email_username'], password=data['password'])
              if user is None:
              form.add_error(None, _('Wrong email/username'))
              return self.form_invalid(form)
              login(self.request, user)
              return redirect('somewhere')





              share|improve this answer




























                0












                0








                0







                You need a custom authentication backend doc



                Something like this:



                class MyAuthenticationBackend:

                def authenticate(self, email_username=None, password=None):
                if "@" in email_username:
                try:
                user = User.objects.get(email=email_username)
                except User.DoesNotExist:
                return None
                else:
                try:
                user = User.objects.get(username=email_username)
                except User.DoesNotExist:
                return None
                if getattr(user, 'is_active', False) and user.check_password(password):
                return user
                return None

                def get_user(self, user_id):
                try:
                return User.objects.get(pk=user_id)
                except User.DoesNotExist:
                return None


                Then in your form view:



                from django.contrib.auth import authenticate
                from django.contrib.auth import login
                from django.shortcuts import redirect

                class LoginView(FormView):
                template_name = 'my-auth/login.html'
                form_class = LoginForm

                def form_valid(self, form):
                data = form.cleaned_data
                user = authenticate(email_username=data['email_username'], password=data['password'])
                if user is None:
                form.add_error(None, _('Wrong email/username'))
                return self.form_invalid(form)
                login(self.request, user)
                return redirect('somewhere')





                share|improve this answer















                You need a custom authentication backend doc



                Something like this:



                class MyAuthenticationBackend:

                def authenticate(self, email_username=None, password=None):
                if "@" in email_username:
                try:
                user = User.objects.get(email=email_username)
                except User.DoesNotExist:
                return None
                else:
                try:
                user = User.objects.get(username=email_username)
                except User.DoesNotExist:
                return None
                if getattr(user, 'is_active', False) and user.check_password(password):
                return user
                return None

                def get_user(self, user_id):
                try:
                return User.objects.get(pk=user_id)
                except User.DoesNotExist:
                return None


                Then in your form view:



                from django.contrib.auth import authenticate
                from django.contrib.auth import login
                from django.shortcuts import redirect

                class LoginView(FormView):
                template_name = 'my-auth/login.html'
                form_class = LoginForm

                def form_valid(self, form):
                data = form.cleaned_data
                user = authenticate(email_username=data['email_username'], password=data['password'])
                if user is None:
                form.add_error(None, _('Wrong email/username'))
                return self.form_invalid(form)
                login(self.request, user)
                return redirect('somewhere')






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 25 '18 at 9:32

























                answered Nov 25 '18 at 9:12









                GoranGoran

                2,05492243




                2,05492243
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53464381%2fhow-to-authenticate-user-with-django-allauth-using-either-email-or-username-in-o%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Ottavio Pratesi

                    Tricia Helfer

                    15 giugno