Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Python social auth to only get tokens

I am using the fantastic Python social auth with Django.
However, at the moment, everytime the process is invoked, a new user is created. I only need the tokens (access_token and refresh_token) from the process. How can this be achieved? Via some sort of pipeline?

This is my pipeline.py code at the moment (abbreviated):

def get_token(backend, user, response, *args, **kwargs):

    # get token from the oauth2 flow
    social = user.social_auth.get(provider='google-oauth2')
    access_token = social.extra_data['access_token']
    refresh_token = social.extra_data.get('refresh_token')

And the corresponding settings.py file:

# set django session
SESSION_EXPIRE_AT_BROWSER_CLOSE = True

# psa settings
SOCIAL_AUTH_URL_NAMESPACE = 'social'

# see http://psa.matiasaguirre.net/docs/configuration/settings.html
SOCIAL_AUTH_UUID_LENGTH = 32

AUTHENTICATION_BACKENDS = (
    #'social.backends.facebook.FacebookOAuth2',
    'social.backends.google.GoogleOAuth2',
    #'social.backends.twitter.TwitterOAuth',
    'django.contrib.auth.backends.ModelBackend',
)

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',
    'social.pipeline.user.create_user',
    'social.pipeline.social_auth.associate_user',
    'social.pipeline.social_auth.load_extra_data',
    'social.pipeline.user.user_details',
    'youtube.pipeline.get_token',
)
like image 910
Jan Avatar asked Apr 28 '16 18:04

Jan


1 Answers

Yes, it's all in the pipeline. If you take a look at what you already have, you'll even see the social.pipeline.user.create_user step.

From the documentation:

# Create a user account if we haven't found one yet.
'social.pipeline.user.create_user',

(source for that function)

Replace this (and all of the following steps if you don't need them) with whatever it is that you are trying to achieve.

def get_token(backend, uid, *args, **kwargs):
    # get token from the oauth2 flow
    provider = backend.name
    social = backend.strategy.storage.user.get_social_auth(provider, uid)
    access_token = social.extra_data['access_token']
    refresh_token = social.extra_data.get('refresh_token')

The modified method should work even if no user exists/is created.

like image 155
Anonymous Avatar answered Oct 23 '22 14:10

Anonymous