I have an Android application, interacting with a Django API, which also hosts a website.
On the Django website, the user logs in with Google+/Facebook/Twitter (using django-social-auth) and all subsequent requests contain a user object, which identifies the user. I assume this is done via cookies.
I want to implement the same functionality in my Android application. The application logs the user in with Google+/Facebook/Twitter, then sends the access token to the API, which logs the user in.
What do I need to pass back to the Android application, and then back to the API with every request in order to have Django recognize the logged in user?
I found a solution for this. After logging the user in in Django
you return request.session.session_key
. You store this in the application and whenever you need to make an authenticated request you pass it back as a POST
parameter.
In Django
, you can create a decorator as such to automatically transform this into a User
object in the request:
def extract_user(function):
def handle_extraction(request, *args, **kwargs):
# Try to store the request.user if a session id is specified.
if request.POST.get('SESSION-ID'):
request.user = get_user_from_request_w_session_id(request)
# Execute the function.
return function(request, *args, **kwargs)
return handle_extraction
Every function that expects an authenticated user is now annotated like this:
@extract_user
def my_function(request):
...
If you want to use @login_required
you can do that as well, just make sure to have the annotation AFTER @extract_user
, as such:
@extract_user
@login_required
def my_function(request):
...