mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-02-20 05:20:56 +03:00
Added authtoken login/logout urlpatterns and views to support scripted logins and logouts using TokenAuthentication. Added unittests.
This commit is contained in:
parent
f9a9ff1db0
commit
e029e44477
37
rest_framework/authtoken/serializers.py
Normal file
37
rest_framework/authtoken/serializers.py
Normal file
|
@ -0,0 +1,37 @@
|
||||||
|
from django.contrib.auth import authenticate
|
||||||
|
|
||||||
|
from rest_framework import serializers
|
||||||
|
from rest_framework.authtoken.models import Token
|
||||||
|
|
||||||
|
|
||||||
|
class AuthTokenSerializer(serializers.Serializer):
|
||||||
|
token = serializers.Field(source="key")
|
||||||
|
username = serializers.CharField(max_length=30)
|
||||||
|
password = serializers.CharField()
|
||||||
|
|
||||||
|
def validate(self, attrs):
|
||||||
|
username = attrs.get('username')
|
||||||
|
password = attrs.get('password')
|
||||||
|
|
||||||
|
if username and password:
|
||||||
|
user = authenticate(username=username, password=password)
|
||||||
|
|
||||||
|
if user:
|
||||||
|
if not user.is_active:
|
||||||
|
raise serializers.ValidationError('User account is disabled.')
|
||||||
|
attrs['user'] = user
|
||||||
|
return attrs
|
||||||
|
else:
|
||||||
|
raise serializers.ValidationError('Unable to login with provided credentials.')
|
||||||
|
else:
|
||||||
|
raise serializers.ValidationError('Must include "username" and "password"')
|
||||||
|
|
||||||
|
def convert_object(self, obj):
|
||||||
|
ret = self._dict_class()
|
||||||
|
ret['token'] = obj.key
|
||||||
|
ret['user'] = obj.user.id
|
||||||
|
return ret
|
||||||
|
|
||||||
|
def restore_object(self, attrs, instance=None):
|
||||||
|
token, created = Token.objects.get_or_create(user=attrs['user'])
|
||||||
|
return token
|
21
rest_framework/authtoken/urls.py
Normal file
21
rest_framework/authtoken/urls.py
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
"""
|
||||||
|
Login and logout views for token authentication.
|
||||||
|
|
||||||
|
Add these to your root URLconf if you're using token authentication
|
||||||
|
your API requires authentication.
|
||||||
|
|
||||||
|
The urls must be namespaced as 'rest_framework', and you should make sure
|
||||||
|
your authentication settings include `TokenAuthentication`.
|
||||||
|
|
||||||
|
urlpatterns = patterns('',
|
||||||
|
...
|
||||||
|
url(r'^auth-token', include('rest_framework.authtoken.urls', namespace='rest_framework'))
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
from django.conf.urls.defaults import patterns, url
|
||||||
|
from rest_framework.authtoken.views import AuthTokenView
|
||||||
|
|
||||||
|
urlpatterns = patterns('rest_framework.authtoken.views',
|
||||||
|
url(r'^login/$', AuthTokenView.as_view(), name='token_login'),
|
||||||
|
# url(r'^logout/$', 'token_logout', name='token_logout'),
|
||||||
|
)
|
Loading…
Reference in New Issue
Block a user