Skip to content

Commit

Permalink
Changes for fully local development
Browse files Browse the repository at this point in the history
 - Enables direct frontend/backend communication sans Login.gov/Cloud.gov
 - Drives off new DEVELOPMENT env var
 - Pre-configures and disables frontend auth functionality
 - Testing based on new dev user
   - Install via web: ./manage.py generate_dev_user
  • Loading branch information
Thomas Tignor authored and Thomas Tignor committed Nov 29, 2023
1 parent 9b1c2d1 commit 55fec3f
Show file tree
Hide file tree
Showing 10 changed files with 85 additions and 6 deletions.
2 changes: 2 additions & 0 deletions tdrs-backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
# Copy this file to `.env` and replace variables as needed
#

DEVELOPMENT=1

# ##
# Required environment variables
# These must be defined or the application will encounter fatal errors
Expand Down
3 changes: 3 additions & 0 deletions tdrs-backend/tdpservice/data_files/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,15 @@ class DataFileViewSet(ModelViewSet):

def create(self, request, *args, **kwargs):
"""Override create to upload in case of successful scan."""
logger.debug(f"{self.__class__.__name__}: {request}")
response = super().create(request, *args, **kwargs)

# only if file is passed the virus scan and created successfully will we perform side-effects:
# * Send to parsing
# * Upload to ACF-TITAN
# * Send email to user

logger.debug(f"{self.__class__.__name__}: status: {response.status_code}")
if response.status_code == status.HTTP_201_CREATED or response.status_code == status.HTTP_200_OK:
user = request.user
data_file_id = response.data.get('id')
Expand Down Expand Up @@ -109,6 +111,7 @@ def create(self, request, *args, **kwargs):
if len(recipients) > 0:
send_data_submitted_email(list(recipients), data_file, email_context, subject)

logger.debug(f"{self.__class__.__name__}: return val: {response}")
return response

def get_s3_versioning_id(self, file_name, prefix):
Expand Down
1 change: 1 addition & 0 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
15 changes: 15 additions & 0 deletions tdrs-backend/tdpservice/users/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,23 @@

from rest_framework.authentication import BaseAuthentication
import logging
import os
logger = logging.getLogger(__name__)

class DevAuthentication(BaseAuthentication):
def authenticate(self, request):
if not os.environ.get('DEVELOPMENT'):
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."""

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#!/usr/bin/env python

from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core.management import BaseCommand

User = get_user_model()

email = "[email protected]"
pswd = "pass"
first = "Jon"
last = "Tester"

class Command(BaseCommand):

def handle(self, *args, **options):
try:
user = User.objects.get(username=email)
print(f"Found {vars(user)}")
except User.DoesNotExist:
group = Group.objects.get(name="Developer")
user = User.objects.create(username=email,
email=email,
password=pswd,
first_name=first,
last_name=last,
account_approval_status="Approved")
user.groups.add(group)
print(f"Created {vars(user)}")

6 changes: 6 additions & 0 deletions tdrs-backend/tdpservice/users/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
from collections import ChainMap
from copy import deepcopy
from typing import List, Optional, TYPE_CHECKING
import logging

logger = logging.getLogger(__name__)


if TYPE_CHECKING: # pragma: no cover
Expand Down Expand Up @@ -126,6 +129,7 @@ class IsApprovedPermission(permissions.DjangoModelPermissions):

def has_permission(self, request, view):
"""Return True if the user has been assigned a group and is approved."""
logging.debug(f"{self.__class__.__name__}: {request} ; {view}")
return (request.user.groups.first() is not None and
request.user.account_approval_status == AccountApprovalStatusChoices.APPROVED)

Expand Down Expand Up @@ -160,6 +164,8 @@ def has_permission(self, request, view):
Data Analyst will only have permission to files within their STT and a
Regional Manager will only have permission to files within their region.
"""
logging.debug(f"{self.__class__.__name__}: {request} ; {view}")

# Checks for existence of `data_files.view_datafile` Permission
has_permission = super().has_permission(request, view)

Expand Down
2 changes: 2 additions & 0 deletions tdrs-frontend/.env
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
# WARNING: This file is checked in to source control, do NOT store any secrets in this file
#

DEVELOPMENT=1

# The hostname behind the tdrs-backend Django app
REACT_APP_BACKEND_HOST=http://127.0.0.1:8080

Expand Down
6 changes: 1 addition & 5 deletions tdrs-frontend/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ services:
ports:
- 8090:8090
networks:
- local
- default
volumes:
- ./reports:/zap/wrk/:rw
- ../scripts/zap-hook.py:/zap/scripts/zap-hook.py:ro
Expand All @@ -21,7 +21,6 @@ services:
- 3000:80
- 8080:8080
networks:
- local
- default
volumes:
- ./:/home/node/app
Expand All @@ -42,9 +41,6 @@ services:
&& nginx -g 'daemon off;'"
networks:
local:
driver: bridge

default:
external:
name: external-net
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.DEVELOPMENT) {
return 0
}
dispatch({ type: FETCH_AUTH })
try {
const URL = `${process.env.REACT_APP_BACKEND_URL}/auth_check`
Expand Down
23 changes: 22 additions & 1 deletion tdrs-frontend/src/configureStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { createBrowserHistory } from 'history'
import thunkMiddleware from 'redux-thunk'
import loggerMiddleware from './middleware/logger'
import createRootReducer from './reducers'
import { permissions } from './components/Header/developer_permissions'

export const history = createBrowserHistory()

Expand All @@ -13,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.DEVELOPMENT ? devState : preloadedState,
composedEnhancers
)
return store
Expand Down

0 comments on commit 55fec3f

Please sign in to comment.