Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create new user and new django allauth social account when given access token over api?

I have a mobile app that allows users to sign up via Facebook. Once I receive the access token from FB, I send it to the Django backend.

But then what?

Is there a method inside of django-allauth that I can feed the access token to to have it create the new user/social account?

Or do I need to do it all manually?

like image 790
KrisF Avatar asked May 05 '13 05:05

KrisF


Video Answer


2 Answers

I always seem to figure out the answers right after I post the question. In any case, the following is a custom method on UserResource (tastypie api using ApiKeyAuthentication). Most of it was taken from the login_by_token method in allauth.socialaccount.providers.facebook.views.

I won't select my answer as correct for a while in case anyone posts a better answer.

def facebook_login(self, request, **kwargs):
    self.method_check(request, allowed=['post'])

    data = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))

    access_token = data.get('access_token', '')

    from allauth.socialaccount import providers
    from allauth.socialaccount.models import SocialLogin, SocialToken, SocialApp
    from allauth.socialaccount.providers.facebook.views import fb_complete_login
    from allauth.socialaccount.helpers import complete_social_login
    try:
        app = SocialApp.objects.get(provider="facebook")
        token = SocialToken(app=app,
                            token=access_token)
        login = fb_complete_login(app, token)
        login.token = token
        login.state = SocialLogin.state_from_request(request)
        ret = complete_social_login(request, login)

        #if we get here we've succeeded
        return self.create_response(request, {
                'success': True,
                'username': request.user.username,
                'user_id': request.user.pk,
                'api_key': request.user.api_key.key,
                } ) 
    except:
        # FIXME: Catch only what is needed
        return self.create_response(request, {
                'success': False,
                'reason': "Bad Access Token",
                }, HttpForbidden ) 
like image 68
KrisF Avatar answered Oct 25 '22 17:10

KrisF


Modern readers (2017) may want to look at django-rest-auth, which builds on allauth but is built with single page apps in mind:

http://django-rest-auth.readthedocs.io/en/latest/introduction.html

like image 25
Doug Bradshaw Avatar answered Oct 25 '22 17:10

Doug Bradshaw