Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions mental_health_hub (James Nardella)/ROOT_README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Mental Health Hub - Individual Contributions (James)

This repository contains my individual contributions to the **Wearables for Seniors - Mental Health Hub** project.
The work here demonstrates different security, integration, and prototype development tasks completed during the trimester.

Each subfolder contains its own project with relevant code, documentation, and (where necessary) a detailed `README.md` for setup and usage.

---

## Repository Structure

- **logging_demo/**
Demonstration of Python logging for better debugging, auditing, and system monitoring.
→ See the folder `README.md` for details and usage.

- **incident_response_plan/**
Written documentation outlining an Incident Response Plan for the project.

- **flask_jwt_demo/**
Prototype Flask application showcasing authentication with JWT (JSON Web Tokens).
→ Setup and run instructions in the folder `README.md`.

- **streamlit_hub_app/**
Streamlit prototype of the Mental Health Hub user interface.
→ Setup and run instructions in the folder `README.md`.

- **threat_model/**
Threat modeling documentation using STRIDE to evaluate security risks.

- **Collaborative Confidence Model Summary.pdf**
Summary document outlining the Collaborative Confidence Model research.

- **website_integration_plan.pdf**
Technical integration and deployment roadmap for moving from prototype to production.

---

## Getting Started

To explore any of the technical demos (e.g., Streamlit app, Flask JWT), please open the corresponding folder and follow its `README.md` setup guide.
All documentation-based contributions (e.g., plans, summaries) are in PDF or markdown format for easy review.

---

## Author

This work was completed individually by **James** as part of the *Wearables for Seniors - Mental Health Hub* project.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
from flask import Flask, request, jsonify #web framework to create routes like /login, /register
import bcrypt #hashes the passwords
import jwt #creates and verifies token
import datetime #helps set token expiry times

app = Flask(__name__) #creates the flask app
app.config['SECRET_KEY'] = "super-secret-key" #



users_db = {} #testing database



def hash_password(password: str) -> bytes:
"""Securely hash a plaintext password using bcrypt."""
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())

def verify_password(password: str, hashed: bytes) -> bool:
"""Verify that a given plaintext password matches the stored bcrypt hash."""
return bcrypt.checkpw(password.encode('utf-8'), hashed)



def generate_token(username: str) -> str:
#create the payload
payload = {
'user': username, #store the username
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30) #set expiration time (30 minutes)
}
#encode the password into a JWT token, signed with the secret key
token = jwt.encode(payload, app.config['SECRET_KEY'], algorithm="HS256")
return token

def verify_token(token: str):
try:
#decode the token and check the signature and expiry
payload = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
return payload
except jwt.ExpiredSignatureError:
# If token is invalid or expired, return None
return None
except jwt.InvalidTokenError:
return None


#user registration
@app.route('/register', methods=['POST'])
def register():
data = request.get_json()
username = data.get("username")
password = data.get("password")

if username in users_db:
return jsonify({"error": "User already exists"}), 400

#save the user with a hashed password
hashed_pw = hash_password(password)
users_db[username] = hashed_pw

return jsonify({"message": f"User {username} registered successfully"}), 201

#user login
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data.get("username")
password = data.get("password")

#check if user exists
if username not in users_db:
return jsonify({"error": "Invalid credentials"}), 401

#check if password matches the hashed one
stored_pw = users_db[username]
if not verify_password(password, stored_pw):
return jsonify({"error": "Invalid credentials"}), 401

#if password is correct then generate token
token = generate_token(username)
return jsonify({"message": f"Welcome, {username}!", "token": token}), 200

@app.route('/protected', methods=['GET'])
def protected():
#read the authorization" header (format: Bearer <token>)
auth_header = request.headers.get("Authorization")
#if no header or wrong format then deny access
if not auth_header or not auth_header.startswith("Bearer "):
return jsonify({"error": "Missing or invalid token"}), 401
#extract the token
token = auth_header.split(" ")[1]
payload = verify_token(token)
#if token is invalid/expired then deny access
if not payload:
return jsonify({"error": "Invalid or expired token"}), 401
# if token is valid then user gets access

username = payload["user"]
return jsonify({"message": f"Hello {username}, you accessed a protected route!"})

@app.route('/logout', methods=['POST'])
def logout():

#logout is just deleting the token from the client side

return jsonify({"message": "Logout by deleting token on client-side"}), 200


if __name__ == "__main__":
app.run(debug=True)
65 changes: 65 additions & 0 deletions mental_health_hub (James Nardella)/flask_jwt_demo/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Flask JWT Authentication Demo

## Overview
This project demonstrates a **token-based authentication system** using **Flask** and **JWT (JSON Web Tokens)**.
It includes:

- **User Registration** - securely hashes and stores passwords with `bcrypt`
- **User Login** - verifies credentials and returns a signed JWT
- **Protected Routes** - accessible only with a valid token in the `Authorization` header
- **Logout** - client-side token invalidation concept
- **API Test Script** - demonstrates how to interact with the Flask app using `requests`

---

## Requirements
- Python 3.8+

Install dependencies with:

pip install flask bcrypt pyjwt requests


## Running the Application

1. Start the Flask app:
python "Token-Based Authentication (JWT).py"

This will start the server at:
http://127.0.0.1:5000


2. Test the API using the provided script:
python test_api.py


## Files

Token-Based Authentication (JWT).py - Flask app with JWT authentication system
test_api.py - Example script to register, login, and access protected routes


## Example API Flow

1. Register a user:
POST /register → { "username": "alice", "password": "mypassword" }

2. Login to receive JWT:
POST /login → returns { "token": "<JWT_TOKEN>" }

3. Access protected route with token:
GET /protected + header → Authorization: Bearer <JWT_TOKEN>

4. Logout:
POST /logout → instructs client to delete token


## Notes

Tokens expire after 30 minutes.

Passwords are never stored in plaintext - they are hashed with bcrypt.

The demo uses an in-memory dictionary (users_db) as a mock database (resets when the server restarts).


24 changes: 24 additions & 0 deletions mental_health_hub (James Nardella)/flask_jwt_demo/test_api.py

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just curious regarding this test API, as it does seem to have hardcoded values stored on it, is there any way outside users can access this? Or is it simply an isolated testing unit?

Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import requests

#register
r = requests.post("http://127.0.0.1:5000/register", json={
"username": "alice",
"password": "mypassword"
})
print(r.json())

#login
r = requests.post("http://127.0.0.1:5000/login", json={
"username": "alice",
"password": "mypassword"
})
data = r.json()
print(data)

token = data.get("token")

#access protected route
r = requests.get("http://127.0.0.1:5000/protected", headers={
"Authorization": f"Bearer {token}"
})
print(r.json())
Binary file not shown.
Binary file not shown.
50 changes: 50 additions & 0 deletions mental_health_hub (James Nardella)/logging_demo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Logging Demo

## Overview
This project demonstrates a basic Python-based **logging and monitoring system**.
It simulates user activity on a website, capturing events such as:

- Successful and failed logins
- File uploads (with validation for safe extensions)
- Chat messages (with spam detection and abuse flags)
- Administrative log viewing and CSV export

This was designed as a prototype to illustrate how user actions can be tracked for **security, auditing, and incident response**.

---

## Requirements
- Python 3.8+
- No external libraries required (uses only built-in modules: `datetime`, `random`, `csv`)

---

## Usage
Run the script from inside the `logging_demo` folder:


python activity_logger.py

Valid usernames: user_102, user_877, user_324, user_3424, admin342

Any password is accepted.

The admin342 account allows: Viewing all logs, Exporting logs to a .csv file

---

## Files

activity_logger.py - Python script implementing the logging system.

Logging & Monitoring.pdf - Documentation explaining the system design, features, and demonstration.

---

## Notes

File uploads accept only safe extensions (.png, .jpg, .jpeg, .pdf, .txt).

Sending 5+ chat messages in one session results in a spam flag and auto-logout.

Logs can be exported to CSV with dynamically generated headers for audit purposes.
Loading
Loading