Skip to content

Commit 59a9b4f

Browse files
authored
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
1 parent f113ab6 commit 59a9b4f

File tree

1 file changed

+10
-22
lines changed

1 file changed

+10
-22
lines changed

rest_framework/authentication.py

Lines changed: 10 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -150,10 +150,10 @@ def dummy_get_response(request): # pragma: no cover
150150

151151
class TokenAuthentication(BaseAuthentication):
152152
"""
153-
Simple token based authentication.
153+
Simple token-based authentication.
154154
155155
Clients should authenticate by passing the token key in the "Authorization"
156-
HTTP header, prepended with the string "Token ". For example:
156+
HTTP header, prepended with the string "Token ". For example:
157157
158158
Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a
159159
"""
@@ -167,31 +167,19 @@ def get_model(self):
167167
from rest_framework.authtoken.models import Token
168168
return Token
169169

170-
"""
171-
A custom token model may be used, but must have the following properties.
172-
173-
* key -- The string identifying the token
174-
* user -- The user to which the token belongs
175-
"""
176-
177170
def authenticate(self, request):
178171
auth = get_authorization_header(request).split()
179172

180-
if not auth or auth[0].lower() != self.keyword.lower().encode():
173+
if len(auth) != 2 or auth[0].lower() != self.keyword.lower().encode():
181174
return None
182-
183-
if len(auth) == 1:
184-
msg = _('Invalid token header. No credentials provided.')
185-
raise exceptions.AuthenticationFailed(msg)
186-
elif len(auth) > 2:
187-
msg = _('Invalid token header. Token string should not contain spaces.')
188-
raise exceptions.AuthenticationFailed(msg)
189-
175+
176+
token = auth[1]
190177
try:
191-
token = auth[1].decode()
178+
token = token.decode()
192179
except UnicodeError:
193-
msg = _('Invalid token header. Token string should not contain invalid characters.')
194-
raise exceptions.AuthenticationFailed(msg)
180+
raise exceptions.AuthenticationFailed(
181+
_('Invalid token header. Token string should not contain invalid characters.')
182+
)
195183

196184
return self.authenticate_credentials(token)
197185

@@ -205,7 +193,7 @@ def authenticate_credentials(self, key):
205193
if not token.user.is_active:
206194
raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))
207195

208-
return (token.user, token)
196+
return token.user, token
209197

210198
def authenticate_header(self, request):
211199
return self.keyword

0 commit comments

Comments
 (0)