Comments (7)
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.
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:
- Install both frameworks
- 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).
- 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
- 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.
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.
Fixed in restframework2
branch. See source and docs.
from django-rest-framework.
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.
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.
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)
- Issue when using base.HTML copy template in other app
- 3.15 missing package inflection HOT 3
- 3.15.0 - bug in rendering `%` characters from `ValidationError` HOT 4
- `permissions.DjangoModelPermissionsOrAnonReadOnly` doesn't actually enable anonymous read-only access in 3.15 HOT 3
- Error: An admin for model "User" has to be registered to be referenced by TokenAdmin.autocomplete_fields. HOT 6
- 3.15 not backwards compatible with 3.14 - "View' should either include a `queryset` attribute, or override the `get_queryset()` method." HOT 11
- 3.15 backward compatibility issue with 3.14 - `rest_framework.filters.SearchFilter.get_search_terms` returns `str` instead of `list` HOT 3
- New handling of default= for ModelSerializer HOT 6
- 3.15 regression: ListSerializer ValidationErrors silently changed return type
- 3.15 regression: ListSerializer ValidationError nested structure silently changed HOT 1
- 3.15 regression: UpdateModelMixin breaks views using Manager objects as queryset HOT 4
- Version 3.15.1 HOT 1
- 3.15 regression: Unset default namespace version suddenly raises 404 HOT 3
- 3.15(.1?) regression: optional fields in serializers are suddenly required (or need explicit None passed) HOT 11
- UniqueConstraint violation_error_message as error response in drf
- rest-framework Supports async class views ?
- 3.15 regression: Serializer validation failed for unique together constraint HOT 1
- Revert changes to `CursorPagination` that caused serious performance regression HOT 1
- Router.register cannot merge with urlpatters HOT 3
- UniqueTogetherValidator does not comply to Database standards
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from django-rest-framework.