-
Notifications
You must be signed in to change notification settings - Fork 41
Added James’ individual contributions (mental_health_hub demo) #147
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
gituser14d
wants to merge
1
commit into
main
Choose a base branch
from
james_contributions
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 added
BIN
+488 KB
mental_health_hub (James Nardella)/docs/Collaborative Confidence Model Summary.pdf
Binary file not shown.
Binary file not shown.
110 changes: 110 additions & 0 deletions
110
mental_health_hub (James Nardella)/flask_jwt_demo/Token-Based Authentication (JWT).py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
65
mental_health_hub (James Nardella)/flask_jwt_demo/readme.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
24
mental_health_hub (James Nardella)/flask_jwt_demo/test_api.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 added
BIN
+567 KB
mental_health_hub (James Nardella)/incident_response_plan/Incident Response Plan.pdf
Binary file not shown.
Binary file added
BIN
+951 KB
mental_health_hub (James Nardella)/logging_demo/Logging & Monitoring.pdf
Binary file not shown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?