Skip to content

Commit

Permalink
Updated .env by adding a new line! Updated blacklist.py to use the st…
Browse files Browse the repository at this point in the history
…ored REDIS_HOST environment variable to access the host correctly for running locally vs in docker! Updated run.py by changing the host to run on 0.0.0.0 instead of debug mode! Updated setupEnv.py by adding a function to check if running in docker to determine whether to run redis since redis is in its own docker container! Created Dockerfile.backend to configure the docker image to install and setup the backend! Created Dockerfile.frontend to configure the docker image to install and setup the frontend! Created compose.yml file with the logic to run the three services in docker containers!
  • Loading branch information
brianlugo1 committed Sep 14, 2024
1 parent 26ab50f commit 14234e2
Show file tree
Hide file tree
Showing 7 changed files with 120 additions and 24 deletions.
2 changes: 1 addition & 1 deletion BackEndFlask/.env
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ FRONT_END_URL=http://127.0.0.1:3000
SUPER_ADMIN_PASSWORD=@super_admin_password123
DEMO_ADMIN_PASSWORD=demo_admin
DEMO_TA_INSTRUCTOR_PASSWORD=demo_ta
DEMO_STUDENT_PASSWORD=demo_student
DEMO_STUDENT_PASSWORD=demo_student
17 changes: 11 additions & 6 deletions BackEndFlask/controller/security/blacklist.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,23 @@
from core import app
from flask_jwt_extended import decode_token
from jwt.exceptions import ExpiredSignatureError
import os

redis_host = os.environ.get('REDIS_HOST', 'localhost')

# Starts a Redis server as a subprocess using the subprocess.Popen function
# Redirects the standard output and standard error streams to subprocess.DEVNULL to get rid of them
def start_redis() -> None:
subprocess.Popen(
'redis-server',
stdout=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)

# Checks if a given token exists in a Redis database and returns True if it is blacklisted
def is_token_blacklisted(token: str) -> bool:
try:
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
r = redis.Redis(host=redis_host, port=6379, db=0, decode_responses=True)
found = r.get(token)
r.close()
return True if found else False
Expand All @@ -30,8 +33,10 @@ def is_token_blacklisted(token: str) -> bool:
def blacklist_token(token: str) -> None:
with app.app_context():
try:
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
r.set(token, r.dbsize()+1, math.ceil((decode_token(token)['exp']) - time.time()))
r.close()
r = redis.Redis(host=redis_host, port=6379, db=0, decode_responses=True)
expiration = math.ceil(decode_token(token)['exp'] - time.time())
r.set(token, r.dbsize()+1, ex=expiration)
r.close()
except ExpiredSignatureError:
return
return

6 changes: 3 additions & 3 deletions BackEndFlask/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@

if __name__ == '__main__':
#The app.run(debug = True) line is needed if we are working on our local machine
app.run(debug=True)
# app.run(debug=True)

#the app.run(host="0.0.0.0") line is currently commented out and if and only when we are seting up an EC2 instance
#app.run(host="0.0.0.0")
app.run(host="0.0.0.0")

# token: MFFt4RjpXNMh1c_T1AQj
# token: MFFt4RjpXNMh1c_T1AQj
36 changes: 22 additions & 14 deletions BackEndFlask/setupEnv.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,36 +85,44 @@ def load_demo():

log("Demo data loaded.")

def is_docker():
path = '/proc/self/cgroup'
try:
with open(path, 'r') as f:
for line in f:
if 'docker' in line:
return True
return os.path.exists('/.dockerenv')
except Exception:
return False

def start_server():
global SYSTEM

log("Starting server...")

if SYSTEM == "Darwin":
exit_code = cmd("brew services start redis")

if is_docker():
log("Running inside Docker. Skipping Redis server start.")
else:
isactive = cmd("systemctl is-active redis-server.service > /dev/null")

if isactive != 0: # 0 = active
exit_code = cmd("systemctl start redis-server.service")
if SYSTEM == "Darwin":
exit_code = cmd("brew services start redis")
else:
isactive = cmd("systemctl is-active redis-server.service > /dev/null")

if exit_code != 0:
err(f"Failed to start redis server. Exit code: {exit_code}")
if isactive != 0: # 0 = active
exit_code = cmd("systemctl start redis-server.service")

sys.exit(1)
if exit_code != 0:
err(f"Failed to start redis server. Exit code: {exit_code}")
sys.exit(1)

exit_code = os.system("python3 run.py")

if exit_code != 0 and exit_code != 2:
err("python3 failed to run. Is it installed?")

err(f"Process exited with exit code {exit_code}")

sys.exit(1)


def reset_db():
log("Resetting database...")

Expand Down Expand Up @@ -229,4 +237,4 @@ def start_tests():
funclst[arg]()

except:
err(f"could not read argument: `{arg}` either because a previous command failed, or it is invalid. See -h for help.")
err(f"could not read argument: `{arg}` either because a previous command failed, or it is invalid. See -h for help.")
28 changes: 28 additions & 0 deletions Dockerfile.backend
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Use Python 3.12 slim image as base
FROM python:3.12-slim-bullseye

# Install necessary dependencies
RUN apt-get update && apt-get install -y cron

# Set the working directory
WORKDIR /app

# Copy only requirements and setup scripts first to leverage Docker cache
COPY BackEndFlask/requirements.txt BackEndFlask/setupEnv.py /app/

# Install Python dependencies
RUN pip install --no-cache-dir --upgrade pip \
&& pip install --no-cache-dir -r requirements.txt

# Copy the rest of the backend code
COPY BackEndFlask/ /app/

# Initialize the Backend environment
RUN python setupEnv.py -id

# Expose the Backend port
EXPOSE 5000

# Start the Flask server
CMD ["python", "setupEnv.py", "-s"]

19 changes: 19 additions & 0 deletions Dockerfile.frontend
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Use a valid Node.js version as base
FROM node:20

# Set the working directory
WORKDIR /app

# Copy package files and install dependencies
COPY FrontEndReact/package*.json /app/
RUN npm install

# Copy the rest of the frontend code
COPY FrontEndReact/ /app/

# Expose the Frontend port
EXPOSE 3000

# Start the Frontend server
CMD ["npm", "start"]

36 changes: 36 additions & 0 deletions compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
services:
backend:
build:
context: .
dockerfile: Dockerfile.backend
ports:
- "5001:5000"
depends_on:
- redis
networks:
- app-network
environment:
- REDIS_HOST=redis

redis:
image: redis:7.2.4
ports:
- "6379:6379"
networks:
- app-network

frontend:
build:
context: .
dockerfile: Dockerfile.frontend
ports:
- "3000:3000"
environment:
- REACT_APP_API_URL=http://localhost:5001/api
networks:
- app-network

networks:
app-network:
driver: bridge

0 comments on commit 14234e2

Please sign in to comment.