mirror of
https://github.com/tmdinosaurcenter/kiosk-guestbook.git
synced 2026-06-28 18:59:05 -06:00
Compare commits
43 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2d4eac6583 | |||
| 94d6690e57 | |||
| 4f0a7df22a | |||
| b2e7eeb570 | |||
| 047f1a8c8b | |||
| c2b6c1b460 | |||
| e733e7b092 | |||
| 9fe3bc43d0 | |||
| a0e6042300 | |||
| 05bcf10614 | |||
| 78ef3eeb85 | |||
| 46dca45e04 | |||
| 2dc276f098 | |||
| e6d742f92e | |||
| e0d72f8057 | |||
| d98dd1518b | |||
| 920463b4a7 | |||
| a178e6193b | |||
| 0c4d3ab15d | |||
| 3e17574fe6 | |||
| 0c8491ce7a | |||
| 1a0a1371bc | |||
| d260bc6f9f | |||
| 412d373421 | |||
| bae3ddda32 | |||
| 85a0096846 | |||
| d76a95e57b | |||
| 91d4715e19 | |||
| ffa09e3daa | |||
| dfb350f8a8 | |||
| ff175edcf6 | |||
| 2bbe30e1e0 | |||
| af3ad37b4c | |||
| bc9fe0909e | |||
| c04ffaf16d | |||
| 5091518bd2 | |||
| caf6f9e970 | |||
| 20dd611b70 | |||
| ada25eba70 | |||
| f34c163a76 | |||
| cfcd301eb0 | |||
| 86529e0728 | |||
| dba4c21a5e |
@@ -0,0 +1,44 @@
|
|||||||
|
name: Docker Image CI
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ "main" ]
|
||||||
|
pull_request:
|
||||||
|
branches: [ "main" ]
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v2
|
||||||
|
- name: Log in to DockerHub
|
||||||
|
if: github.event_name == 'push'
|
||||||
|
uses: docker/login-action@v2
|
||||||
|
with:
|
||||||
|
username: ${{ vars.DOCKER_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
- name: Build the Docker image
|
||||||
|
id: build-image
|
||||||
|
run: |
|
||||||
|
IMAGE_TAG=my-image-name:${{ github.sha }}
|
||||||
|
docker build . --file Dockerfile --tag $IMAGE_TAG
|
||||||
|
echo "IMAGE_TAG=$IMAGE_TAG" >> $GITHUB_ENV
|
||||||
|
# Uncomment below to push the image to Docker Hub (or another registry)
|
||||||
|
- name: Push the Docker image
|
||||||
|
if: github.event_name == 'push'
|
||||||
|
run: |
|
||||||
|
docker tag $IMAGE_TAG snachodog/kiosk-guestbook:latest
|
||||||
|
docker push snachodog/kiosk-guestbook:latest
|
||||||
|
- name: Notify via ntfy
|
||||||
|
if: github.event_name == 'push'
|
||||||
|
env:
|
||||||
|
NTFY_URL: ${{ secrets.NTFY_URL }}
|
||||||
|
NTFY_TOKEN: ${{ secrets.NTFY_TOKEN }}
|
||||||
|
run: |
|
||||||
|
curl -s -o /dev/null \
|
||||||
|
-H "Title: kiosk-guestbook image pushed to Docker Hub" \
|
||||||
|
-H "Tags: white_check_mark" \
|
||||||
|
-H "Authorization: Bearer $NTFY_TOKEN" \
|
||||||
|
-d "The kiosk-guestbook container has been pushed to Docker Hub and is ready to pull. Commit: ${{ github.sha }} — ${{ github.event.head_commit.message }}" \
|
||||||
|
"$NTFY_URL"
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
name: TODO to Issue
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ "main" ]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
todo:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: alstr/todo-to-issue-action@v5
|
||||||
|
with:
|
||||||
|
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
@@ -184,3 +184,8 @@ cython_debug/
|
|||||||
# VS Code
|
# VS Code
|
||||||
.vscode/
|
.vscode/
|
||||||
|
|
||||||
|
# Claude Code
|
||||||
|
.claude/
|
||||||
|
|
||||||
|
.env
|
||||||
|
docker-compose.yml
|
||||||
|
|||||||
+19
-4
@@ -4,18 +4,33 @@ FROM python:3.9-slim
|
|||||||
# Set the working directory
|
# Set the working directory
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Install dependencies
|
# Install system dependencies (including gettext for envsubst and gosu for privilege dropping)
|
||||||
|
RUN apt-get update && apt-get install -y gettext gosu && rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# Install Python dependencies
|
||||||
COPY requirements.txt .
|
COPY requirements.txt .
|
||||||
RUN pip install --no-cache-dir -r requirements.txt
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
# Copy the application code
|
# Copy the application code and template files
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
|
# Copy the entrypoint script into the container and make it executable
|
||||||
|
COPY entrypoint.sh /entrypoint.sh
|
||||||
|
RUN chmod +x /entrypoint.sh
|
||||||
|
|
||||||
# Set environment variables (can be overridden by .env)
|
# Set environment variables (can be overridden by .env)
|
||||||
ENV FLASK_ENV=production
|
ENV FLASK_ENV=production
|
||||||
|
|
||||||
# Expose the port (Gunicorn will run on 8000)
|
# Expose the port (Gunicorn will run on 8000)
|
||||||
EXPOSE 8000
|
EXPOSE 8000
|
||||||
|
|
||||||
# Run the app with Gunicorn; use 3 workers (can be tuned via .env)
|
# Create a non-root user. UID/GID match the PID/GID vars in example.env (default 1000).
|
||||||
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app:app", "--workers", "3"]
|
# Override at build time with: docker build --build-arg UID=1001 --build-arg GID=1001
|
||||||
|
ARG UID=1000
|
||||||
|
ARG GID=1000
|
||||||
|
RUN groupadd -g ${GID} appuser && useradd -u ${UID} -g ${GID} -s /bin/sh -M appuser
|
||||||
|
RUN chown -R appuser:appuser /app /entrypoint.sh
|
||||||
|
# Entrypoint runs as root, fixes volume permissions, then drops to appuser via gosu
|
||||||
|
|
||||||
|
# Use the entrypoint script as the container's command
|
||||||
|
CMD ["/entrypoint.sh"]
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2025 Montana Dinosaur Center
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -8,38 +8,17 @@ A simple Flask-based guestbook application designed for an internal museum kiosk
|
|||||||
|
|
||||||
- Dynamic Form Behavior:
|
- Dynamic Form Behavior:
|
||||||
The comment field is hidden by default and only revealed when the first name, last name, and location fields each contain at least 3 characters.
|
The comment field is hidden by default and only revealed when the first name, last name, and location fields each contain at least 3 characters.
|
||||||
-Input Validation:
|
- Input Validation:
|
||||||
Ensures required fields (first name, last name, and location) are filled.
|
Ensures required fields (first name, last name, and location) are filled and validates email format (if provided).
|
||||||
- Validates email format (if provided).
|
|
||||||
Uses a profanity filter loaded from en.txt to prevent inappropriate language in comments.
|
Uses a profanity filter loaded from en.txt to prevent inappropriate language in comments.
|
||||||
- Logging:
|
- Logging:
|
||||||
Logs key events and validation errors to help with debugging and monitoring.
|
Logs key events and validation errors for debugging and monitoring.
|
||||||
- SQLite Database:
|
- SQLite Database:
|
||||||
Stores guest entries locally, with persistence ensured by mounting a Docker volume.
|
Stores guest entries locally, with persistence ensured by mounting a Docker volume.
|
||||||
- Containerized Deployment:
|
- Containerized Deployment:
|
||||||
Uses Docker and Docker Compose to create a production-ready environment with Gunicorn as the WSGI server.
|
Uses Docker and Docker Compose for a production-ready environment with Gunicorn as the WSGI server.
|
||||||
|
- Configurable Template:
|
||||||
## Project Structure
|
The application’s title and logo can be dynamically configured via environment variables without rebuilding the image.
|
||||||
|
|
||||||
``` bash
|
|
||||||
kiosk-guestbook/
|
|
||||||
├── scripts/
|
|
||||||
│ ├── guestbook_export.py # Script to export guest entries (e.g., for Mailchimp)
|
|
||||||
│ └── guestbook.db # SQLite database file (if stored here, mainly for development)
|
|
||||||
├── static/
|
|
||||||
│ └── images/
|
|
||||||
│ └── logo.png # Logo for display in the application
|
|
||||||
├── templates/
|
|
||||||
│ └── index.html # Main HTML template for the guestbook
|
|
||||||
├── .env # Environment variables for Docker Compose (production settings)
|
|
||||||
├── app.py # Main Flask application code
|
|
||||||
├── docker-compose.yml # Docker Compose configuration for container orchestration
|
|
||||||
├── Dockerfile # Default Dockerfile (development or general usage)
|
|
||||||
├── en.txt # Profanity list file (one banned word per line)
|
|
||||||
├── production.Dockerfile # Optional Dockerfile optimized for production
|
|
||||||
├── README.md # Project documentation
|
|
||||||
└── requirements.txt # Python dependencies (Flask, Gunicorn, etc.)
|
|
||||||
```
|
|
||||||
|
|
||||||
## Getting Started
|
## Getting Started
|
||||||
|
|
||||||
@@ -47,40 +26,146 @@ kiosk-guestbook/
|
|||||||
|
|
||||||
- Docker
|
- Docker
|
||||||
- Docker Compose
|
- Docker Compose
|
||||||
|
- Optionally, Portainer for GUI-based container management
|
||||||
|
|
||||||
### Building and Running the Application
|
## Running the Application
|
||||||
|
|
||||||
### Build and Start Containers
|
Before proceeding, you’ll need to have the example configuration files. These files—example.docker-compose.yml and example.env—are included in the repository. You can download them by cloning the entire repository:
|
||||||
|
|
||||||
1. From the project root, run:
|
```bash
|
||||||
`docker-compose up --build -d`
|
git clone https://github.com/tmdinosaurcenter/kiosk-guestbook.git
|
||||||
This command will build the Docker image, start the container in detached mode, and mount the persistent volume at `/data` for the SQLite database.
|
cd kiosk-guestbook
|
||||||
|
```
|
||||||
|
|
||||||
2. Access the Application:
|
If you don’t wish to clone the entire repo, you can also download the two files individually from GitHub. Once you have them, follow the steps below.
|
||||||
Open a web browser and navigate to `http://<your-server-ip>:8000` (or the port specified in your .env file).
|
|
||||||
|
|
||||||
### Deployment with Docker Compose
|
### Method 1: Using Docker on the CLI
|
||||||
|
|
||||||
The `docker-compose.yml` is configured to:
|
1. Copy Example Files:
|
||||||
|
From the project root, copy the example files:
|
||||||
|
|
||||||
- Build the image from the Dockerfile.
|
``` bash
|
||||||
- Expose the service on the specified port.
|
cp example.docker-compose.yml docker-compose.yml
|
||||||
- Mount a volume (named `guestbook_data`) at `/data` to persist your database.
|
cp example.env .env
|
||||||
- Load environment variables from the `.env` file
|
```
|
||||||
|
|
||||||
### Logging and Monitoring
|
2. **Edit the `.env` File (Optional)**
|
||||||
|
|
||||||
|
Modify `.env` to customize settings such as `SITE_TITLE`, `LOGO_URL`, `PORT`, etc.
|
||||||
|
|
||||||
|
3. **Start the Application**
|
||||||
|
|
||||||
|
Run the following command to pull (or use) the pre-built image and start the container:
|
||||||
|
|
||||||
|
`docker-compose up -d`
|
||||||
|
|
||||||
|
This command starts the container in detached mode, mounts the persistent volume for the SQLite database, and uses your environment variable settings.
|
||||||
|
|
||||||
|
4. **Access the Application**
|
||||||
|
|
||||||
|
Open your browser and navigate to `http://<your-server-ip>:8000` (or the port specified in your `.env` file).
|
||||||
|
|
||||||
|
### Method 2: Running in Portainer
|
||||||
|
|
||||||
|
1. **Copy Example Files**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp example.docker-compose.yml docker-compose.yml
|
||||||
|
cp example.env stack.env
|
||||||
|
```
|
||||||
|
|
||||||
|
*Note*: Portainer expects the environment file to be named stack.env rather than .env
|
||||||
|
|
||||||
|
2. **Edit `docker-compose.yml`**
|
||||||
|
In the `docker-compose.yml` file, update the environment file reference from `.env` to `stack.env`
|
||||||
|
|
||||||
|
3. **Deploy via Portainer**
|
||||||
|
|
||||||
|
- Log in to Portainer and navigate to the "Stacks" section.
|
||||||
|
- Create a new stack and upload or paste your modified docker-compose.yml along with the `stack.env` file.
|
||||||
|
- Deploy the stack. Portainer will use stack.env for the environment variables.
|
||||||
|
|
||||||
|
4. **Access the Application:**
|
||||||
|
Once deployed, open your browser and navigate to http://<your-server-ip>:8000 (or your specified port) to view the application.
|
||||||
|
|
||||||
|
## Logging and Monitoring
|
||||||
|
|
||||||
- The application uses Python's built-in logging module.
|
- The application uses Python's built-in logging module.
|
||||||
- Key events (like database initialization, form submissions, and validation errors) are logged.
|
- Key events, such as database initialization, form submissions, and validation errors, are logged.
|
||||||
- Logs can be viewed by running:
|
- View logs with:
|
||||||
|
|
||||||
`docker-compose logs -f`
|
`docker-compose logs -f`
|
||||||
|
|
||||||
|
## Admin Interface
|
||||||
|
|
||||||
|
A password-protected admin panel is available at `/admin`. It displays all guest entries in a paginated table and allows individual entries to be deleted. Authentication uses session cookies with an HTML login form — logging out fully invalidates the session so credentials are never cached by the browser.
|
||||||
|
|
||||||
|
Access requires `ADMIN_USER`, `ADMIN_PASSWORD`, and `SECRET_KEY` to be set in your `.env`. If either of the admin credentials are missing the interface returns 503. If `SECRET_KEY` is not set a default development key is used, which is insecure in production — always set your own.
|
||||||
|
|
||||||
|
### Generating a `SECRET_KEY`
|
||||||
|
|
||||||
|
Use Python to generate a cryptographically random key:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -c "import secrets; print(secrets.token_hex(32))"
|
||||||
|
```
|
||||||
|
|
||||||
|
Paste the output as the value for `SECRET_KEY` in your `.env`.
|
||||||
|
|
||||||
|
### User Roles
|
||||||
|
|
||||||
|
The bootstrap superadmin (set via `ADMIN_USER` / `ADMIN_PASSWORD`) can manage additional users at `/admin/users`:
|
||||||
|
|
||||||
|
| Role | View entries | Delete entries | Manage users |
|
||||||
|
| ---------- | :----------: | :------------: | :----------: |
|
||||||
|
| superadmin | ✓ | ✓ | ✓ |
|
||||||
|
| admin | ✓ | ✓ | — |
|
||||||
|
| viewer | ✓ | — | — |
|
||||||
|
|
||||||
|
## API Access
|
||||||
|
|
||||||
|
Access the API endpoint to export guest entries by navigating to:
|
||||||
|
|
||||||
|
`http://your-server-ip:8000/api/guests`
|
||||||
|
|
||||||
|
Set the `API_KEY` variable in your `.env` and pass it in requests as the `X-API-Key` header. This endpoint can be integrated with on-prem automation tools like n8n.
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
|
||||||
|
When upgrading from a previous version, compare your `.env` against `example.env` to check for newly required variables.
|
||||||
|
|
||||||
|
As of **v2.1.0**, the following variables are required for the admin interface:
|
||||||
|
|
||||||
|
```env
|
||||||
|
ADMIN_USER=admin
|
||||||
|
ADMIN_PASSWORD=changeme
|
||||||
|
```
|
||||||
|
|
||||||
|
As of **v2.3.0**, a `SECRET_KEY` is also required for session-based authentication:
|
||||||
|
|
||||||
|
```env
|
||||||
|
SECRET_KEY=your-random-secret-key-here
|
||||||
|
```
|
||||||
|
|
||||||
|
Generate one with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -c "import secrets; print(secrets.token_hex(32))"
|
||||||
|
```
|
||||||
|
|
||||||
|
Replace all placeholder values with your own before deploying.
|
||||||
|
|
||||||
## Additional Notes
|
## Additional Notes
|
||||||
|
|
||||||
- Intranet-Only Deployment:
|
- **Intranet-Only Deployment**
|
||||||
This application is designed for internal use only. It is not exposed to the public internet.
|
This application is designed for internal use only and is not exposed to the public internet.
|
||||||
- Database Persistence:
|
|
||||||
The SQLite database is stored in a Docker volume (guestbook_data), ensuring that data persists even if containers are rebuilt.
|
|
||||||
- Production Considerations:
|
|
||||||
|
|
||||||
The app runs with Gunicorn as a production-ready WSGI server. Make sure to adjust worker counts and resource limits as needed based on your server’s specifications.
|
- **Database Persistence**
|
||||||
|
The SQLite database is stored in a Docker volume (guestbook_data), ensuring that data persists even if containers are rebuilt.
|
||||||
|
|
||||||
|
- **Production Considerations**
|
||||||
|
The app runs with Gunicorn as a production-ready WSGI server. Adjust worker counts and resource limits as needed based on your server’s specifications.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
This project is licensed under the [MIT License](LICENSE).
|
||||||
|
|||||||
@@ -1,24 +1,71 @@
|
|||||||
from flask import Flask, render_template, request, redirect, url_for
|
|
||||||
import sqlite3
|
|
||||||
import re
|
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
|
import sqlite3
|
||||||
|
|
||||||
# Set up basic logging
|
from email_validator import validate_email, EmailNotValidError
|
||||||
|
from flask import Flask, render_template, request, redirect, url_for, jsonify, abort
|
||||||
|
from flask_limiter import Limiter
|
||||||
|
from flask_limiter.util import get_remote_address
|
||||||
|
from flask_login import (
|
||||||
|
LoginManager, UserMixin, login_user, logout_user, login_required, current_user
|
||||||
|
)
|
||||||
|
from werkzeug.security import generate_password_hash, check_password_hash
|
||||||
|
|
||||||
|
# Set up logging
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
|
|
||||||
# Use an environment variable for the database path (defaulting to 'guestbook.db')
|
|
||||||
DATABASE = os.environ.get('DATABASE_PATH', 'guestbook.db')
|
DATABASE = os.environ.get('DATABASE_PATH', 'guestbook.db')
|
||||||
|
app.secret_key = os.environ.get('SECRET_KEY', 'dev-secret-key-change-in-production')
|
||||||
|
|
||||||
|
limiter = Limiter(get_remote_address, app=app, default_limits=[])
|
||||||
|
|
||||||
|
login_manager = LoginManager(app)
|
||||||
|
login_manager.login_view = 'admin_login'
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# User model
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class User(UserMixin):
|
||||||
|
"""Lightweight user object stored in the session."""
|
||||||
|
def __init__(self, user_id, username, role):
|
||||||
|
# user_id format: 's:<username>' for superadmin, 'u:<db_id>' for DB users
|
||||||
|
self.id = user_id
|
||||||
|
self.username = username
|
||||||
|
self.role = role
|
||||||
|
|
||||||
|
|
||||||
|
@login_manager.user_loader
|
||||||
|
def load_user(user_id):
|
||||||
|
if user_id.startswith('s:'):
|
||||||
|
username = user_id[2:]
|
||||||
|
admin_user = os.environ.get('ADMIN_USER')
|
||||||
|
if admin_user and username == admin_user:
|
||||||
|
return User(user_id, username, 'superadmin')
|
||||||
|
return None
|
||||||
|
if user_id.startswith('u:'):
|
||||||
|
db_id = user_id[2:]
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(DATABASE)
|
||||||
|
c = conn.cursor()
|
||||||
|
row = c.execute(
|
||||||
|
'SELECT id, username, role FROM users WHERE id = ?', (db_id,)
|
||||||
|
).fetchone()
|
||||||
|
conn.close()
|
||||||
|
if row:
|
||||||
|
return User(f'u:{row[0]}', row[1], row[2])
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
logger.error("Database error in user_loader: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Profanity filter
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
def load_banned_words():
|
def load_banned_words():
|
||||||
"""Load a set of banned words from a local file.
|
|
||||||
|
|
||||||
Expects 'en.txt' to be in the same directory as this script.
|
|
||||||
If the file is missing, a minimal fallback set is used.
|
|
||||||
"""
|
|
||||||
banned_words = set()
|
banned_words = set()
|
||||||
file_path = os.path.join(os.path.dirname(__file__), 'en.txt')
|
file_path = os.path.join(os.path.dirname(__file__), 'en.txt')
|
||||||
if os.path.exists(file_path):
|
if os.path.exists(file_path):
|
||||||
@@ -33,102 +80,368 @@ def load_banned_words():
|
|||||||
logger.error("Error reading banned words file: %s", e)
|
logger.error("Error reading banned words file: %s", e)
|
||||||
banned_words = {"fuck", "shit", "damn", "bitch", "asshole", "cunt", "dick", "piss", "crap", "hell"}
|
banned_words = {"fuck", "shit", "damn", "bitch", "asshole", "cunt", "dick", "piss", "crap", "hell"}
|
||||||
else:
|
else:
|
||||||
logger.warning("Banned words file not found. Using fallback minimal list.")
|
logger.warning("Banned words file not found. Using fallback list.")
|
||||||
banned_words = {"fuck", "shit", "damn", "bitch", "asshole", "cunt", "dick", "piss", "crap", "hell"}
|
banned_words = {"fuck", "shit", "damn", "bitch", "asshole", "cunt", "dick", "piss", "crap", "hell"}
|
||||||
return banned_words
|
return banned_words
|
||||||
|
|
||||||
# Load the banned words using the helper function.
|
|
||||||
BANNED_WORDS = load_banned_words()
|
BANNED_WORDS = load_banned_words()
|
||||||
|
|
||||||
def contains_banned_words(text):
|
def contains_banned_words(text):
|
||||||
"""Check if the provided text contains any banned words."""
|
lower = text.lower()
|
||||||
words = text.lower().split()
|
# Whole-word check (punctuation-stripped) — catches exact matches
|
||||||
for word in words:
|
for word in lower.split():
|
||||||
word_clean = word.strip(".,!?;:\"'")
|
if word.strip(".,!?;:\"'") in BANNED_WORDS:
|
||||||
if word_clean in BANNED_WORDS:
|
return True
|
||||||
|
# Normalized substring check — catches spacing tricks (f u c k) and
|
||||||
|
# embedded forms (fucking). Note: may produce false positives on words
|
||||||
|
# that contain a banned word as a substring (e.g. "classic" → "ass").
|
||||||
|
normalized = re.sub(r'[^a-z]', '', lower)
|
||||||
|
for banned in BANNED_WORDS:
|
||||||
|
if banned in normalized:
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def init_db():
|
# ---------------------------------------------------------------------------
|
||||||
"""Initialize the SQLite database and create the guests table if it doesn't exist."""
|
# Database migrations
|
||||||
conn = sqlite3.connect(DATABASE)
|
# ---------------------------------------------------------------------------
|
||||||
c = conn.cursor()
|
|
||||||
c.execute('''
|
# Each entry is a list of SQL statements for that schema version.
|
||||||
CREATE TABLE IF NOT EXISTS guests (
|
# To add a column or index in the future, append a new list — never modify existing entries.
|
||||||
|
MIGRATIONS = [
|
||||||
|
# v1 — initial schema
|
||||||
|
[
|
||||||
|
'''CREATE TABLE IF NOT EXISTS guests (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
first_name TEXT NOT NULL,
|
first_name TEXT NOT NULL,
|
||||||
last_name TEXT NOT NULL,
|
last_name TEXT NOT NULL,
|
||||||
email TEXT,
|
email TEXT,
|
||||||
location TEXT NOT NULL,
|
location TEXT NOT NULL,
|
||||||
comment TEXT,
|
comment TEXT,
|
||||||
|
newsletter_opt_in BOOLEAN DEFAULT 1,
|
||||||
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
|
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
)
|
)''',
|
||||||
''')
|
'CREATE INDEX IF NOT EXISTS idx_guests_id ON guests (id DESC)',
|
||||||
conn.commit()
|
'CREATE INDEX IF NOT EXISTS idx_guests_email ON guests (email)',
|
||||||
|
],
|
||||||
|
# v2 — user accounts for admin interface (role: 'admin' or 'viewer')
|
||||||
|
[
|
||||||
|
'''CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
username TEXT NOT NULL UNIQUE,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
role TEXT NOT NULL CHECK(role IN ('admin', 'viewer'))
|
||||||
|
)''',
|
||||||
|
],
|
||||||
|
]
|
||||||
|
|
||||||
|
def migrate_db():
|
||||||
|
conn = sqlite3.connect(DATABASE)
|
||||||
|
c = conn.cursor()
|
||||||
|
|
||||||
|
# Bootstrap the version table and seed it at 0 if empty
|
||||||
|
c.execute('CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)')
|
||||||
|
if c.execute('SELECT COUNT(*) FROM schema_version').fetchone()[0] == 0:
|
||||||
|
c.execute('INSERT INTO schema_version VALUES (0)')
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
current = c.execute('SELECT version FROM schema_version').fetchone()[0]
|
||||||
|
pending = MIGRATIONS[current:]
|
||||||
|
|
||||||
|
if not pending:
|
||||||
|
logger.info("Database schema is up to date at v%d.", current)
|
||||||
|
conn.close()
|
||||||
|
return
|
||||||
|
|
||||||
|
for statements in pending:
|
||||||
|
current += 1
|
||||||
|
logger.info("Applying migration v%d...", current)
|
||||||
|
for sql in statements:
|
||||||
|
c.execute(sql)
|
||||||
|
c.execute('UPDATE schema_version SET version = ?', (current,))
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
logger.info("Database migrated to v%d.", current)
|
||||||
conn.close()
|
conn.close()
|
||||||
logger.info("Database initialized.")
|
|
||||||
|
|
||||||
def is_valid_email(email):
|
def is_valid_email(email):
|
||||||
"""Simple regex-based email validation."""
|
try:
|
||||||
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
|
validate_email(email, check_deliverability=False)
|
||||||
return re.match(pattern, email)
|
return True
|
||||||
|
except EmailNotValidError:
|
||||||
|
return False
|
||||||
|
|
||||||
@app.before_first_request
|
with app.app_context():
|
||||||
def initialize_database():
|
migrate_db()
|
||||||
"""Ensure the database is initialized before handling the first request."""
|
|
||||||
init_db()
|
# ---------------------------------------------------------------------------
|
||||||
|
# Public routes
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
@app.route('/', methods=['GET', 'POST'])
|
@app.route('/', methods=['GET', 'POST'])
|
||||||
|
@limiter.limit("5 per minute", methods=["POST"])
|
||||||
def index():
|
def index():
|
||||||
error = None
|
error = None
|
||||||
if request.method == 'POST':
|
if request.method == 'POST':
|
||||||
logger.info("Received POST request with form data.")
|
logger.info("Received POST request.")
|
||||||
first_name = request.form.get('first_name', '').strip()
|
first_name = request.form.get('first_name', '').strip()
|
||||||
last_name = request.form.get('last_name', '').strip()
|
last_name = request.form.get('last_name', '').strip()
|
||||||
email = request.form.get('email', '').strip()
|
email = request.form.get('email', '').strip()
|
||||||
location = request.form.get('location', '').strip()
|
location = request.form.get('location', '').strip()
|
||||||
comment = request.form.get('comment', '').strip()
|
comment = request.form.get('comment', '').strip()
|
||||||
|
newsletter_opt_in = request.form.get('newsletter_opt_in') == 'on'
|
||||||
|
|
||||||
if not (first_name and last_name and location):
|
if not (first_name and last_name and location):
|
||||||
error = "First name, last name, and location are required."
|
error = "First name, last name, and location are required."
|
||||||
logger.warning("Validation error: Missing required fields.")
|
logger.warning("Missing required fields.")
|
||||||
elif email and not is_valid_email(email):
|
elif email and not is_valid_email(email):
|
||||||
error = "Invalid email address."
|
error = "Invalid email address."
|
||||||
logger.warning("Validation error: Invalid email address '%s'.", email)
|
logger.warning("Invalid email: %s", email)
|
||||||
elif comment and contains_banned_words(comment):
|
elif comment and contains_banned_words(comment):
|
||||||
error = "Your comment contains inappropriate language. Please revise."
|
error = "Your comment contains inappropriate language. Please revise."
|
||||||
logger.warning("Validation error: Inappropriate language detected in comment.")
|
logger.warning("Profanity detected in comment.")
|
||||||
|
|
||||||
if error:
|
if error:
|
||||||
conn = sqlite3.connect(DATABASE)
|
try:
|
||||||
c = conn.cursor()
|
conn = sqlite3.connect(DATABASE)
|
||||||
c.execute('SELECT first_name, location FROM guests ORDER BY id DESC')
|
c = conn.cursor()
|
||||||
guests = c.fetchall()
|
c.execute('SELECT first_name, location FROM guests ORDER BY id DESC LIMIT 100')
|
||||||
conn.close()
|
guests = c.fetchall()
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
logger.error("Database error loading guests: %s", e)
|
||||||
|
guests = []
|
||||||
return render_template('index.html', error=error, guests=guests)
|
return render_template('index.html', error=error, guests=guests)
|
||||||
|
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(DATABASE)
|
||||||
|
c = conn.cursor()
|
||||||
|
c.execute(
|
||||||
|
'''
|
||||||
|
INSERT INTO guests (first_name, last_name, email, location, comment, newsletter_opt_in)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)
|
||||||
|
''',
|
||||||
|
(first_name, last_name, email, location, comment, newsletter_opt_in)
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
logger.error("Database error saving guest: %s", e)
|
||||||
|
return render_template('index.html',
|
||||||
|
error="Unable to save your entry. Please try again.",
|
||||||
|
guests=[])
|
||||||
|
logger.info("Added guest: %s %s from %s", first_name, last_name, location)
|
||||||
|
return redirect(url_for('index'))
|
||||||
|
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(DATABASE)
|
||||||
|
c = conn.cursor()
|
||||||
|
c.execute('SELECT first_name, location FROM guests ORDER BY id DESC LIMIT 100')
|
||||||
|
guests = c.fetchall()
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
logger.error("Database error loading guests: %s", e)
|
||||||
|
guests = []
|
||||||
|
logger.info("Rendering index with %d guests.", len(guests))
|
||||||
|
return render_template('index.html', error=error, guests=guests)
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Admin auth routes
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _admin_configured():
|
||||||
|
return bool(os.environ.get('ADMIN_USER') and os.environ.get('ADMIN_PASSWORD'))
|
||||||
|
|
||||||
|
@app.route('/admin/login', methods=['GET', 'POST'])
|
||||||
|
def admin_login():
|
||||||
|
if not _admin_configured():
|
||||||
|
abort(503)
|
||||||
|
if current_user.is_authenticated:
|
||||||
|
return redirect(url_for('admin'))
|
||||||
|
error = None
|
||||||
|
if request.method == 'POST':
|
||||||
|
username = request.form.get('username', '').strip()
|
||||||
|
password = request.form.get('password', '').strip()
|
||||||
|
admin_user = os.environ.get('ADMIN_USER')
|
||||||
|
admin_password = os.environ.get('ADMIN_PASSWORD')
|
||||||
|
# Check superadmin first
|
||||||
|
if admin_user and username == admin_user and password == admin_password:
|
||||||
|
login_user(User(f's:{username}', username, 'superadmin'))
|
||||||
|
logger.info("Superadmin '%s' logged in.", username)
|
||||||
|
return redirect(request.args.get('next') or url_for('admin'))
|
||||||
|
# Check DB users
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(DATABASE)
|
||||||
|
c = conn.cursor()
|
||||||
|
row = c.execute(
|
||||||
|
'SELECT id, password_hash, role FROM users WHERE username = ?', (username,)
|
||||||
|
).fetchone()
|
||||||
|
conn.close()
|
||||||
|
if row and check_password_hash(row[1], password):
|
||||||
|
login_user(User(f'u:{row[0]}', username, row[2]))
|
||||||
|
logger.info("User '%s' (role=%s) logged in.", username, row[2])
|
||||||
|
return redirect(request.args.get('next') or url_for('admin'))
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
logger.error("Database error during login: %s", e)
|
||||||
|
error = 'Invalid username or password.'
|
||||||
|
logger.warning("Failed login attempt for username '%s'.", username)
|
||||||
|
return render_template('admin_login.html', error=error)
|
||||||
|
|
||||||
|
@app.route('/admin/logout')
|
||||||
|
def admin_logout():
|
||||||
|
logout_user()
|
||||||
|
return redirect(url_for('admin_login'))
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Admin routes
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@app.route('/admin')
|
||||||
|
@login_required
|
||||||
|
def admin():
|
||||||
|
if not _admin_configured():
|
||||||
|
abort(503)
|
||||||
|
page = request.args.get('page', 1, type=int)
|
||||||
|
per_page = 25
|
||||||
|
offset = (page - 1) * per_page
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(DATABASE)
|
||||||
|
c = conn.cursor()
|
||||||
|
total = c.execute('SELECT COUNT(*) FROM guests').fetchone()[0]
|
||||||
|
c.execute('''
|
||||||
|
SELECT id, first_name, last_name, email, location, comment, newsletter_opt_in, timestamp
|
||||||
|
FROM guests ORDER BY id DESC LIMIT ? OFFSET ?
|
||||||
|
''', (per_page, offset))
|
||||||
|
guests = c.fetchall()
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
logger.error("Database error in admin: %s", e)
|
||||||
|
guests = []
|
||||||
|
total = 0
|
||||||
|
total_pages = (total + per_page - 1) // per_page
|
||||||
|
return render_template('admin.html', guests=guests, page=page, total_pages=total_pages,
|
||||||
|
total=total)
|
||||||
|
|
||||||
|
@app.route('/admin/delete/<int:entry_id>', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
def admin_delete(entry_id):
|
||||||
|
if not _admin_configured():
|
||||||
|
abort(503)
|
||||||
|
if current_user.role == 'viewer':
|
||||||
|
abort(403)
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(DATABASE)
|
||||||
|
c = conn.cursor()
|
||||||
|
c.execute('DELETE FROM guests WHERE id = ?', (entry_id,))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
logger.info("Admin deleted guest entry id=%d", entry_id)
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
logger.error("Database error deleting guest %d: %s", entry_id, e)
|
||||||
|
return redirect(url_for('admin', page=request.args.get('page', 1)))
|
||||||
|
|
||||||
|
@app.route('/admin/users')
|
||||||
|
@login_required
|
||||||
|
def admin_users():
|
||||||
|
if not _admin_configured():
|
||||||
|
abort(503)
|
||||||
|
if current_user.role != 'superadmin':
|
||||||
|
abort(403)
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(DATABASE)
|
||||||
|
c = conn.cursor()
|
||||||
|
users = c.execute('SELECT id, username, role FROM users ORDER BY username').fetchall()
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
logger.error("Database error in admin_users: %s", e)
|
||||||
|
users = []
|
||||||
|
return render_template('admin_users.html', users=users)
|
||||||
|
|
||||||
|
@app.route('/admin/users/add', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
def admin_users_add():
|
||||||
|
if not _admin_configured():
|
||||||
|
abort(503)
|
||||||
|
if current_user.role != 'superadmin':
|
||||||
|
abort(403)
|
||||||
|
username = request.form.get('username', '').strip()
|
||||||
|
password = request.form.get('password', '').strip()
|
||||||
|
role = request.form.get('role', '').strip()
|
||||||
|
if not username or not password or role not in ('admin', 'viewer'):
|
||||||
|
return redirect(url_for('admin_users'))
|
||||||
|
try:
|
||||||
conn = sqlite3.connect(DATABASE)
|
conn = sqlite3.connect(DATABASE)
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute(
|
c.execute(
|
||||||
'INSERT INTO guests (first_name, last_name, email, location, comment) VALUES (?, ?, ?, ?, ?)',
|
'INSERT INTO users (username, password_hash, role) VALUES (?, ?, ?)',
|
||||||
(first_name, last_name, email, location, comment)
|
(username, generate_password_hash(password), role)
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
logger.info("New guest entry added: %s from %s.", first_name, location)
|
logger.info("Superadmin added user '%s' with role '%s'", username, role)
|
||||||
return redirect(url_for('index'))
|
except sqlite3.IntegrityError:
|
||||||
|
logger.warning("Attempted to add duplicate username '%s'", username)
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
logger.error("Database error adding user: %s", e)
|
||||||
|
return redirect(url_for('admin_users'))
|
||||||
|
|
||||||
# For GET requests, retrieve guest entries to display.
|
@app.route('/admin/users/delete/<int:user_id>', methods=['POST'])
|
||||||
conn = sqlite3.connect(DATABASE)
|
@login_required
|
||||||
c = conn.cursor()
|
def admin_users_delete(user_id):
|
||||||
c.execute('SELECT first_name, location FROM guests ORDER BY id DESC')
|
if not _admin_configured():
|
||||||
guests = c.fetchall()
|
abort(503)
|
||||||
conn.close()
|
if current_user.role != 'superadmin':
|
||||||
logger.info("Rendering guestbook page with %d entries.", len(guests))
|
abort(403)
|
||||||
return render_template('index.html', error=error, guests=guests)
|
try:
|
||||||
|
conn = sqlite3.connect(DATABASE)
|
||||||
|
c = conn.cursor()
|
||||||
|
c.execute('DELETE FROM users WHERE id = ?', (user_id,))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
logger.info("Superadmin deleted user id=%d", user_id)
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
logger.error("Database error deleting user %d: %s", user_id, e)
|
||||||
|
return redirect(url_for('admin_users'))
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# API
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@app.route('/api/guests', methods=['GET'])
|
||||||
|
def api_guests():
|
||||||
|
api_key = request.headers.get('X-API-Key')
|
||||||
|
if api_key != os.environ.get("API_KEY"):
|
||||||
|
abort(403)
|
||||||
|
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(DATABASE)
|
||||||
|
c = conn.cursor()
|
||||||
|
c.execute('''
|
||||||
|
SELECT first_name, last_name, email, location, comment, newsletter_opt_in, timestamp
|
||||||
|
FROM guests
|
||||||
|
WHERE email IS NOT NULL AND email != ''
|
||||||
|
ORDER BY id DESC
|
||||||
|
''')
|
||||||
|
rows = c.fetchall()
|
||||||
|
conn.close()
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
logger.error("Database error in api_guests: %s", e)
|
||||||
|
return jsonify({"error": "Database unavailable"}), 503
|
||||||
|
|
||||||
|
guests = [
|
||||||
|
{
|
||||||
|
"first_name": row[0],
|
||||||
|
"last_name": row[1],
|
||||||
|
"email": row[2],
|
||||||
|
"location": row[3],
|
||||||
|
"comment": row[4],
|
||||||
|
"newsletter_opt_in": bool(row[5]),
|
||||||
|
"timestamp": row[6]
|
||||||
|
}
|
||||||
|
for row in rows
|
||||||
|
]
|
||||||
|
return jsonify(guests)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
# For development use; production (gunicorn) will not execute this block.
|
migrate_db()
|
||||||
init_db()
|
logger.info("Starting development server at http://0.0.0.0:8000")
|
||||||
logger.info("Starting Flask app on host 0.0.0.0, port 8000.")
|
|
||||||
app.run(host='0.0.0.0', port=8000)
|
app.run(host='0.0.0.0', port=8000)
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Fix ownership of the data directory so appuser can write the database.
|
||||||
|
# This runs as root (no USER directive in Dockerfile) and is safe because
|
||||||
|
# we immediately drop privileges via gosu before starting the app.
|
||||||
|
DATA_DIR=$(dirname "${DATABASE_PATH:-/data/guestbook.db}")
|
||||||
|
chown -R appuser:appuser "$DATA_DIR"
|
||||||
|
|
||||||
|
# Process index.html.template to create index.html
|
||||||
|
envsubst < /app/templates/index.html.template > /app/templates/index.html
|
||||||
|
|
||||||
|
# Drop to appuser and start Gunicorn
|
||||||
|
exec gosu appuser gunicorn --bind 0.0.0.0:8000 app:app --workers ${GUNICORN_WORKERS:-3}
|
||||||
@@ -1,15 +1,15 @@
|
|||||||
version: "3.8"
|
version: "3.8"
|
||||||
services:
|
services:
|
||||||
guestbook:
|
guestbook:
|
||||||
build: .
|
image: snachodog/kiosk-guestbook:latest
|
||||||
container_name: guestbook
|
container_name: guestbook
|
||||||
ports:
|
ports:
|
||||||
- "${PORT:-8000}:8000"
|
- "${PORT:-8000}:8000"
|
||||||
env_file:
|
env_file:
|
||||||
- .env
|
- .env
|
||||||
volumes:
|
volumes:
|
||||||
# Mount a named volume at /data so that the database file (configured in .env) persists
|
# Mount your local directory to persist data; adjust if you prefer a named volume
|
||||||
- /home/steve/kiosk-guestbook:/data
|
- /path/to/guestbook_data:/data
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
guestbook_data:
|
guestbook_data:
|
||||||
+6
-2
@@ -3,9 +3,13 @@ PORT=8000
|
|||||||
# Flask environment setting (production)
|
# Flask environment setting (production)
|
||||||
FLASK_ENV=production
|
FLASK_ENV=production
|
||||||
# Path to the SQLite database (this file will be stored in the mounted /data volume)
|
# Path to the SQLite database (this file will be stored in the mounted /data volume)
|
||||||
DATABASE_PATH=/data/scripts/guestbook.db
|
DATABASE_PATH=/data/guestbook.db
|
||||||
# Number of Gunicorn workers (adjust as needed)
|
# Number of Gunicorn workers (adjust as needed)
|
||||||
GUNICORN_WORKERS=3
|
GUNICORN_WORKERS=3
|
||||||
PID=1000
|
PID=1000
|
||||||
GID=1000
|
GID=1000
|
||||||
|
SITE_TITLE="The Montana Dinosaur Center Visitor Log"
|
||||||
|
LOGO_URL="/static/images/logo.png"
|
||||||
|
ADMIN_USER=admin
|
||||||
|
ADMIN_PASSWORD=changeme
|
||||||
|
SECRET_KEY=change-this-to-a-random-secret-key
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
FROM python:3.9-slim
|
|
||||||
|
|
||||||
WORKDIR /app
|
|
||||||
|
|
||||||
# Copy and install Python dependencies.
|
|
||||||
COPY requirements.txt requirements.txt
|
|
||||||
RUN pip install --no-cache-dir -r requirements.txt
|
|
||||||
|
|
||||||
# Copy the rest of the app code.
|
|
||||||
COPY . .
|
|
||||||
|
|
||||||
EXPOSE 5000
|
|
||||||
|
|
||||||
CMD ["python", "app.py"]
|
|
||||||
+4
-1
@@ -1,3 +1,6 @@
|
|||||||
Flask==2.2.5
|
Flask>=3.1.3
|
||||||
Werkzeug>=3.0.6
|
Werkzeug>=3.0.6
|
||||||
|
Flask-Limiter>=3.0
|
||||||
|
Flask-Login>=0.6
|
||||||
|
email-validator>=2.0
|
||||||
gunicorn
|
gunicorn
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import csv
|
import csv
|
||||||
|
import os
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
|
||||||
# Update the database file path if needed.
|
DATABASE = os.environ.get('DATABASE_PATH', 'guestbook.db')
|
||||||
DATABASE = 'guestbook.db'
|
|
||||||
EXPORT_FILE = 'mailchimp_export.csv'
|
EXPORT_FILE = 'mailchimp_export.csv'
|
||||||
|
|
||||||
def export_guestbook_to_csv():
|
def export_guestbook_to_csv():
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Guestbook Admin</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||||
|
</head>
|
||||||
|
<body class="bg-light">
|
||||||
|
<div class="container py-4">
|
||||||
|
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||||
|
<h1 class="h3 mb-0">Guestbook Admin</h1>
|
||||||
|
<div class="d-flex align-items-center gap-3">
|
||||||
|
<span class="text-muted">{{ current_user.username }} · {{ total }} entries</span>
|
||||||
|
{% if current_user.role == 'superadmin' %}
|
||||||
|
<a href="{{ url_for('admin_users') }}" class="btn btn-outline-secondary btn-sm">Manage Users</a>
|
||||||
|
{% endif %}
|
||||||
|
<a href="{{ url_for('admin_logout') }}" class="btn btn-outline-danger btn-sm">Logout</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-bordered table-hover bg-white">
|
||||||
|
<thead class="table-dark">
|
||||||
|
<tr>
|
||||||
|
<th>ID</th>
|
||||||
|
<th>Name</th>
|
||||||
|
<th>Email</th>
|
||||||
|
<th>Location</th>
|
||||||
|
<th>Comment</th>
|
||||||
|
<th>Newsletter</th>
|
||||||
|
<th>Timestamp</th>
|
||||||
|
<th></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for g in guests %}
|
||||||
|
<tr>
|
||||||
|
<td class="text-muted">{{ g[0] }}</td>
|
||||||
|
<td>{{ g[1] }} {{ g[2] }}</td>
|
||||||
|
<td>{{ g[3] or '—' }}</td>
|
||||||
|
<td>{{ g[4] }}</td>
|
||||||
|
<td>{{ g[5] or '—' }}</td>
|
||||||
|
<td>{{ 'Yes' if g[6] else 'No' }}</td>
|
||||||
|
<td class="text-nowrap">{{ g[7] }}</td>
|
||||||
|
<td>
|
||||||
|
{% if current_user.role != 'viewer' %}
|
||||||
|
<form method="POST" action="{{ url_for('admin_delete', entry_id=g[0]) }}?page={{ page }}"
|
||||||
|
onsubmit="return confirm('Delete entry for {{ g[1] }} {{ g[2] }}?')">
|
||||||
|
<button type="submit" class="btn btn-danger btn-sm">Delete</button>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr>
|
||||||
|
<td colspan="8" class="text-center text-muted">No entries found.</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if total_pages > 1 %}
|
||||||
|
<nav>
|
||||||
|
<ul class="pagination">
|
||||||
|
<li class="page-item {% if page == 1 %}disabled{% endif %}">
|
||||||
|
<a class="page-link" href="{{ url_for('admin', page=page-1) }}">Previous</a>
|
||||||
|
</li>
|
||||||
|
{% for p in range(1, total_pages + 1) %}
|
||||||
|
<li class="page-item {% if p == page %}active{% endif %}">
|
||||||
|
<a class="page-link" href="{{ url_for('admin', page=p) }}">{{ p }}</a>
|
||||||
|
</li>
|
||||||
|
{% endfor %}
|
||||||
|
<li class="page-item {% if page == total_pages %}disabled{% endif %}">
|
||||||
|
<a class="page-link" href="{{ url_for('admin', page=page+1) }}">Next</a>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</nav>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Guestbook Admin — Login</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||||
|
</head>
|
||||||
|
<body class="bg-light">
|
||||||
|
<div class="container py-5" style="max-width: 400px;">
|
||||||
|
<h1 class="h4 mb-4 text-center">Admin Login</h1>
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-body">
|
||||||
|
{% if error %}
|
||||||
|
<div class="alert alert-danger py-2">{{ error }}</div>
|
||||||
|
{% endif %}
|
||||||
|
<form method="POST" action="{{ url_for('admin_login', next=request.args.get('next', '')) }}">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="username" class="form-label">Username</label>
|
||||||
|
<input type="text" id="username" name="username" class="form-control"
|
||||||
|
autocomplete="username" required autofocus />
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="password" class="form-label">Password</label>
|
||||||
|
<input type="password" id="password" name="password" class="form-control"
|
||||||
|
autocomplete="current-password" required />
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn btn-primary w-100">Log In</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Guestbook Admin — Users</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||||
|
</head>
|
||||||
|
<body class="bg-light">
|
||||||
|
<div class="container py-4" style="max-width: 700px;">
|
||||||
|
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||||
|
<h1 class="h3 mb-0">User Management</h1>
|
||||||
|
<div class="d-flex gap-2">
|
||||||
|
<a href="{{ url_for('admin') }}" class="btn btn-outline-secondary btn-sm">Back to Entries</a>
|
||||||
|
<a href="{{ url_for('admin_logout') }}" class="btn btn-outline-danger btn-sm">Logout</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card mb-4">
|
||||||
|
<div class="card-header">Add User</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<form method="POST" action="{{ url_for('admin_users_add') }}">
|
||||||
|
<div class="row g-2">
|
||||||
|
<div class="col-sm-4">
|
||||||
|
<input type="text" name="username" class="form-control" placeholder="Username" required />
|
||||||
|
</div>
|
||||||
|
<div class="col-sm-4">
|
||||||
|
<input type="password" name="password" class="form-control" placeholder="Password" required />
|
||||||
|
</div>
|
||||||
|
<div class="col-sm-2">
|
||||||
|
<select name="role" class="form-select">
|
||||||
|
<option value="viewer">Viewer</option>
|
||||||
|
<option value="admin">Admin</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="col-sm-2">
|
||||||
|
<button type="submit" class="btn btn-primary w-100">Add</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<table class="table table-bordered bg-white">
|
||||||
|
<thead class="table-dark">
|
||||||
|
<tr>
|
||||||
|
<th>Username</th>
|
||||||
|
<th>Role</th>
|
||||||
|
<th></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for u in users %}
|
||||||
|
<tr>
|
||||||
|
<td>{{ u[1] }}</td>
|
||||||
|
<td><span class="badge bg-{{ 'danger' if u[2] == 'admin' else 'secondary' }}">{{ u[2] }}</span></td>
|
||||||
|
<td>
|
||||||
|
<form method="POST" action="{{ url_for('admin_users_delete', user_id=u[0]) }}"
|
||||||
|
onsubmit="return confirm('Remove user {{ u[1] }}?')">
|
||||||
|
<button type="submit" class="btn btn-danger btn-sm">Remove</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr>
|
||||||
|
<td colspan="3" class="text-center text-muted">No users added yet.</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<p class="text-muted small">
|
||||||
|
These accounts are in addition to the bootstrap superadmin configured in <code>.env</code>.
|
||||||
|
Admins can view and delete entries. Viewers can only view.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -2,11 +2,12 @@
|
|||||||
<html lang="en">
|
<html lang="en">
|
||||||
|
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<title>The Montana Dinosaur Center Visitor Log</title>
|
<title>${SITE_TITLE}</title>
|
||||||
|
|
||||||
<!-- Bootstrap CSS -->
|
<!-- Bootstrap CSS -->
|
||||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||||
<style>
|
<style>
|
||||||
/* Scrolling marquee styles */
|
/* Scrolling marquee styles */
|
||||||
.scrolling-wrapper {
|
.scrolling-wrapper {
|
||||||
@@ -22,16 +23,17 @@
|
|||||||
.scrolling-content {
|
.scrolling-content {
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
padding: 10px;
|
padding: 10px;
|
||||||
animation: scroll-left 20s linear infinite;
|
font-size: 1.25rem;
|
||||||
|
animation: scroll-left linear infinite;
|
||||||
}
|
}
|
||||||
|
|
||||||
@keyframes scroll-left {
|
@keyframes scroll-left {
|
||||||
0% {
|
0% {
|
||||||
transform: translateX(100%);
|
transform: translateX(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
100% {
|
100% {
|
||||||
transform: translateX(-100%);
|
transform: translateX(-50%);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
@@ -40,8 +42,8 @@
|
|||||||
<body>
|
<body>
|
||||||
<div class="container mt-5 mb-5">
|
<div class="container mt-5 mb-5">
|
||||||
<header class="d-flex align-items-center mb-4">
|
<header class="d-flex align-items-center mb-4">
|
||||||
<img src="static/images/logo.png" alt="Museum Logo" class="me-3" style="height: 50px;">
|
<img src="${LOGO_URL}" alt="Logo" class="me-3" style="height: 50px;" />
|
||||||
<h1 class="h3 mb-0">The Montana Dinosaur Center Visitor Log</h1>
|
<h1 class="h3 mb-0">${SITE_TITLE}</h1>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<!-- Brief instructions for the form -->
|
<!-- Brief instructions for the form -->
|
||||||
@@ -59,61 +61,99 @@
|
|||||||
<form method="post" action="/" class="mb-4">
|
<form method="post" action="/" class="mb-4">
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="first_name" class="form-label">First Name(s):</label>
|
<label for="first_name" class="form-label">First Name(s):</label>
|
||||||
<input type="text" class="form-control" id="first_name" name="first_name" required>
|
<input type="text" class="form-control" id="first_name" name="first_name" required />
|
||||||
</div>
|
</div>
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="last_name" class="form-label">Last Name:</label>
|
<label for="last_name" class="form-label">Last Name:</label>
|
||||||
<input type="text" class="form-control" id="last_name" name="last_name" required>
|
<input type="text" class="form-control" id="last_name" name="last_name" required />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Email + Newsletter Block (fully fixed) -->
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="email" class="form-label">Email (Optional):</label>
|
<label for="email" class="form-label">Email (Optional):</label>
|
||||||
<input type="email" class="form-control" id="email" name="email">
|
<input type="email" class="form-control" id="email" name="email" />
|
||||||
|
|
||||||
|
<div class="form-check mt-2">
|
||||||
|
<input class="form-check-input" type="checkbox" name="newsletter_opt_in" id="newsletter_opt_in"
|
||||||
|
checked />
|
||||||
|
<label class="form-check-label" for="newsletter_opt_in">
|
||||||
|
Subscribe our newsletter
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="location" class="form-label">Location:</label>
|
<label for="location" class="form-label">Location:</label>
|
||||||
<input type="text" class="form-control" id="location" name="location" required>
|
<input type="text" class="form-control" id="location" name="location" required />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Comment field hidden by default -->
|
<!-- Comment field hidden by default -->
|
||||||
<div class="mb-3" id="comment-field" style="display: none;">
|
<div class="mb-3" id="comment-field" style="display: none;">
|
||||||
<label for="comment" class="form-label">Comment (Optional):</label>
|
<label for="comment" class="form-label">Comment (Optional):</label>
|
||||||
<textarea class="form-control" id="comment" name="comment" rows="3"></textarea>
|
<textarea class="form-control" id="comment" name="comment" rows="3"></textarea>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button type="submit" class="btn btn-primary">Submit</button>
|
<button type="submit" class="btn btn-primary">Submit</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Scrolling Guest Entries at the Bottom -->
|
<!-- Scrolling Guest Entries at the Bottom -->
|
||||||
|
<!-- Content is duplicated so the loop is seamless: animate 0 → -50% -->
|
||||||
<div class="scrolling-wrapper">
|
<div class="scrolling-wrapper">
|
||||||
<div class="scrolling-content">
|
<div class="scrolling-content">
|
||||||
{% for guest in guests %}
|
{% for guest in guests %}
|
||||||
<span class="me-4">
|
<span class="me-5">
|
||||||
|
<strong>{{ guest[0] }}</strong> from {{ guest[1] }}
|
||||||
|
</span>
|
||||||
|
{% endfor %}
|
||||||
|
{% for guest in guests %}
|
||||||
|
<span class="me-5">
|
||||||
<strong>{{ guest[0] }}</strong> from {{ guest[1] }}
|
<strong>{{ guest[0] }}</strong> from {{ guest[1] }}
|
||||||
</span>
|
</span>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Set scrolling speed to a fixed pixels-per-second rate -->
|
||||||
|
<script>
|
||||||
|
(function () {
|
||||||
|
const pixelsPerSecond = 80;
|
||||||
|
const content = document.querySelector(".scrolling-content");
|
||||||
|
|
||||||
|
function updateScrollSpeed() {
|
||||||
|
// Travel distance is half the total width (one copy of the list)
|
||||||
|
const oneCopyWidth = content.offsetWidth / 2;
|
||||||
|
content.style.animationDuration = (oneCopyWidth / pixelsPerSecond) + "s";
|
||||||
|
}
|
||||||
|
|
||||||
|
updateScrollSpeed();
|
||||||
|
window.addEventListener("resize", updateScrollSpeed);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
|
||||||
<!-- JavaScript to reveal the comment field -->
|
<!-- JavaScript to reveal the comment field -->
|
||||||
<script>
|
<script>
|
||||||
document.addEventListener("DOMContentLoaded", function () {
|
document.addEventListener("DOMContentLoaded", function () {
|
||||||
const firstNameInput = document.getElementById('first_name');
|
const firstNameInput = document.getElementById("first_name");
|
||||||
const lastNameInput = document.getElementById('last_name');
|
const lastNameInput = document.getElementById("last_name");
|
||||||
const locationInput = document.getElementById('location');
|
const locationInput = document.getElementById("location");
|
||||||
const commentField = document.getElementById('comment-field');
|
const commentField = document.getElementById("comment-field");
|
||||||
|
|
||||||
function checkFields() {
|
function checkFields() {
|
||||||
if (firstNameInput.value.trim().length >= 3 &&
|
if (
|
||||||
|
firstNameInput.value.trim().length >= 3 &&
|
||||||
lastNameInput.value.trim().length >= 3 &&
|
lastNameInput.value.trim().length >= 3 &&
|
||||||
locationInput.value.trim().length >= 3) {
|
locationInput.value.trim().length >= 3
|
||||||
commentField.style.display = 'block';
|
) {
|
||||||
|
commentField.style.display = "block";
|
||||||
} else {
|
} else {
|
||||||
commentField.style.display = 'none';
|
commentField.style.display = "none";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
firstNameInput.addEventListener('input', checkFields);
|
firstNameInput.addEventListener("input", checkFields);
|
||||||
lastNameInput.addEventListener('input', checkFields);
|
lastNameInput.addEventListener("input", checkFields);
|
||||||
locationInput.addEventListener('input', checkFields);
|
locationInput.addEventListener("input", checkFields);
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
Reference in New Issue
Block a user