mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-08-04 20:40:14 +03:00
Upgrade TokenAuthentication
Simplify the process needed to override TokenAuthentication so it can be using any model that has a key and a user field, whatever the name of those fields. E.g. CustomTokenAuth(TokenAuthentication): model = MyToken user_field_name = 'owner' key_field_name = 'api_key'
This commit is contained in:
parent
7bc9954fdb
commit
c3ee76db10
|
@ -140,15 +140,17 @@ class TokenAuthentication(BaseAuthentication):
|
||||||
HTTP header, prepended with the string "Token ". For example:
|
HTTP header, prepended with the string "Token ". For example:
|
||||||
|
|
||||||
Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a
|
Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a
|
||||||
|
|
||||||
|
You can override this class to use a different Token model by specifying
|
||||||
|
|
||||||
|
* model -- Your Token Model
|
||||||
|
* user_field_name -- the name field that hold the user
|
||||||
|
* key_field_name -- the name of field that hold an authentification key
|
||||||
"""
|
"""
|
||||||
|
|
||||||
model = Token
|
model = Token
|
||||||
"""
|
user_field_name = 'user'
|
||||||
A custom token model may be used, but must have the following properties.
|
key_field_name = 'key'
|
||||||
|
|
||||||
* key -- The string identifying the token
|
|
||||||
* user -- The user to which the token belongs
|
|
||||||
"""
|
|
||||||
|
|
||||||
def authenticate(self, request):
|
def authenticate(self, request):
|
||||||
auth = get_authorization_header(request).split()
|
auth = get_authorization_header(request).split()
|
||||||
|
@ -167,14 +169,16 @@ class TokenAuthentication(BaseAuthentication):
|
||||||
|
|
||||||
def authenticate_credentials(self, key):
|
def authenticate_credentials(self, key):
|
||||||
try:
|
try:
|
||||||
token = self.model.objects.get(key=key)
|
token = self.model.objects.get(**{self.key_field_name: key})
|
||||||
except self.model.DoesNotExist:
|
except self.model.DoesNotExist:
|
||||||
raise exceptions.AuthenticationFailed('Invalid token')
|
raise exceptions.AuthenticationFailed('Invalid token')
|
||||||
|
|
||||||
if not token.user.is_active:
|
user = getattr(token, self.user_field_name)
|
||||||
|
|
||||||
|
if not user.is_active:
|
||||||
raise exceptions.AuthenticationFailed('User inactive or deleted')
|
raise exceptions.AuthenticationFailed('User inactive or deleted')
|
||||||
|
|
||||||
return (token.user, token)
|
return (user, token)
|
||||||
|
|
||||||
def authenticate_header(self, request):
|
def authenticate_header(self, request):
|
||||||
return 'Token'
|
return 'Token'
|
||||||
|
|
Loading…
Reference in New Issue
Block a user