Skip to content

Commit

Permalink
Merge bc7365f into b4d59c2
Browse files Browse the repository at this point in the history
  • Loading branch information
engjames committed Apr 29, 2019
2 parents b4d59c2 + bc7365f commit df884c1
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 18 deletions.
38 changes: 23 additions & 15 deletions authors/apps/authentication/backends.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,49 @@
from django.conf import settings

from rest_framework import authentication, exceptions

from authors.apps.authentication.models import User
from rest_framework.response import Response
from rest_framework import status
import jwt


class JWTAuthentication(authentication.BaseAuthentication):
"""Authenticate requests by using tokens."""

authentication_header_prefix = "Bearer"

def authenticate(self, request):
"""Check for authorization header."""
try:
request.user = None
header = authentication.get_authorization_header(request).split()
token = header[1]
if header[0] != self.authentication_header_prefix:
message = "Bearer prefix missing in Authorization header"
return Response(message, status=status.HTTP_401_UNAUTHORIZED)
return self.authenticate_credentials(request, token)
except Exception as e:
raise exceptions.AuthenticationFailed(e)
request.user = None
header = authentication.get_authorization_header(request).split()
prefix = self.authentication_header_prefix.lower()
if not header:
message = "Token is missing."
raise exceptions.AuthenticationFailed(message)
if len(header) == 1 or len(header) > 2:
message = "Invalid Token, header expects two parameters."
raise exceptions.AuthenticationFailed(message)
prefix = header[0].decode('utf-8')
token = header[1].decode('utf-8')
if prefix.lower() != 'Bearer'.lower():
message = "Bearer prefix missing in authorization headers."
raise exceptions.AuthenticationFailed(message)
return self.authenticate_credentials(request, token)

def authenticate_credentials(self, request, token):
"""Identify a user using the token provided"""
"""Identify a user using the token provided."""
try:
payload = jwt.decode(token, settings.SECRET_KEY, 'utf-8')
except jwt.ExpiredSignatureError:
message = "The token has expired, please login again."
raise exceptions.AuthenticationFailed(message)
except BaseException:
message = "The token provided can not be decoded."
raise exceptions.AuthenticationFailed(message)
user = User.objects.get(username=payload['sub']['username'])
user = User.objects.get(email=payload['sub']['email'])
if not user:
message = "User does not exist in the database."
raise exceptions.AuthenticationFailed(message)
if not user.is_active:
message = "User is not activated."
raise exceptions.AuthenticationFailed(message)
return (user, token)

6 changes: 3 additions & 3 deletions authors/apps/authentication/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,14 +117,14 @@ def get_short_name(self):
return self.username

@staticmethod
def encode_auth_token(username):
def encode_auth_token(email):
"""Generates auth token."""
try:
payload = {
'exp': datetime.datetime.utcnow() + datetime.timedelta(
days=2, seconds=20000),
seconds=900),
'iat': datetime.datetime.utcnow(),
'sub': username
'sub': email
}
return jwt.encode(
payload, settings.SECRET_KEY, algorithm='HS256'
Expand Down

0 comments on commit df884c1

Please sign in to comment.