Skip to content

Commit

Permalink
Merge pull request #9 from ral-facilities/5_add_bearer_authentication…
Browse files Browse the repository at this point in the history
…_type_to_auth_header

Use bearer type in authorisation header
  • Loading branch information
keiranjprice101 authored Jun 18, 2019
2 parents 647dde6 + b3440ed commit 2ec57a9
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 12 deletions.
4 changes: 4 additions & 0 deletions common/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@ class MissingRecordError(ApiError):

class BadFilterError(ApiError):
pass


class AuthenticationError(ApiError):
pass
26 changes: 16 additions & 10 deletions common/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from sqlalchemy.exc import IntegrityError

from common.database_helpers import get_icat_db_session
from common.exceptions import MissingRecordError, BadFilterError
from common.exceptions import MissingRecordError, BadFilterError, AuthenticationError
from common.models.db_models import SESSION


Expand All @@ -19,12 +19,15 @@ def requires_session_id(method):

@wraps(method)
def wrapper_requires_session(*args, **kwargs):
session = get_icat_db_session()
query = session.query(SESSION).filter(
SESSION.ID == get_session_id_from_auth_header()).first()
if query is not None:
return method(*args, **kwargs)
else:
try:
session = get_icat_db_session()
query = session.query(SESSION).filter(
SESSION.ID == get_session_id_from_auth_header()).first()
if query is not None:
return method(*args, **kwargs)
else:
return "Forbidden", 403
except AuthenticationError:
return "Forbidden", 403

return wrapper_requires_session
Expand Down Expand Up @@ -63,9 +66,12 @@ def get_session_id_from_auth_header():
parser = reqparse.RequestParser()
parser.add_argument("Authorization", location="headers")
args = parser.parse_args()
if args["Authorization"] is not None:
return args["Authorization"]
return ""
auth_header = args["Authorization"].split(" ") if args["Authorization"] is not None else ""
if auth_header == "":
return ""
if len(auth_header) != 2 or auth_header[0] != "Bearer":
raise AuthenticationError()
return auth_header[1]


def is_valid_json(string):
Expand Down
4 changes: 2 additions & 2 deletions test/test_base/constants.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
GOOD_CREDENTIALS_HEADER = {"Authorization": "TestSession"}
BAD_CREDENTIALS_HEADER = {"Authorization": "Santa Claus"}
GOOD_CREDENTIALS_HEADER = {"Authorization": "Bearer TestSession"}
BAD_CREDENTIALS_HEADER = {"Authorization": "Bearer SantaClaus"}

0 comments on commit 2ec57a9

Please sign in to comment.