Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check that user already authenticated from tastypie?

When user authenticates in Django, how do I check that from tastypie?

Once user logs on, the view includes some JS that pulls data from API, which is backed by tastypie.

I have basic authentication/djangoauthorisation set up on my resources, so the browser pops up http auth window. Is there any way to avoid this?

My idea so far is to extend BasicAuthentication so that it first checks session data and when it doesn't find it, it falls back to http auth? AFAIK AJAX calls include session cookies, so this in theory should work? Has anybody done something similar?

like image 311
rytis Avatar asked Sep 09 '11 14:09

rytis


2 Answers

I have this solution so far:

class MyBasicAuthentication(BasicAuthentication):
    def __init__(self, *args, **kwargs):
        super(MyBasicAuthentication, self).__init__(*args, **kwargs)

    def is_authenticated(self, request, **kwargs):
        from django.contrib.sessions.models import Session
        if 'sessionid' in request.COOKIES:
            s = Session.objects.get(pk=request.COOKIES['sessionid'])
            if '_auth_user_id' in s.get_decoded():
                u = User.objects.get(id=s.get_decoded()['_auth_user_id'])
                request.user = u
                return True
        return super(MyBasicAuthentication, self).is_authenticated(request, **kwargs)

which seems to do what I want. If user is logged on, then session contains _auth_user_id, if not, the key is missing.

Anyone can think of any problems this approach may cause?

like image 152
rytis Avatar answered Oct 11 '22 12:10

rytis


You may want to check out this ticket on tastypie's GitHub:

https://github.com/toastdriven/django-tastypie/issues/197

The author suggests a very clean approach to authenticate the call with both the session and the API key methods.

There goes the snippet:

class ApiKeyPlusWebAuthentication(ApiKeyAuthentication):
def is_authenticated(self, request, **kwargs):
    if request.user.is_authenticated():
        return True

    return super(ApiKeyPlusWebAuthentication, self).is_authenticated(request, **kwargs)

def get_identifier(self, request):
    if request.user.is_authenticated():
        return request.user.username
    else:
        return super(ApiKeyPlusWebAuthentication, self).get_identifier(request)
like image 36
ulysses Avatar answered Oct 11 '22 10:10

ulysses