How to restrict AuthenticateCallbackView in django-microsoft-auth only to registered accounts?

Question:

I am using django-microsoft-auth in my Django project. I am trying to restrict this option only to registered users so only people who have already registered themselves are allowed to use Log in with Microsoft button.

I found in AuthenticateCallbackView method called _authenticate. Code below:

def _authenticate(self, code):
if "error" not in self.context["message"]:
    if code is None:
        self.context["message"] = {"error": "missing_code"}
    else:
        # authenticate user using Microsoft code
        user = authenticate(self.request, code=code)
        if user is None:
            # this should not fail at this point except for network
            # error while retrieving profile or database error
            # adding new user
            self.context["message"] = {"error": "login_failed"}
        else:
            login(self.request, user)

I am wondering how can I restrict authentication only to those who have accounts. In case someone doesn’t have an account it would send a message: Please register your account first.

Asked By: Adrian

||

Answers:

You can extend MicrosoftAuthenticationBackend to override authenticate method. Don’t forget to upload your settings to use your own authentication backend.

Try something like below:

class MyAuthenticationBackend(MicrosoftAuthenticationBackend):
    def authenticate(self, request):
        email = request.POST.get("email") # replace this username or any other attribute used for auth
        if User.objects.filter(email=email).exists():
            return super().authenticate(request)
        return None
Answered By: May.D
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.