Skip to content

Initial Minimal Prototype for Behavioral Health Vault (BHV)#97

Open
sk66641 wants to merge 2 commits intoKathiraveluLab:devfrom
sk66641:dev
Open

Initial Minimal Prototype for Behavioral Health Vault (BHV)#97
sk66641 wants to merge 2 commits intoKathiraveluLab:devfrom
sk66641:dev

Conversation

@sk66641
Copy link
Copy Markdown

@sk66641 sk66641 commented Mar 9, 2026

Description:

This PR consists of a minimal prototype of Behavioral Health Vault (BHV) to demonstrate a simple architecture with the goal of keeping the system lightweight.

Tech Stack:

  • Python + FastAPI
  • Jinja2 templates with HTML/CSS
  • MongoDB (PyMongo)
  • local filesystem storage for images

Future Improvements:

  • github repository integration for user storage
  • optional research module for color emotion analysis
  • improved moderation tools for administrators
  • enhanced privacy and access control mechanisms

Screenshots:

Screenshot From 2026-03-10 03-10-55 Screenshot From 2026-03-10 03-11-01

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request lays the foundation for the Behavioral Health Vault (BHV) application, providing a basic framework for users to securely store and manage images related to behavioral health. It includes essential features such as user authentication, image uploading, and gallery viewing, with an admin panel for administrative oversight.

Highlights

  • Initial Prototype: This PR introduces the initial minimal prototype for the Behavioral Health Vault (BHV) application.
  • Tech Stack: The prototype utilizes Python with FastAPI for the backend, Jinja2 templates with HTML/CSS for the frontend, MongoDB for the database, JWT for authentication, and local filesystem storage for images.
  • Functionality: The application includes user authentication (signup/login/logout), image uploading, a gallery to view uploaded images, and an admin panel for managing all images.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • .env.example
    • Added example environment variables for MongoDB URI, database name, JWT secret key, and access token expiration time.
  • .gitignore
    • Updated to ignore the 'storage/images/' directory to prevent storing user-uploaded images in the repository.
  • SETUP.md
    • Added a setup guide with instructions for setting up the BHV, including stack details, project structure, setup steps, and running the application.
  • app/config.py
    • Added configuration settings for the application, including database connection details, JWT settings, and image storage directory.
  • app/database.py
    • Added database connection setup using PyMongo, defining collections for users and images.
  • app/main.py
    • Added the main FastAPI application setup, including routing, static file serving, and middleware configuration.
  • app/routes/admin.py
    • Added routes for the admin panel, including viewing and deleting any image.
  • app/routes/auth.py
    • Added authentication routes for signup, login, and logout.
  • app/routes/gallery.py
    • Added routes for viewing, editing, and deleting images in the user's gallery.
  • app/routes/upload.py
    • Added routes for uploading images, including validation and storage.
  • app/services/auth_service.py
    • Added authentication services for user creation, authentication, and token management.
  • app/services/image_service.py
    • Added image services for saving, deleting, and validating images.
  • app/static/css/style.css
    • Added CSS styling for the application's user interface.
  • app/static/js/theme.js
    • Added JavaScript for theme switching functionality.
  • app/templates/dashboard.html
    • Added HTML template for the user dashboard.
  • app/templates/gallery.html
    • Added HTML template for the image gallery.
  • app/templates/login.html
    • Added HTML template for the login page.
  • app/templates/signup.html
    • Added HTML template for the signup page.
  • app/templates/upload.html
    • Added HTML template for the image upload page.
  • requirements.txt
    • Added project dependencies, including FastAPI, Uvicorn, Jinja2, PyMongo, PyJWT, Passlib, python-multipart and python-dotenv.
  • run.py
    • Added a script to run the FastAPI application using Uvicorn.
Activity
  • Initial commit of the Behavioral Health Vault (BHV) prototype.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a minimal prototype for the Behavioral Health Vault (BHV) application. A critical security vulnerability was identified due to a hardcoded default secret key for JWT token generation, which must be addressed to prevent unauthorized access. Additionally, the review highlighted other critical and high-severity issues such as a path traversal vulnerability, an N+1 query problem, and insecure file upload validation. Suggestions have also been provided to improve security, performance, and maintainability, including aligning the code with FastAPI best practices like using dependency injection and managing resources with lifespan events.

Comment on lines +25 to +29
for image in images:
image["id"] = str(image["_id"])
image["sentiment"] = image.get("sentiment", "neutral")
owner = users_collection.find_one({"_id": ObjectId(image.get("user_id"))})
image["owner_email"] = owner.get("email") if owner else "Unknown"
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

This loop executes a database query for each image to fetch the owner's details. This is an N+1 query problem that will lead to poor performance as the number of images grows. You should aggregate the user_ids and fetch all user documents in a single query before the loop.

    user_ids = {ObjectId(image["user_id"]) for image in images if image.get("user_id")}
    owners = {str(user["_id"]): user for user in users_collection.find({"_id": {"$in": list(user_ids)}})}

    for image in images:
        image["id"] = str(image["_id"])
        image["sentiment"] = image.get("sentiment", "neutral")
        owner = owners.get(image.get("user_id"))
        image["owner_email"] = owner.get("email") if owner else "Unknown"

status_code=400,
)

if not image.filename or not is_allowed_image(image.filename):
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

Validating the file type based on the filename extension is insecure. An attacker could upload a malicious file (e.g., an HTML file with scripts) with an allowed extension (e.g., .jpg). You should validate the file's content (MIME type) to ensure it's actually an image or PDF. Libraries like python-magic can be used for this purpose.


try:
image_doc = images_collection.find_one({"_id": ObjectId(image_id)})
except Exception:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Catching a broad Exception can mask unexpected errors. It's better to catch a more specific exception. ObjectId(image_id) can raise bson.errors.InvalidId for a malformed ID. You should catch that specifically. You'll need to import InvalidId from bson.errors.

Suggested change
except Exception:
except InvalidId:

Comment on lines +6 to +7
client = MongoClient(MONGO_URI)
db = client[DATABASE_NAME]
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The MongoDB client is created at the module level. A better practice in FastAPI is to manage the lifecycle of resources like database connections using startup and shutdown events. This ensures the connection is established when the application starts and gracefully closed when it stops, preventing potential resource leaks. You could create the client in a startup event in app/main.py and close it in a shutdown event.

"email": email,
"password": hash_password(password),
"role": role,
"created_at": datetime.utcnow(),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

datetime.utcnow() is deprecated and will be removed in a future version of Python. It's recommended to use the timezone-aware datetime.now(timezone.utc) to avoid ambiguity. You'll need to update the import to from datetime import datetime, timezone.

Suggested change
"created_at": datetime.utcnow(),
"created_at": datetime.now(timezone.utc),


try:
user = users_collection.find_one({"_id": ObjectId(user_id)})
except Exception:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Catching a broad Exception can hide unexpected errors. It's better to catch a more specific exception. ObjectId(user_id) can raise bson.errors.InvalidId for a malformed ID. You should catch that specifically. You'll need to import InvalidId from bson.errors.

Suggested change
except Exception:
except InvalidId:

with destination.open("wb") as buffer:
shutil.copyfileobj(upload_file.file, buffer)

relative_path = os.path.join("storage", "images", user_id, new_filename)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

This file primarily uses pathlib for path manipulation, but os.path.join is used here. For consistency, it's better to stick with pathlib. Using as_posix() ensures forward slashes in the path, which is standard for web URLs.

Suggested change
relative_path = os.path.join("storage", "images", user_id, new_filename)
relative_path = (Path("storage") / "images" / user_id / new_filename).as_posix()

@@ -0,0 +1,4 @@
MONGO_URI=mongodb://localhost:27017
DATABASE_NAME=bhv_db
JWT_SECRET_KEY=replace-with-a-strong-secret
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The default JWT secret key is weak and should be replaced with a securely generated random string. While this is an example file, providing a stronger example encourages better security practices from the start. Consider using a tool like openssl rand -hex 32 to generate a key and suggest that in the documentation.

Comment on lines +428 to +499
{% if admin_view %}
<script>
const previewModal = document.getElementById("preview-modal");
const closePreviewModalButton = document.getElementById("close-preview-modal");
const previewModalTitle = document.getElementById("preview-modal-title");
const previewModalImage = document.getElementById("preview-modal-image");
const previewModalPdf = document.getElementById("preview-modal-pdf");
const openPreviewButtons = Array.from(document.querySelectorAll(".open-preview-modal"));

const closePreviewModal = () => {
if (!previewModal) {
return;
}
previewModal.hidden = true;
previewModalImage.hidden = true;
previewModalPdf.hidden = true;
previewModalImage.removeAttribute("src");
previewModalPdf.removeAttribute("src");
document.body.style.overflow = "";
};

const openPreviewModal = (payload) => {
if (!previewModal) {
return;
}
previewModalTitle.textContent = payload.title || "Preview";
previewModalImage.hidden = true;
previewModalPdf.hidden = true;
previewModalImage.removeAttribute("src");
previewModalPdf.removeAttribute("src");

if (payload.type === "pdf") {
previewModalPdf.src = payload.path;
previewModalPdf.hidden = false;
} else {
previewModalImage.src = payload.path;
previewModalImage.hidden = false;
}

previewModal.hidden = false;
document.body.style.overflow = "hidden";
};

openPreviewButtons.forEach((button) => {
button.addEventListener("click", () => {
openPreviewModal({
path: button.dataset.filePath,
title: button.dataset.fileTitle,
type: button.dataset.fileType,
});
});
});

if (closePreviewModalButton) {
closePreviewModalButton.addEventListener("click", closePreviewModal);
}

if (previewModal) {
previewModal.addEventListener("click", (event) => {
if (event.target === previewModal) {
closePreviewModal();
}
});
}

document.addEventListener("keydown", (event) => {
if (event.key === "Escape" && previewModal && !previewModal.hidden) {
closePreviewModal();
}
});
</script>
{% endif %}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

There is a large amount of duplicated JavaScript code for handling the preview modal between the admin_view and the regular view. This code should be consolidated into a single script block to improve maintainability and reduce the chance of bugs. You can use the admin_view template variable to conditionally add event listeners for admin-specific functionality if needed, but the core modal logic is the same.

@pradeeban pradeeban added the on hold Not merging this PR now. label Mar 10, 2026
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

on hold Not merging this PR now.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants