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
This commit is contained in:
Ved Shah 2024-08-18 14:02:30 +05:30 committed by GitHub
parent f113ab6b68
commit 59a9b4f084
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -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