Django Python Social Auth only allow certain users to sign in
<p>I want only users from a @companyname.net email <em>or</em> from a list of email addresses to be able to sign in with Python Social Auth through google+. How would I accomplish this?</p>

<pre><code>SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS = ['companyname.net']
</code></pre>

<p>is what I currently have in settings.py, but that only allows @companyname.net-ers to sign in.</p>

<p>One way to solve this is overriding python-social-auth pipeline.</p>

<p>You can override create_user with something like:</p>

<pre><code>def create_user(strategy, details, user=None, *args, **kwargs):
    if user:
        return {'is_new': False}

    allowed_emails = get_list_of_emails()

    fields = dict((name, kwargs.get(name, details.get(name)))
                  for name in strategy.setting('USER_FIELDS', USER_FIELDS))
    if not fields:
        return

    if fields[email] in allowed_emails:        
        return {
            'is_new': True,
            'user': strategy.create_user(**fields)
        }

    return
</code></pre>

<p>This method <code>get_list_of_emails()</code> is to be used as a way to load the emails from file ou from database. It needs to return a list of emails.</p>

<p>Then, in the SOCIAL_AUTH_PIPELINE in your settings you replace the create_user to your custom method:</p>

<pre><code>SOCIAL_AUTH_PIPELINE = (
    'social.pipeline.social_auth.social_details',
    'social.pipeline.social_auth.social_uid',
    'social.pipeline.social_auth.auth_allowed',
    'social.pipeline.social_auth.social_user',
    'social.pipeline.user.get_username',
    'path.to.my.method.create_user',
    'social.pipeline.social_auth.associate_user',
    'social.pipeline.social_auth.load_extra_data',
    'social.pipeline.user.user_details',
)
</code></pre>

<p>This way you can keep the domais whitelist, and then store the emails you want somewhere where you can load them with the method <code>get_list_of_emails()</code></p>

<p>more on the <a href="https://python-social-auth.readthedocs.io/en/latest/pipeline.html#authentication-pipeline" rel="nofollow">docs</a></p>

python django python-social-auth