From 59a9b4f08451cbf29ec7e03979474e81098bf05b Mon Sep 17 00:00:00 2001 From: Ved Shah Date: Sun, 18 Aug 2024 14:02:30 +0530 Subject: [PATCH] Update authentication.py Code Simplification Reduced redundant checks in the authenticate method by combining the conditions for the length of auth. Removed the unnecessary elif in favor of an if to make the code flow clearer --- rest_framework/authentication.py | 32 ++++++++++---------------------- 1 file changed, 10 insertions(+), 22 deletions(-) diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py index 3f3bd2227..971d80983 100644 --- a/rest_framework/authentication.py +++ b/rest_framework/authentication.py @@ -150,10 +150,10 @@ class SessionAuthentication(BaseAuthentication): class TokenAuthentication(BaseAuthentication): """ - Simple token based authentication. + Simple token-based authentication. Clients should authenticate by passing the token key in the "Authorization" - HTTP header, prepended with the string "Token ". For example: + HTTP header, prepended with the string "Token ". For example: Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a """ @@ -167,31 +167,19 @@ class TokenAuthentication(BaseAuthentication): from rest_framework.authtoken.models import Token return Token - """ - A custom token model may be used, but must have the following properties. - - * key -- The string identifying the token - * user -- The user to which the token belongs - """ - def authenticate(self, request): auth = get_authorization_header(request).split() - if not auth or auth[0].lower() != self.keyword.lower().encode(): + if len(auth) != 2 or auth[0].lower() != self.keyword.lower().encode(): return None - - if len(auth) == 1: - msg = _('Invalid token header. No credentials provided.') - raise exceptions.AuthenticationFailed(msg) - elif len(auth) > 2: - msg = _('Invalid token header. Token string should not contain spaces.') - raise exceptions.AuthenticationFailed(msg) - + + token = auth[1] try: - token = auth[1].decode() + token = token.decode() except UnicodeError: - msg = _('Invalid token header. Token string should not contain invalid characters.') - raise exceptions.AuthenticationFailed(msg) + raise exceptions.AuthenticationFailed( + _('Invalid token header. Token string should not contain invalid characters.') + ) return self.authenticate_credentials(token) @@ -205,7 +193,7 @@ class TokenAuthentication(BaseAuthentication): if not token.user.is_active: raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) - return (token.user, token) + return token.user, token def authenticate_header(self, request): return self.keyword