Skip to content

Commit

Permalink
updated middleware, passes tests
Browse files Browse the repository at this point in the history
  • Loading branch information
sritanmotati committed Nov 22, 2024
1 parent 9eda14c commit eb327d1
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 24 deletions.
63 changes: 42 additions & 21 deletions accounts/middleware.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,31 @@
from django.http import HttpResponseForbidden, HttpResponseBadRequest, HttpResponseServerError
from django.shortcuts import redirect
from django.conf import settings
import requests
import re
from jwcrypto import jwt, jwk

import requests
from django.http import (
HttpResponseBadRequest,
HttpResponseForbidden,
HttpResponseServerError,
)
from django.shortcuts import redirect
from jwcrypto import jwk, jwt

from accounts.views import get_redirect_uri


class LoginRequiredMiddleware:
def __init__(self, get_response):
self.get_response = get_response
self.EXEMPT_URLS = [
r"^accounts/login/$",
r"^accounts/callback/$",
r"^accounts/logout/$",
r"^accounts/token/$",
r"^/accounts/login/$",
r"^/accounts/callback/$",
r"^/accounts/logout/$",
r"^/accounts/token/$",
r"^/admin/.*$",
]

def handle_no_permission(self, request):
return redirect(get_redirect_uri(request))

def add_new_exempt_urls(self):
pass
# EXAMPLE USAGE
Expand All @@ -30,25 +37,39 @@ def __call__(self, request):
regex_list = [re.compile(url) for url in self.EXEMPT_URLS]
if any(url.match(request.path) for url in regex_list):
return self.get_response(request)

try:
key = jwk.JWK()
key.import_key(**(requests.get("https://platform.pennlabs.org/accounts/.well-known/jwks.json").json()['keys'][0]))

key.import_key(
**(
requests.get(
"https://platform.pennlabs.org/accounts/.well-known/jwks.json"
).json()["keys"][0]
)
)

token = request.headers.get("Authorization")
if token is None:
return HttpResponseBadRequest(content="No Authorization header")

response = HttpResponseBadRequest(content="No Authorization header")
response.status_code = 401
return response

token = token.split(" ")
if len(token) != 2 or token[0] != "Bearer":
return HttpResponseBadRequest(content="Invalid Authorization header")

response = HttpResponseBadRequest(
content="Invalid Authorization header"
)
response.status_code = 401
return response

try:
token = jwt.JWT(key=key, jwt=token[1])
except Exception as e:
return HttpResponseForbidden(content="Invalid token")
response = HttpResponseForbidden(content=f"Invalid token: {e}")
response.status_code = 401
return response

return self.get_response(request)
except Exception as e:
print(e)
return HttpResponseServerError(content=str(e))
print(e)
return HttpResponseServerError(content=str(e))
2 changes: 1 addition & 1 deletion identity/identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from accounts.settings import accounts_settings


JWKS_URL = f"{accounts_settings.PLATFORM_URL}/identity/jwks/"
JWKS_URL = f"{accounts_settings.PLATFORM_URL}/accounts/.well-known/jwks.json"
ATTEST_URL = f"{accounts_settings.PLATFORM_URL}/identity/attest/"
REFRESH_URL = f"{accounts_settings.PLATFORM_URL}/identity/refresh/"

Expand Down
5 changes: 4 additions & 1 deletion tests/accounts/test_authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ def setUp(self):
self.csrf_client = APIClient(enforce_csrf_checks=True)
self.path = "/token/"
self.header_prefix = "Bearer "
self.auth = f"{self.header_prefix}eyJ0eXAiOiAiSldUIiwgImFsZyI6ICJSUzI1NiIsICJraWQiOiAiZ2JoaHZzMmRTX2NDcjYwN0tzb1kzdjBNdjFpRlJkUUV2Z2xfSUVKZjBHYyJ9.eyJhdWQiOiAiNG12aUxodGo4N05LaHFCRFhsVjZDaXRmNWZZb015UXpSR05tWmRpaCIsICJpYXQiOiAxNzMxODY4MjQyLCAiYXRfaGFzaCI6ICIyRkZIeHVVaVpoRWE4MHBVWkRMR3d3IiwgInN1YiI6ICIwNjQ1MTgwMy01MWNhLTQ4OWUtYmY0OC05NWI3Y2Q0OTViOTEiLCAibmFtZSI6ICJTcml0YW4gTW90YXRpIiwgImVtYWlsIjogInNyaXRhbkBzZWFzLnVwZW5uLmVkdSIsICJwZW5ua2V5IjogInNyaXRhbiIsICJwZW5uaWQiOiA3NzcwOTE2MywgImlzX3N0YWZmIjogZmFsc2UsICJpc19hY3RpdmUiOiB0cnVlLCAiaXNzIjogImh0dHA6Ly9wbGF0Zm9ybS5wZW5ubGFicy5vcmcvYWNjb3VudCIsICJleHAiOiAxNzMxOTA0MjQyLCAiYXV0aF90aW1lIjogMTczMTcwOTEzMSwgImp0aSI6ICJmMjVhMGQ5NS0yZDJhLTRkOWYtYTNiNC05Yzk4Y2Y4NGZkYTIifQ.CpMIQVHBeQgvfqw0nGknYOXttNfiOphFGsFvlVVO3Jv1zSR577nOSIU-CQ_NBSmryY0DbWdvoMfcnmUgwmTUZa65HwKPfiSZD3UW47yqKhRSsPZqCDFCNrAl8o5ooVi3glmJuj4H4MQeCg7o44jXQk8jn2wzDW21Q7Tp_D6ubj_u1vMjcQ0ioa_EUj7ycV3A6SFCbhbaV1zyo_Trbz_4bDsnB9Ze4wkDW2ml5C1epqHnc12LyWeYGlptadchQoel5i9Dp4OGUj-fSVHKQzzggyhwiBk664GYnq1pIZiA-BVssFxp3fxBwe4-z6RVIY5n_mGDFfwtRngql5aGv-iyuK5d9Evvt-bTkSmU_uobhgGrbL-HiRcGrf2zOmS4rXGiiHpX4nIFKPWMJfS4k_gjegyz6rfu41iogto5IyCtmOEHx3-DbRUBi1qzSPCDURGODgjRY3vYEpmyPWJpOq0MazwtEytQMvFTPmBuRrvbJtCLF169xEb1d-km5K98KqLCJXZ8JftFLTYuyNP0NlWf3vDj9n25NQEG2fgzhbjl16XPmFB8Cri6tilD5Zr4nIE9JfTSmADgnjiHyXInhD9zx6rvr723R5_03QJRiR8W4xQpBaM1-4zZ99kkSRS9LaQoPoaVoGIWo_O--LAHRuWCvIv1itnqCcpdoH-c30x1pF8"
# TODO: Generate a valid token for the test
# instead of hardcoding with a token from Course Alert 2.0
valid_token = "abcd..."
self.auth = f"{self.header_prefix}{valid_token}"

self.user = User.objects.create(id=123, username="username")
self.headers = {}
Expand Down
2 changes: 1 addition & 1 deletion tests/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"accounts.middleware.LoginRequiredMiddleware"
"accounts.middleware.LoginRequiredMiddleware",
]

ROOT_URLCONF = "tests.urls"
Expand Down

0 comments on commit eb327d1

Please sign in to comment.