Skip to content

Commit

Permalink
Revert "DevAuth feature redesign inspired by Cypress"
Browse files Browse the repository at this point in the history
This reverts commit 1497d4a.
  • Loading branch information
elipe17 committed Dec 19, 2023
1 parent c49365f commit 7bb7522
Show file tree
Hide file tree
Showing 9 changed files with 53 additions and 51 deletions.
1 change: 0 additions & 1 deletion tdrs-backend/docker-compose.local.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions tdrs-backend/tdpservice/settings/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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)
2 changes: 0 additions & 2 deletions tdrs-backend/tdpservice/users/api/authorization_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
1 change: 0 additions & 1 deletion tdrs-backend/tdpservice/users/api/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
50 changes: 27 additions & 23 deletions tdrs-backend/tdpservice/users/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "[email protected]"
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):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)}")
3 changes: 3 additions & 0 deletions tdrs-frontend/src/actions/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
22 changes: 21 additions & 1 deletion tdrs-frontend/src/configureStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: '[email protected]',
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
Expand Down
20 changes: 0 additions & 20 deletions tdrs-frontend/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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/)) {
Expand Down

0 comments on commit 7bb7522

Please sign in to comment.