What I have done is:
Define a class that inherits from SocialAuthExceptionMiddleware
Implement the method process_exception
,
Add the implemented class to MIDDLEWARE
list on settings.py
.
In middleware.py
, which should be in your apps's directory, i.e., same directory of your views.py
file associated with your app, define the following class:
from django.shortcuts import redirect
from django.urls import reverse
from social_core.exceptions import AuthAlreadyAssociated
class FacebookAuthAlreadyAssociatedMiddleware(SocialAuthExceptionMiddleware):
"""Redirect users to desired-url when AuthAlreadyAssociated exception occurs."""
def process_exception(self, request, exception):
if isinstance(exception, AuthAlreadyAssociated):
if request.backend.name == "facebook":
message = "This facebook account is already in use."
if message in str(exception):
# Add logic if required
# User is redirected to any url you want
# in this case to "app_name:url_name"
return redirect(reverse("app_name:url_name"))
In settings.py
, add the implemented class to the MIDDLEWARE
list:
MIDDLEWARE = [
# Some Django middlewares
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.locale.LocaleMiddleware",
"django.middleware.common.CommonMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"social_django.middleware.SocialAuthExceptionMiddleware",
# the middleware you just implemented
"app_name.middleware.FacebookAuthAlreadyAssociatedMiddleware",
]
This solved my problem, and I was able to handle the flow of control when the AuthAlreadyAssociated
exception was raised.