AuthAlreadyAssociated Exception in Django Social Auth

后端 未结 5 1261
渐次进展
渐次进展 2020-12-30 04:37

After I create a user using say Facebook(let\'s say fbuser) or Google(googleuser). If I create another user through the normal django admin(normaluser), and try logging aga

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-30 05:25

    What I have done is:

    1. Define a class that inherits from SocialAuthExceptionMiddleware

    2. Implement the method process_exception,

    3. 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.

提交回复
热议问题