From 7bb7522bf003ebaab5a0b75fd7eaaa19dd4acd3f Mon Sep 17 00:00:00 2001 From: Eric Lipe Date: Tue, 19 Dec 2023 09:43:47 -0700 Subject: [PATCH] Revert "DevAuth feature redesign inspired by Cypress" This reverts commit 1497d4ab7549bf674e1f71d8f8f039ec7de363bf. --- tdrs-backend/docker-compose.local.yml | 1 - tdrs-backend/tdpservice/settings/common.py | 4 +- .../users/api/authorization_check.py | 2 - tdrs-backend/tdpservice/users/api/login.py | 1 - .../tdpservice/users/authentication.py | 50 ++++++++++--------- .../management/commands/generate_dev_user.py | 1 - tdrs-frontend/src/actions/auth.js | 3 ++ tdrs-frontend/src/configureStore.js | 22 +++++++- tdrs-frontend/src/index.js | 20 -------- 9 files changed, 53 insertions(+), 51 deletions(-) diff --git a/tdrs-backend/docker-compose.local.yml b/tdrs-backend/docker-compose.local.yml index d2cd5289c..3c8e76317 100644 --- a/tdrs-backend/docker-compose.local.yml +++ b/tdrs-backend/docker-compose.local.yml @@ -36,7 +36,6 @@ services: environment: - discovery.type=single-node - xpack.security.enabled=false - - cluster.routing.allocation.disk.threshold_enabled=false - logger.discovery.level=debug ports: - 9200:9200 diff --git a/tdrs-backend/tdpservice/settings/common.py b/tdrs-backend/tdpservice/settings/common.py index fd0c8ff28..0c15a9f43 100644 --- a/tdrs-backend/tdpservice/settings/common.py +++ b/tdrs-backend/tdpservice/settings/common.py @@ -293,6 +293,7 @@ class Common(Configuration): "DEFAULT_RENDERER_CLASSES": DEFAULT_RENDERER_CLASSES, "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"], "DEFAULT_AUTHENTICATION_CLASSES": ( + "tdpservice.users.authentication.DevAuthentication", "tdpservice.users.authentication.CustomAuthentication", "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", @@ -472,5 +473,4 @@ class Common(Configuration): }, } - REACT_APP_DEVAUTH = os.getenv('REACT_APP_DEVAUTH', None) - CYPRESS_TOKEN = 'local-cypress-token' if REACT_APP_DEVAUTH else os.getenv('CYPRESS_TOKEN', None) + CYPRESS_TOKEN = os.getenv('CYPRESS_TOKEN', None) diff --git a/tdrs-backend/tdpservice/users/api/authorization_check.py b/tdrs-backend/tdpservice/users/api/authorization_check.py index ddcfcb1be..57ed30527 100644 --- a/tdrs-backend/tdpservice/users/api/authorization_check.py +++ b/tdrs-backend/tdpservice/users/api/authorization_check.py @@ -21,8 +21,6 @@ class AuthorizationCheck(APIView): def get(self, request, *args, **kwargs): """Handle get request and verify user is authorized.""" - logger.debug(f"{self.__class__.__name__}: {request} {args} {kwargs}") - user = request.user serializer = UserProfileSerializer(user) diff --git a/tdrs-backend/tdpservice/users/api/login.py b/tdrs-backend/tdpservice/users/api/login.py index 0efdf5cce..338508148 100644 --- a/tdrs-backend/tdpservice/users/api/login.py +++ b/tdrs-backend/tdpservice/users/api/login.py @@ -395,7 +395,6 @@ class CypressLoginDotGovAuthenticationOverride(TokenAuthorizationOIDC): def post(self, request): """Create a session for the specified user, if they exist.""" - logging.debug(f"{self.__class__.__name__}: {request} ; {request.data}") username = request.data.get('username', None) token = request.data.get('token', None) diff --git a/tdrs-backend/tdpservice/users/authentication.py b/tdrs-backend/tdpservice/users/authentication.py index 2f4e97b30..3045d2852 100644 --- a/tdrs-backend/tdpservice/users/authentication.py +++ b/tdrs-backend/tdpservice/users/authentication.py @@ -3,50 +3,54 @@ from django.contrib.auth import get_user_model from rest_framework.authentication import BaseAuthentication -from rest_framework.request import Request import logging import os logger = logging.getLogger(__name__) +class DevAuthentication(BaseAuthentication): + """Define authentication and get user functions for local/developer authentication.""" + + def authenticate(self, request): + """Authenticate user.""" + if not os.environ.get('REACT_APP_DEVAUTH'): + return None + logging.debug(f"{self.__class__.__name__}: {request} ; {request.data}") + requser = request.data.get("user") + reqname = requser if requser and requser != "undefined" else "dev@test.com" + User = get_user_model() + authuser = User.objects.get(username=reqname) + if authuser and requser == "undefined": + request.data["user"] = authuser.id + return (User.objects.get(username=reqname), True) + + class CustomAuthentication(BaseAuthentication): """Define authentication and get user functions for custom authentication.""" @staticmethod - def authenticate(request=None, login_gov_uuid=None, hhs_id=None): - """ HACK - This method currently needs to support two unrelated workflows. - References: - tdpservice/users/api/login.py:TokenAuthorizationOIDC.handleUser - https://www.django-rest-framework.org/api-guide/authentication - """ - if type(request) == Request: - logging.debug(f"CustomAuthentication::authenticate: {request} {request.data} " - f"login_gov_id={login_gov_uuid} hhs_id={hhs_id}") - username = request.data.get('username') - else: - logging.debug(f"CustomAuthentication::authenticate: {username} " - f"login_gov_id={login_gov_uuid} hhs_id={hhs_id}") - username = request + def authenticate(username=None, login_gov_uuid=None, hhs_id=None): + """Authenticate user with the request and username.""" User = get_user_model() + logging.debug("CustomAuthentication::authenticate:hhs_id {}".format(hhs_id)) + logging.debug("CustomAuthentication::authenticate:login_gov_uuid {}".format(login_gov_uuid)) + logging.debug("CustomAuthentication::authenticate:username {}".format(username)) try: if hhs_id: try: - user_obj = User.objects.get(hhs_id=hhs_id) + return User.objects.get(hhs_id=hhs_id) except User.DoesNotExist: # If below line also fails with User.DNE, will bubble up and return None user = User.objects.filter(username=username) user.update(hhs_id=hhs_id) logging.debug("Updated user {} with hhs_id {}.".format(username, hhs_id)) - user_obj = User.objects.get(hhs_id=hhs_id) + return User.objects.get(hhs_id=hhs_id) elif login_gov_uuid: - user_obj = User.objects.get(login_gov_uuid=login_gov_uuid) + return User.objects.get(login_gov_uuid=login_gov_uuid) else: - user_obj = User.objects.get(username=username) + return User.objects.get(username=username) except User.DoesNotExist: - user_obj = None - logging.debug(f"CustomAuthentication::authenticate found user: {user_obj}") - return (user_obj, None) if user_obj else None + return None @staticmethod def get_user(user_id): diff --git a/tdrs-backend/tdpservice/users/management/commands/generate_dev_user.py b/tdrs-backend/tdpservice/users/management/commands/generate_dev_user.py index bfc4078fa..ea9b630e0 100755 --- a/tdrs-backend/tdpservice/users/management/commands/generate_dev_user.py +++ b/tdrs-backend/tdpservice/users/management/commands/generate_dev_user.py @@ -28,7 +28,6 @@ def handle(self, *args, **options): is_staff=True, first_name=first, last_name=last, - stt_id=31, account_approval_status="Approved") user.groups.add(group) print(f"Created {vars(user)}") diff --git a/tdrs-frontend/src/actions/auth.js b/tdrs-frontend/src/actions/auth.js index 6b0147c6b..f98b8158f 100644 --- a/tdrs-frontend/src/actions/auth.js +++ b/tdrs-frontend/src/actions/auth.js @@ -40,6 +40,9 @@ export const SET_MOCK_LOGIN_STATE = 'SET_MOCK_LOGIN_STATE' */ export const fetchAuth = () => async (dispatch) => { + if (process.env.REACT_APP_DEVAUTH) { + return 0 + } dispatch({ type: FETCH_AUTH }) try { const URL = `${process.env.REACT_APP_BACKEND_URL}/auth_check` diff --git a/tdrs-frontend/src/configureStore.js b/tdrs-frontend/src/configureStore.js index 3b20fb58a..b96bea6b2 100644 --- a/tdrs-frontend/src/configureStore.js +++ b/tdrs-frontend/src/configureStore.js @@ -14,9 +14,29 @@ export const history = createBrowserHistory() export default function configureStore(preloadedState) { const middlewares = [thunkMiddleware, loggerMiddleware] const composedEnhancers = composeWithDevTools(applyMiddleware(...middlewares)) + const devState = { + router: { location: { pathname: '/profile' } }, + auth: { + user: { + email: 'dev@test.com', + first_name: 'Jon', + last_name: 'Tester', + roles: [{ id: 1, name: 'Developer', permissions }], + access_request: true, + account_approval_status: 'Approved', + stt: { + id: 31, + type: 'state', + code: 'NJ', + name: 'New Jersey', + }, + }, + authenticated: true, + }, + } const store = createStore( createRootReducer(history), - preloadedState, + process.env.REACT_APP_DEVAUTH ? devState : preloadedState, composedEnhancers ) return store diff --git a/tdrs-frontend/src/index.js b/tdrs-frontend/src/index.js index 394371280..3a2f2060c 100644 --- a/tdrs-frontend/src/index.js +++ b/tdrs-frontend/src/index.js @@ -24,28 +24,8 @@ axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = 'X-CSRFToken' axios.defaults.withCredentials = true -function devLogin(devEmail) { - const BACKEND_URL = process.env.REACT_APP_BACKEND_URL - axios - .post(`${BACKEND_URL}/login/cypress`, { - username: devEmail, - token: 'local-cypress-token', - }) - .then(function (response) { - console.log(response) - }) - .catch(function (error) { - console.log(error) - }) - store.dispatch({ type: 'SET_AUTH', payload: { devEmail } }) - console.log(`dispatched SET_AUTH(${devEmail})`) -} - // call auth_check const store = configureStore() -if (process.env.REACT_APP_DEVAUTH) { - devLogin(process.env.REACT_APP_DEVAUTH) -} store.dispatch(fetchAuth()) // if (window.location.href.match(/https:\/\/.*\.app\.cloud\.gov/)) {