How can I use Django OAuth Toolkit with Python Social Auth?

后端 未结 4 2043
小蘑菇
小蘑菇 2020-11-28 01:05

I\'m building an API using Django Rest Framework. Later this API is supposed to be consumed by iOS and Android devices. I want to allow my users to sign-up with oauth2-provi

4条回答
  •  萌比男神i
    2020-11-28 01:32

    I solved it by using your A. option.

    What I do is registering users that use a third party to sign up by their third party access token.

    url(r'^register-by-token/(?P[^/]+)/$',
        views.register_by_access_token),
    

    This way, I can issue a GET request like this one:

    GET http://localhost:8000/register-by-token/facebook/?access_token=123456

    And register_by_access_token gets called. request.backend.do_auth will query the provider for the user info from the token and magically register a user account with the info or sign in the user if he's already registered.

    Then, I create a token manually and return it as JSON for letting the client query my API.

    from oauthlib.common import generate_token
    ...
    @psa('social:complete')
    def register_by_access_token(request, backend):
        # This view expects an access_token GET parameter, if it's needed,
        # request.backend and request.strategy will be loaded with the current
        # backend and strategy.
        third_party_token = request.GET.get('access_token')
        user = request.backend.do_auth(third_party_token)
    
        if user:
            login(request, user)
    
            # We get our app!   
            app = Application.objects.get(name="myapp")
    
            # We delete the old token
            try:
                old = AccessToken.objects.get(user=user, application=app)
            except:
                pass
            else:
                old.delete()
    
            # We create a new one
            my_token = generate_token()
    
            # We create the access token 
            # (we could create a refresh token too the same way) 
            AccessToken.objects.create(user=user,
                                       application=app,
                                       expires=now() + timedelta(days=365),
                                       token=my_token)
    
            return "OK" # you can return your token as JSON here
    
        else:
            return "ERROR"
    

    I'm just not sure about the way I generate the token, is this good practice? Well, in the mean time, it works!!

提交回复
热议问题