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?
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 )
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With