Skip to content

Commit

Permalink
added more test
Browse files Browse the repository at this point in the history
  • Loading branch information
raftmsohani committed Jul 16, 2024
1 parent b4f0995 commit 90b64a6
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 34 deletions.
66 changes: 36 additions & 30 deletions tdrs-backend/tdpservice/users/api/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,40 +199,13 @@ def login_user(request, user, user_status):
)
logger.info("%s: %s on %s", user_status, user.username, timezone.now)

def get(self, request, *args, **kwargs):
"""Handle decoding auth token and authenticate user."""
code = request.GET.get("code", None)
state = request.GET.get("state", None)

if code is None:
logger.info("Redirecting call to main page. No code provided.")
return HttpResponseRedirect(settings.FRONTEND_BASE_URL)

if state is None:
logger.info("Redirecting call to main page. No state provided.")
return HttpResponseRedirect(settings.FRONTEND_BASE_URL)

token_endpoint_response = self.get_token_endpoint_response(code)

if token_endpoint_response.status_code != 200:
return Response(
{
"error": (
"Invalid Validation Code Or OpenID Connect Authenticator "
"Down!"
)
},
status=status.HTTP_400_BAD_REQUEST,
)

token_data = token_endpoint_response.json()
id_token = token_data.get("id_token")

def _get_user_id_token(self, request, state, token_data):
"""Get the user and id_token from the request."""
try:
decoded_payload = self.validate_and_decode_payload(request, state, token_data)
id_token = token_data.get("id_token")
user = self.handle_user(request, id_token, decoded_payload)
return response_redirect(user, id_token)

except (InactiveUser, ExpiredToken) as e:
logger.exception(e)
return Response(
Expand Down Expand Up @@ -276,6 +249,39 @@ def get(self, request, *args, **kwargs):
status=status.HTTP_400_BAD_REQUEST,
)

def get(self, request, *args, **kwargs):
"""Handle decoding auth token and authenticate user."""
code = request.GET.get("code", None)
state = request.GET.get("state", None)

if code is None or state is None:
logger.info(f"Redirecting call to main page. No {'code' if code is None else 'state'} provided.")
return HttpResponseRedirect(settings.FRONTEND_BASE_URL)

try:
token_endpoint_response = self.get_token_endpoint_response(code)
except Exception as e:
logger.exception(e)
return Response(
{
"error": str(e)
},
status=status.HTTP_503_SERVICE_UNAVAILABLE
)

if token_endpoint_response.status_code != 200:
return Response(
{
"error": (
"Invalid Validation Code Or OpenID Connect Authenticator "
"Down!"
)
},
status=status.HTTP_400_BAD_REQUEST,
)

token_data = token_endpoint_response.json()
return self._get_user_id_token(request, state, token_data)

class TokenAuthorizationLoginDotGov(TokenAuthorizationOIDC):
"""Define methods for handling login request from login.gov."""
Expand Down
3 changes: 2 additions & 1 deletion tdrs-backend/tdpservice/users/api/login_redirect_oidc.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import requests
import secrets
import time
from rest_framework import status
from urllib.parse import quote_plus, urlencode

from django.conf import settings
Expand Down Expand Up @@ -118,7 +119,7 @@ def get(self, request, *args, **kwargs):
'error_pages/500.html',
{'error': f"Failed to get AMS configuration: {e}"})
return HttpResponse(rendered,
status=500)
status=status.HTTP_503_SERVICE_UNAVAILABLE)
auth_params = {
"client_id": settings.AMS_CLIENT_ID,
"nonce": nonce,
Expand Down
6 changes: 3 additions & 3 deletions tdrs-backend/tdpservice/users/test/test_api/test_login.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def test_get_ams_configuration(requests_get_mock):
assert returned_value == {'key': 'test'}

# Test if the configuration is not returned
requests_get_mock.return_value.status_code = 500
requests_get_mock.return_value.status_code = 503
with pytest.raises(Exception):
LoginRedirectAMS.get_ams_configuration()

Expand All @@ -40,7 +40,7 @@ class DummyRequest:
assert "dummy_authorization_endpoint" in response.url

# Test if the AMS server is down
requests_get_mock.return_value.status_code = 500
requests_get_mock.return_value.status_code = 503
login_redirect_ams = LoginRedirectAMS()
response = login_redirect_ams.get("request")
assert response.status_code == 500
assert response.status_code == 503
22 changes: 22 additions & 0 deletions tdrs-backend/tdpservice/users/test/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation
from rest_framework import status
from rest_framework.test import APIRequestFactory
from unittest import mock
import jwt
import pytest

Expand Down Expand Up @@ -278,6 +279,27 @@ def test_auth_user_hhs_id_update(self, user):
user_by_id = CustomAuthentication.authenticate(username=user.username, hhs_id=self.test_hhs_id)
assert str(user_by_id.hhs_id) == self.test_hhs_id

@mock.patch("requests.get")
def test_bad_AMS_configuration(
self,
ams_states_factory,
req_factory,
user
):
"""Test login with state and code."""
request = req_factory
request = create_session(request, ams_states_factory)
user.hhs_id = self.test_hhs_id
# test new hash
user.login_gov_uuid = None
user.save()

view = TokenAuthorizationAMS.as_view()
response = view(request)
assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
assert b'Failed to get AMS configuration' in response.render().content


def test_login_gov_redirect(api_client):
"""Test login.gov login url redirects."""
response = api_client.get("/v1/login/dotgov")
Expand Down

0 comments on commit 90b64a6

Please sign in to comment.