Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat-5] 모든 Error Function Customize 지원하기 #10

Merged
merged 3 commits into from
Jul 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 7 additions & 24 deletions django_jwt_extended/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,27 +24,10 @@ def ready(self):
self.refresh_token_expires = data.refresh_token_expires
self.token_header_name = 'Authorization'

# default error messages
self.jwt_not_found_msg = {
'msg': 'JWT token not found'
}
self.bearer_error_msg = {
'msg': (
f"Missing 'Bearer' type in "
f"'{self.token_header_name}' header."
f" Expected '{self.token_header_name}: "
f"Bearer <JWT>'"
)
}
self.decode_error_msg = {
'msg': 'Signature verification failed.'
}
self.expired_token_msg = {
'msg': 'JWT Token has expired'
}
self.invalid_token_type_msg = {
'msg': "Invalid JWT token type"
}
self.invalid_nbf_msg = {
'msg': "The token is not yet valid (nbf)"
}
self.jwt_not_found_msg = data.errors['JWT_NOT_FOUND_MSG']
self.bearer_error_msg = data.errors['BEARER_ERROR_MSG']
self.decode_error_msg = data.errors['DECODE_ERROR_MSG']
self.expired_token_msg = data.errors['EXPIRED_TOKEN_MSG']
self.invalid_token_type_msg = data.errors['INVALID_TOKEN_TYPE_MSG']
self.invalid_nbf_msg = data.errors['INVALID_NBF_MSG']

37 changes: 37 additions & 0 deletions django_jwt_extended/config.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import json
from datetime import timedelta
from django.utils import timezone
from django.apps import apps
from .exceptions import (
ConfigIsNotDict,
InvalidJsonFormat,
InvalidJwtAlgorithm,
InvalidLocation,
InvalidExpires,
Expand All @@ -20,6 +22,7 @@ def __init__(self, config: dict):
self.token_location = self.validate_token_location(config)
self.access_token_expires = self.validate_access_token_expires(config)
self.refresh_token_expires = self.validate_refresh_token_expires(config)
self.errors = self.customize_error(config)

@staticmethod
def validate_jwt_algorithm(config: dict):
Expand Down Expand Up @@ -56,4 +59,38 @@ def validate_refresh_token_expires(config: dict):
raise InvalidExpires('REFRESH_TOKEN')
return expires

@staticmethod
def customize_error(config: dict):

def validate_json(data: dict):
try:
json.dumps(data)
except ValueError:
return False
return True

default_error = {
'JWT_NOT_FOUND_MSG': {'msg': 'JWT token not found'},
'DECODE_ERROR_MSG': {'msg': 'Signature verification failed.'},
'EXPIRED_TOKEN_MSG': {'msg': 'JWT token has expired'},
'INVALID_TOKEN_TYPE_MSG': {'msg': "Invalid JWT token type"},
'INVALID_NBF_MSG': {'msg': "The token is not yet valid (nbf)"},
'BEARER_ERROR_MSG': {
'msg':(
f"Missing 'Bearer' type in "
f"'Authorization' header."
f" Expected 'Authorization: "
f"Bearer <JWT>'"
)
},
}

customized_error = {}
for error in default_error.keys():
target = config.get(error, default_error[error])
if not validate_json(target):
raise InvalidJsonFormat()

customized_error[error] = target

return customized_error
9 changes: 9 additions & 0 deletions django_jwt_extended/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,13 @@ def __init__(self, param: str):
def __str__(self):
return (
f"'refresh' param must be bool type, not {self.param}."
)


class InvalidJsonFormat(Exception):

def __str__(self):
return (
f"Invalid JSON format."
f"Error config must be JSON serializable."
)
1 change: 1 addition & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ def setup_django():
'LOCATION': ['headers'],
'ACCESS_TOKEN_EXPIRES': timedelta(days=2),
'REFRESH_TOKEN_EXPIRES': timedelta(days=30),
'JWT_NOT_FOUND_MSG': {'msg': "can't find JWT token."}
},
TIME_ZONE='Asia/Seoul',
USE_TZ=False,
Expand Down
15 changes: 15 additions & 0 deletions tests/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,21 @@ def test_token_not_found(self):
request = self.factory.get('/user')
response = user(request)
self.assertEqual(response.status_code, 401)
self.assertEqual(
response.content.decode(encoding='utf8'),
json.dumps({'msg': "can't find JWT token."})
)

def test_token_header_not_bearer(self):
"""Test Token Header Not Bearer"""
request = self.factory.get(
'/user',
HTTP_Authorization=(
self.access_token
)
)
response = user(request)
self.assertEqual(response.status_code, 401)

def test_expired_token_auth(self):
"""Test Expired Token Auth"""
Expand Down