Coder Social home page Coder Social logo

Comments (7)

alanjds avatar alanjds commented on May 22, 2024

Maybe this is what we need: https://github.com/jpulgarin/django-tokenapi

I'll just post a request at that repo to allow to set timeout per-token instead of using a django setting

from django-rest-framework.

machineghost avatar machineghost commented on May 22, 2024

First off thanks for the link alanjds; my workplace is now happily using django-tokenapi together with django rest framework!

For anyone who wants to follow in our footsteps, you can basically just:

  1. Install both frameworks
  2. Add the token URLs to your urls.py:
(r'^token/', include('tokenapi.urls')),

(NOTE: This is the URL your users will use to acquire a token).

  1. Instead of using the django token api decorator, use this one:
def token_required(view_func):
    """Django-TokenAPI provides a decorator (similarly named "token_required"), which this decorator
       is based on.  However, Django-TokenAPI's decorator isn't designed to handle
       Django-Rest-Framework's views, so we had to make our own version that can."""

    @csrf_exempt
    @wraps(view_func)
    def _wrapped_view(self, request,  *args, **kwargs):
        user_id = request.REQUEST.get('user')
        token = request.REQUEST.get('token')
        if user_id and token:
            # This is an API-based request; "login" the user specified with the provided token
            user = authenticate(pk=user_id, token=token)
            login(request, user)
        return view_func(self, request, *args, **kwargs)
    return _wrapped_view
  1. Add that decorator to all of your get/post/put/whatever methods ... or just to the dispatch method (which is what I did)

With that all of your API calls will now accept normal (cookie/session-based) Django authentication OR authentication tokens. If you want to not accept normal Django authentication it should be pretty easy to tweak the decorator.

Hope this helps someone :-)

from django-rest-framework.

machineghost avatar machineghost commented on May 22, 2024

Oops, I lied; don't use that decorator, use this one (which has a few extra lines to actually return a ResponseForbidden if the user fails to authenticate):

from django.http import HttpResponseForbidden
def token_required(view_func):
    """Django-TokenAPI provides a decorator (similarly named "token_required"), which this decorator
       is based on.  However, Django-TokenAPI's decorator isn't designed to handle
       Django-Rest-Framework's views, so we had to make our own version that can."""

    @csrf_exempt
    @wraps(view_func)
    def _wrapped_view(self, request,  *args, **kwargs):
        user_id = request.REQUEST.get('user')
        token = request.REQUEST.get('token')
        if user_id and token:
            # This is an API-based request; "login" the user specified with the provided token
            user = authenticate(pk=user_id, token=token)
            login(request, user)
        if request.user.is_authenticated():
            return view_func(self, request, *args, **kwargs)
        return HttpResponseForbidden('Unable to authenticate')
    return _wrapped_view

from django-rest-framework.

tomchristie avatar tomchristie commented on May 22, 2024

Fixed in restframework2 branch. See source and docs.

from django-rest-framework.

machineghost avatar machineghost commented on May 22, 2024

Awesome! I have found one other bug in my code through (sorry, should have tested better before posting). Can you please change:

     def _wrapped_view(self, request,  *args, **kwargs):
+        user = request.user
         user_id = request.REQUEST.get('user')

             login(request, user)
-        if request.user.is_authenticated():
+        if user.is_authenticated():
             return view_func(self, request, *args, **kwargs)

(without that fix the normal authentication flow fails).

from django-rest-framework.

jpulgarin avatar jpulgarin commented on May 22, 2024

Hey @machineghost I'm trying to understand the changes you made to token_required. As far as I can tell, the only difference is that you're not checking if you get a valid user object after calling authenticate. Any reason for that?

from django-rest-framework.

machineghost avatar machineghost commented on May 22, 2024

It's been nine months, I've since stopped working on Python, and I have an absolutely terrible memory even for code I wrote yesterday, so ... you've been warned.

That being said, I think the issue I had was just that request.user wasn't authenticated, but the user that came back from the login was, so I wanted to be sure to check that user. Unfortunately I have no recollection of any details beyond that (eg. what the circumstances were when I observed that problem); sorry :-(

from django-rest-framework.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.