pythondjangodjango-socialauthdjango-1.11

Django: Intervention when raising errors when creating User via social authentication


I'm setting up social authentication with the package social-auth-app-django. I have the below ValueError raised when attempting to create a user when an email isn't supplied.

users.py

    if not email:
        message = "Ooops, it doesn\'t look like an email was specified. If you are signing in via one of your social media account, please ensure there is an email address associated to your account."
        raise ValueError(message)

It wasn't really necessary originally as I would handle the form validation on the front end with standard form validation. However, when integrating social sign-ins this causes an issue. In development this is great - but essentially at this stage I would like to fling the error back to an errors template which says that they must supply an email address. I believe on platforms, such as Twitter, a user can initially register without an email address associated to the account. That's where I spotted this conflict. Essentially, social-auth-app-django isn't throwing an error before this - so how at this point, do I send the user back to a specified template which I can build to handle such errors by passing them back via the context?

Looking and looking through the documentation, I can't see anything I would be confident in running with...any advise would be greatly appreciated!


Solution

  • The python-social-auth module supports a pipeline - so defining a method in the end of your SOCIAL_AUTH_PIPELINE in settings.py and then implementing it in pipeline.py would give you a way to define the desired behavior in case, when your users have no email associated with their social users:

    SOCIAL_AUTH_PIPELINE = (
        # any other pipeline handlers ...                                            
        'custom.signup.pipeline.prevent_without_email'
    )
    

    Then in your custom/signup/pipeline.py you'll need to implement the actual partial for prevent_without_email - You can see it here in more detail https://python-social-auth.readthedocs.io/en/latest/pipeline.html

    If you need a specific handler, you can use Django signals - create a signal in signals.py, emit it in pipeline.py and let the handler in callbacks.py to handle it, when an email is not specified.