From cb3293c7b01c121c567f4b2abc9febd9ddd95678 Mon Sep 17 00:00:00 2001 From: Blake Ridgway Date: Wed, 12 Nov 2025 19:18:29 -0600 Subject: [PATCH] feat: complete go rewrite --- Dockerfile | 29 ++-- README.md | 206 ++++++++++++++++++++------- app.py | 150 ------------------- cmd/admin-panel/main.go | 37 +++++ config.go | 117 +++++++++++++++ database.go | 149 +++++++++++++++++++ database.py | 203 -------------------------- email.go | 86 +++++++++++ go.mod | 41 ++++++ go.sum | 98 +++++++++++++ internal/config/config.go | 81 +++++++++++ internal/database/database.go | 160 +++++++++++++++++++++ internal/email/email.go | 81 +++++++++++ internal/handlers/auth.go | 49 +++++++ internal/handlers/newsletter.go | 28 ++++ internal/handlers/subscribers.go | 19 +++ internal/middleware/auth.go | 42 ++++++ requirements.txt | 5 - sessions.go | 24 ++++ templates/admin_index.html | 44 ------ templates/login.html | 29 ---- templates/send_update.html | 37 ----- {static => web/static}/css/style.css | 0 web/templates/admin_index.html | 32 +++++ web/templates/login.html | 28 ++++ web/templates/send_update.html | 42 ++++++ 26 files changed, 1286 insertions(+), 531 deletions(-) delete mode 100644 app.py create mode 100644 cmd/admin-panel/main.go create mode 100644 config.go create mode 100644 database.go delete mode 100644 database.py create mode 100644 email.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/config/config.go create mode 100644 internal/database/database.go create mode 100644 internal/email/email.go create mode 100644 internal/handlers/auth.go create mode 100644 internal/handlers/newsletter.go create mode 100644 internal/handlers/subscribers.go create mode 100644 internal/middleware/auth.go delete mode 100644 requirements.txt create mode 100644 sessions.go delete mode 100644 templates/admin_index.html delete mode 100644 templates/login.html delete mode 100644 templates/send_update.html rename {static => web/static}/css/style.css (100%) create mode 100644 web/templates/admin_index.html create mode 100644 web/templates/login.html create mode 100644 web/templates/send_update.html diff --git a/Dockerfile b/Dockerfile index 5d0ac86..1925bae 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,18 +1,29 @@ -FROM python:3.11-slim-buster +# Stage 1: Build +FROM docker.io/library/golang:1.23-alpine AS builder -# Install build dependencies (build-essential provides gcc and other tools) -RUN apt-get update && apt-get install -y build-essential +WORKDIR /build -WORKDIR /rideaware_landing +RUN apk add --no-cache gcc musl-dev -COPY requirements.txt . - -RUN pip install --no-cache-dir -r requirements.txt +COPY go.mod go.sum ./ +RUN go mod download COPY . . -ENV FLASK_APP=server.py +RUN CGO_ENABLED=1 GOOS=linux go build -a -installsuffix cgo \ + -o admin-panel ./cmd/admin-panel + +# Stage 2: Runtime +FROM docker.io/library/alpine:latest + +RUN apk add --no-cache ca-certificates + +WORKDIR /app + +COPY --from=builder /build/admin-panel . +COPY .env .env +COPY web ./web EXPOSE 5001 -CMD ["gunicorn", "--bind", "0.0.0.0:5001", "app:app"] +CMD ["./admin-panel"] \ No newline at end of file diff --git a/README.md b/README.md index 510f3b3..6ef9d40 100644 --- a/README.md +++ b/README.md @@ -4,11 +4,10 @@ This project provides a secure and user-friendly Admin Panel for managing RideAw ## Features - **Secure Admin Authentication:** - -* Login protected by username/password authentication using Werkzeug's password hashing. +* Login protected by username/password authentication using bcrypt password hashing. * Default admin credentials configurable via environment variables. +* Session-based authentication with secure HTTP-only cookies. **Subscriber Management:** * View a comprehensive list of all subscribed email addresses. @@ -21,107 +20,206 @@ This project provides a secure and user-friendly Admin Panel for managing RideAw * Utilizes a shared PostgreSQL database with the landing page application for consistent subscriber data. **Centralized Newsletter Storage:** -* Storage of newsletter subject and email bodies in the PostgreSQL database +* Storage of newsletter subject and email bodies in the PostgreSQL database. -**Logging:** -* Implemented comprehensive logging throughout the application for better monitoring and debugging. +**Comprehensive Logging:** +* Implemented structured logging throughout the application for better monitoring and debugging. ## Architecture -The Admin Panel is built using Python with the Flask web framework, using the following technologies: +The Admin Panel is built using Go with the Gin web framework, using the following technologies: -* **Backend:** Python 3.11+, Flask -* **Database:** PostgreSQL -* **Template Engine:** Jinja2 -* **Authentication:** Werkzeug Security -* **Email:** SMTP (using `smtplib`) -* **Containerization:** Docker -* **Configuration:** .env file using `python-dotenv` +* **Backend:** Go 1.23+, Gin Web Framework +* **Database:** PostgreSQL with `lib/pq` driver +* **Authentication:** Bcrypt for password hashing, Gorilla Sessions for session management +* **Email:** SMTP via `go-mail` library +* **Containerization:** Podman/Docker with multi-stage builds +* **Configuration:** Environment variables via `godotenv` ## Setup & Deployment ### Prerequisites -* Docker (recommended for containerized deployment) -* Python 3.11+ (if running locally without Docker) -* A PostgreSQL database instance -* An SMTP account (e.g., SendGrid, Mailgun) for sending emails -* A `.env` file with configuration details +* Podman or Docker (recommended for containerized deployment) +* Go 1.23+ (if running locally without containers) +* A PostgreSQL database instance +* An SMTP account (e.g., SendGrid, Gmail, Mailgun) for sending emails +* A `.env` file with configuration details ### .env Configuration -Create a `.env` file in the project root directory with the following environment variables. Make sure to replace the placeholder values with your actual credentials. +Create a `.env` file in the project root directory with the following environment variables. Make sure to replace the placeholder values with your actual credentials. ```env -# Flask Application -SECRET_KEY="YourSecretKeyHere" #Used to sign session cookies +# Go Application +PORT=5001 +GIN_MODE=debug # Use 'release' in production # PostgreSQL Database Configuration PG_HOST=localhost PG_PORT=5432 -PG_DATABASE=rideaware_db -PG_USER=rideaware_user -PG_PASSWORD=rideaware_password +PG_DATABASE=rideaware +PG_USER=postgres +PG_PASSWORD=your_postgres_password # Admin credentials for the Admin Center ADMIN_USERNAME=admin -ADMIN_PASSWORD="changeme" # Change this to a secure password +ADMIN_PASSWORD=your_secure_password # Change this to a secure password +SECRET_KEY=your_secret_key_here # Used to sign session cookies # SMTP Email Settings -SMTP_SERVER=smtp.example.com -SMTP_PORT=465 #Or another appropriate port -SMTP_USER=your_email@example.com -SMTP_PASSWORD=YourEmailPassword -SENDER_EMAIL=your_email@example.com #Email to send emails from -BASE_URL="your_site_domain.com" # used for unsubscribe links, example.com not https:// +SMTP_SERVER=smtp.gmail.com +SMTP_PORT=465 # Or another appropriate port +SMTP_USER=your_email@gmail.com +SMTP_PASSWORD=your_app_password # Use app-specific password for Gmail +SENDER_EMAIL=your_email@gmail.com # Email address to send from -#Used for debugging -FLASK_DEBUG=1 +# Application Settings +BASE_URL=example.com # Used for unsubscribe links (without https://) ``` -### Running with Docker (Recommended) +### Running with Podman (Recommended) -This is the recommended approach for deploying the RideAware Admin Panel +This is the recommended approach for deploying the RideAware Admin Panel. -Building the Docker image: +**Building the image:** ```sh -docker build -t admin-panel . +podman build -t admin-panel:latest . ``` -Running the container mapping port 5001: +**Running the container:** ```sh -docker run -p 5001:5001 admin-panel +podman run -d \ + --name admin-panel \ + -p 5001:5001 \ + --env-file .env \ + admin-panel:latest +``` + +**Viewing logs:** +```sh +podman logs -f admin-panel ``` The application will be accessible at `http://localhost:5001` or `http://:5001` -*Note: When running locally with Docker, ensure the .env file is located at the project root. Alternatively, you can pass the variables in the CLI.* +### Running with Podman Compose -### Running locally +Create a `podman-compose.yml`: -Install Dependencies: +```yaml +version: '3.8' -```sh -pip install -r requirements.txt +services: + admin-panel: + build: . + ports: + - "5001:5001" + env_file: + - .env + depends_on: + - postgres + restart: unless-stopped + + postgres: + image: docker.io/library/postgres:15-alpine + environment: + POSTGRES_USER: ${PG_USER} + POSTGRES_PASSWORD: ${PG_PASSWORD} + POSTGRES_DB: ${PG_DATABASE} + ports: + - "5432:5432" + volumes: + - postgres_data:/var/lib/postgresql/data + restart: unless-stopped + +volumes: + postgres_data: ``` -Set Environment Variables: - -Ensure all the environment variables specified in the `.env` configuration section are set in your shell environment. You can source the `.env` file: - - -Then run the admin app: +Then run: ```sh -python app.py +podman-compose up -d +podman-compose logs -f admin-panel +``` + +### Running Locally (Development) + +**Install Go 1.23+** + +Ensure you have Go installed. Download from [golang.org](https://golang.org/dl) + +**Install dependencies:** +```sh +go mod tidy +``` + +**Run the application:** +```sh +go run ./cmd/admin-panel ``` The app will be accessible at `http://127.0.0.1:5001` -### Contributing +**For hot-reloading during development, install `air`:** +```sh +go install github.com/cosmtrek/air@latest +air +``` + +## API Endpoints + +| Method | Endpoint | Description | Protected | +|--------|----------|-------------|-----------| +| GET | `/login` | Login page | No | +| POST | `/login` | Submit login credentials | No | +| GET | `/logout` | Logout and clear session | Yes | +| GET | `/` | View subscriber list | Yes | +| GET | `/send_update` | Newsletter compose form | Yes | +| POST | `/send_update` | Send newsletter to all subscribers | Yes | + +## Development + +### Adding New Features + +1. Create a new handler in `internal/handlers/` +2. Add routes in `cmd/admin-panel/main.go` +3. Add any new dependencies to `go.mod` via `go get` +4. Run `go mod tidy` to sync dependencies + +### Database Migrations + +The application automatically creates required tables on startup if they don't exist. To add new tables, modify the `createTables()` function in `internal/database/database.go`. + +### Environment Variables + +Configuration is centralized in `internal/config/config.go`. All environment variables are loaded via the `godotenv` package. Defaults are provided for development. + +## Contributing Contributions to the RideAware Admin Panel are welcome! Please follow these steps: * Fork the repository. * Create a new branch for your feature or bug fix. * Make your changes and commit them with descriptive commit messages. -* Submit a pull request. \ No newline at end of file +* Ensure code builds with `go build ./cmd/admin-panel` +* Run `go fmt ./...` to format code +* Submit a pull request. + +## Troubleshooting + +**Database Connection Failed** +* Verify PostgreSQL is running and accessible +* Check `PG_HOST`, `PG_PORT`, `PG_USER`, and `PG_PASSWORD` in `.env` +* Test connection manually: `psql -h -U -d ` + +**Email Not Sending** +* Verify SMTP credentials are correct +* Check `SMTP_SERVER` and `SMTP_PORT` match your email provider +* For Gmail, use an [app-specific password](https://support.google.com/accounts/answer/185833) +* Check container logs for SMTP errors + +**Session/Login Issues** +* Ensure `SECRET_KEY` is set and consistent +* Clear browser cookies and try again +* Check that `GIN_MODE` is not set to `release` in development \ No newline at end of file diff --git a/app.py b/app.py deleted file mode 100644 index 8d6188e..0000000 --- a/app.py +++ /dev/null @@ -1,150 +0,0 @@ -import os -import logging -import smtplib -from email.mime.text import MIMEText -from flask import ( - Flask, - render_template, - request, - redirect, - url_for, - flash, - session, -) -from dotenv import load_dotenv -from werkzeug.security import check_password_hash -from functools import wraps # Import wraps -from database import get_connection, init_db, get_all_emails, get_admin, create_default_admin - -load_dotenv() -app = Flask(__name__) -app.secret_key = os.getenv("SECRET_KEY") -base_url = os.getenv("BASE_URL") - -# SMTP settings (for sending update emails) -SMTP_SERVER = os.getenv("SMTP_SERVER") -SMTP_PORT = int(os.getenv("SMTP_PORT", 465)) -SMTP_USER = os.getenv("SMTP_USER") -SMTP_PASSWORD = os.getenv("SMTP_PASSWORD") -SENDER_EMAIL = os.getenv("SENDER_EMAIL", SMTP_USER) # Use SENDER_EMAIL - -# Logging setup -logging.basicConfig( - level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" -) -logger = logging.getLogger(__name__) - -# Initialize the database and create default admin user if necessary. -init_db() -create_default_admin() - -# Decorator for requiring login -def login_required(f): - @wraps(f) # Use wraps to preserve function metadata - def decorated_function(*args, **kwargs): - if "username" not in session: - return redirect(url_for("login")) - return f(*args, **kwargs) - - return decorated_function - - -def send_update_email(subject, body, email): - """Sends email, returns True on success, False on failure.""" - try: - server = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT, timeout=10) - server.set_debuglevel(False) # Keep debug level at False for production - server.login(SMTP_USER, SMTP_PASSWORD) - - unsub_link = f"https://{base_url}/unsubscribe?email={email}" - custom_body = ( - f"{body}

" - f"If you ever wish to unsubscribe, please click here" - ) - - msg = MIMEText(custom_body, "html", "utf-8") - msg["Subject"] = subject - msg["From"] = SENDER_EMAIL # Use sender email - msg["To"] = email - - server.sendmail(SENDER_EMAIL, email, msg.as_string()) # Use sender email - - server.quit() - logger.info(f"Update email sent to: {email}") - return True - except Exception as e: - logger.error(f"Failed to send email to {email}: {e}") - return False - - -def process_send_update_email(subject, body): - """Helper function to send an update email to all subscribers.""" - subscribers = get_all_emails() - if not subscribers: - return "No subscribers found." - try: - for email in subscribers: - if not send_update_email(subject, body, email): - return f"Failed to send to {email}" # Specific failure message - - # Log newsletter content for audit purposes - conn = get_connection() - cursor = conn.cursor() - cursor.execute( - "INSERT INTO newsletters (subject, body) VALUES (%s, %s)", (subject, body) - ) - conn.commit() - cursor.close() - conn.close() - - return "Email has been sent to all subscribers." - except Exception as e: - logger.exception("Error processing sending updates") - return f"Failed to send email: {e}" - - -@app.route("/") -@login_required -def index(): - """Displays all subscriber emails""" - emails = get_all_emails() - return render_template("admin_index.html", emails=emails) - -@app.route("/send_update", methods=["GET", "POST"]) -@login_required -def send_update(): - """Display a form to send an update email; process submission on POST.""" - if request.method == "POST": - subject = request.form["subject"] - body = request.form["body"] - result_message = process_send_update_email(subject, body) - flash(result_message) - return redirect(url_for("send_update")) - return render_template("send_update.html") - - -@app.route("/login", methods=["GET", "POST"]) -def login(): - if request.method == "POST": - username = request.form.get("username") - password = request.form.get("password") - admin = get_admin(username) - if admin and check_password_hash(admin[1], password): - session["username"] = username - flash("Logged in successfully", "success") - return redirect(url_for("index")) - else: - flash("Invalid username or password", "danger") - return redirect(url_for("login")) - return render_template("login.html") - - -@app.route("/logout") -def logout(): - session.pop("username", None) - flash("Logged out successfully", "success") - return redirect(url_for("login")) - - -if __name__ == "__main__": - app.run(port=5001, debug=True) diff --git a/cmd/admin-panel/main.go b/cmd/admin-panel/main.go new file mode 100644 index 0000000..5c2572b --- /dev/null +++ b/cmd/admin-panel/main.go @@ -0,0 +1,37 @@ +package main + +import ( + "log" + + "github.com/rideaware/admin-panel/internal/config" + "github.com/rideaware/admin-panel/internal/database" + "github.com/rideaware/admin-panel/internal/handlers" + "github.com/rideaware/admin-panel/internal/middleware" + + "github.com/gin-gonic/gin" +) + +func main() { + cfg := config.Load() + middleware.Init() + database.Init(cfg) + defer database.Close() + + router := gin.Default() + + router.LoadHTMLGlob("web/templates/*.html") + router.Static("/static", "web/static") + + router.GET("/login", handlers.LoginGet) + router.POST("/login", handlers.LoginPost) + router.GET("/logout", handlers.Logout) + + protected := router.Group("/") + protected.Use(middleware.Auth()) + protected.GET("/", handlers.IndexGet) + protected.GET("/send_update", handlers.SendUpdateGet) + protected.POST("/send_update", handlers.SendUpdatePost) + + log.Printf("Server running on port %s", cfg.Port) + router.Run(":" + cfg.Port) +} \ No newline at end of file diff --git a/config.go b/config.go new file mode 100644 index 0000000..b6c2665 --- /dev/null +++ b/config.go @@ -0,0 +1,117 @@ +package main + +import ( + "log" + "os" + "strconv" + + "github.com/joho/godotenv" +) + +type Config struct { + // Server + Port string + + // Database + PGHost string + PGPort string + PGUser string + PGPassword string + PGDatabase string + + // SMTP + SMTPServer string + SMTPPort int + SMTPUser string + SMTPPassword string + SenderEmail string + + // Admin + AdminUsername string + AdminPassword string + + // App + SecretKey string + BaseURL string +} + +var config *Config + +func loadConfig() *Config { + // Load .env file + err := godotenv.Load() + if err != nil { + log.Printf("Warning: Could not load .env file: %v", err) + } else { + log.Println("Successfully loaded .env file") + } + + // Debug: Print raw values before any processing + rawPassword := os.Getenv("PG_PASSWORD") + log.Printf("Raw PG_PASSWORD length: %d, value: [%s]", len(rawPassword), rawPassword) + log.Printf("Raw PG_USER: [%s]", os.Getenv("PG_USER")) + log.Printf("Raw PG_HOST: [%s]", os.Getenv("PG_HOST")) + + cfg := &Config{ + Port: getEnv("PORT", "5001"), + PGHost: getEnv("PG_HOST", "localhost"), + PGPort: getEnv("PG_PORT", "5432"), + PGUser: getEnv("PG_USER", "postgres"), + PGPassword: getEnv("PG_PASSWORD", ""), + PGDatabase: getEnv("PG_DATABASE", "newsletter"), + SMTPServer: getEnv("SMTP_SERVER", ""), + SMTPPort: getEnvInt("SMTP_PORT", 465), + SMTPUser: getEnv("SMTP_USER", ""), + SMTPPassword: getEnv("SMTP_PASSWORD", ""), + SenderEmail: getEnv("SENDER_EMAIL", ""), + AdminUsername: getEnv("ADMIN_USERNAME", "admin"), + AdminPassword: getEnv("ADMIN_PASSWORD", "changeme"), + SecretKey: getEnv("SECRET_KEY", "your-secret-key"), + BaseURL: getEnv("BASE_URL", "localhost:5001"), + } + + // Debug output + log.Printf("=== Config Loaded ===") + log.Printf("PG_HOST: %s", cfg.PGHost) + log.Printf("PG_PORT: %s", cfg.PGPort) + log.Printf("PG_USER: %s", cfg.PGUser) + log.Printf("PG_DATABASE: %s", cfg.PGDatabase) + log.Printf("PG_PASSWORD length: %d", len(cfg.PGPassword)) + log.Printf("BASE_URL: %s", cfg.BaseURL) + log.Printf("====================") + + if cfg.SenderEmail == "" { + cfg.SenderEmail = cfg.SMTPUser + } + + return cfg +} + +func getEnv(key, defaultValue string) string { + value := os.Getenv(key) + if value == "" { + log.Printf("Env var %s not found, using default: %s", key, defaultValue) + return defaultValue + } + return value +} + +func getEnvInt(key string, defaultValue int) int { + value := os.Getenv(key) + if value == "" { + return defaultValue + } + intVal, err := strconv.Atoi(value) + if err != nil { + log.Printf("Invalid integer for %s: %v, using default", key, err) + return defaultValue + } + return intVal +} + +func maskPassword(pwd string) string { + if len(pwd) <= 2 { + return "***" + } + return pwd[:2] + "***" + pwd[len(pwd)-2:] +} \ No newline at end of file diff --git a/database.go b/database.go new file mode 100644 index 0000000..6ce4876 --- /dev/null +++ b/database.go @@ -0,0 +1,149 @@ +package main + +import ( + "database/sql" + "fmt" + "log" + "net/url" + + _ "github.com/lib/pq" + "golang.org/x/crypto/bcrypt" +) + +var db *sql.DB + +type Admin struct { + Username string + Password string +} + +func initDB() { + // Escape special characters in password + password := url.QueryEscape(config.PGPassword) + + psqlInfo := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=require", + config.PGUser, + password, + config.PGHost, + config.PGPort, + config.PGDatabase, + ) + + log.Printf("Connecting to database: postgres://%s:***@%s:%s/%s", + config.PGUser, config.PGHost, config.PGPort, config.PGDatabase) + + var err error + db, err = sql.Open("postgres", psqlInfo) + if err != nil { + log.Fatalf("Database connection error: %v", err) + } + + db.SetMaxOpenConns(25) + db.SetMaxIdleConns(5) + + if err = db.Ping(); err != nil { + log.Fatalf("Failed to ping database: %v", err) + } + + log.Println("Database connection successful!") + createTables() +} + +func createTables() { + queries := []string{ + `CREATE TABLE IF NOT EXISTS subscribers ( + id SERIAL PRIMARY KEY, + email TEXT UNIQUE NOT NULL + )`, + `CREATE TABLE IF NOT EXISTS admin_users ( + id SERIAL PRIMARY KEY, + username TEXT UNIQUE NOT NULL, + password TEXT NOT NULL + )`, + `CREATE TABLE IF NOT EXISTS newsletters ( + id SERIAL PRIMARY KEY, + subject TEXT NOT NULL, + body TEXT NOT NULL, + sent_at TIMESTAMP WITH TIME ZONE + DEFAULT CURRENT_TIMESTAMP + )`, + } + + for _, query := range queries { + if _, err := db.Exec(query); err != nil { + log.Printf("Error creating table: %v", err) + } + } + + log.Println("Database tables ready.") +} + +func getAllEmails() ([]string, error) { + rows, err := db.Query("SELECT email FROM subscribers") + if err != nil { + log.Printf("Error retrieving emails: %v", err) + return nil, err + } + defer rows.Close() + + var emails []string + for rows.Next() { + var email string + if err := rows.Scan(&email); err != nil { + return nil, err + } + emails = append(emails, email) + } + + return emails, rows.Err() +} + +func getAdmin(username string) (*Admin, error) { + var admin Admin + err := db.QueryRow( + "SELECT username, password FROM admin_users WHERE username=$1", + username, + ).Scan(&admin.Username, &admin.Password) + + if err != nil { + if err == sql.ErrNoRows { + return nil, fmt.Errorf("admin not found") + } + return nil, err + } + + return &admin, nil +} + +func createDefaultAdmin() { + hashedPassword, err := hashPassword(config.AdminPassword) + if err != nil { + log.Fatalf("Error hashing password: %v", err) + } + + _, err = db.Exec( + "INSERT INTO admin_users (username, password) "+ + "VALUES ($1, $2) ON CONFLICT (username) DO NOTHING", + config.AdminUsername, hashedPassword, + ) + if err != nil { + log.Printf("Error creating default admin: %v", err) + } else { + log.Println("Default admin user ready.") + } +} + +func hashPassword(password string) (string, error) { + hash, err := bcrypt.GenerateFromPassword( + []byte(password), + bcrypt.DefaultCost, + ) + return string(hash), err +} + +func verifyPassword(hash, password string) bool { + return bcrypt.CompareHashAndPassword( + []byte(hash), + []byte(password), + ) == nil +} \ No newline at end of file diff --git a/database.py b/database.py deleted file mode 100644 index b90e0ef..0000000 --- a/database.py +++ /dev/null @@ -1,203 +0,0 @@ -import os -import logging -import psycopg2 -from psycopg2 import IntegrityError -from dotenv import load_dotenv -from werkzeug.security import generate_password_hash - -load_dotenv() - -# Logging setup -logging.basicConfig( - level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" -) -logger = logging.getLogger(__name__) - - -def get_connection(): - """Return a new connection to the PostgreSQL database.""" - try: - conn = psycopg2.connect( - host=os.getenv("PG_HOST"), - port=os.getenv("PG_PORT"), - dbname=os.getenv("PG_DATABASE"), - user=os.getenv("PG_USER"), - password=os.getenv("PG_PASSWORD"), - connect_timeout=10, - ) - return conn - except Exception as e: - logger.error(f"Database connection error: {e}") - raise - - -def init_db(): - """Initialize the database tables.""" - conn = None - try: - conn = get_connection() - cursor = conn.cursor() - - # Create subscribers table (if not exists) - cursor.execute( - """ - CREATE TABLE IF NOT EXISTS subscribers ( - id SERIAL PRIMARY KEY, - email TEXT UNIQUE NOT NULL - ) - """ - ) - - # Create admin_users table (if not exists) - cursor.execute( - """ - CREATE TABLE IF NOT EXISTS admin_users ( - id SERIAL PRIMARY KEY, - username TEXT UNIQUE NOT NULL, - password TEXT NOT NULL - ) - """ - ) - - # Newsletter storage - cursor.execute( - """ - CREATE TABLE IF NOT EXISTS newsletters ( - id SERIAL PRIMARY KEY, - subject TEXT NOT NULL, - body TEXT NOT NULL, - sent_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP - ) - """ - ) - - conn.commit() - logger.info("Database initialized successfully.") - except Exception as e: - logger.error(f"Database initialization error: {e}") - if conn: - conn.rollback() # Rollback if there's an error - - raise - finally: - if conn: - cursor.close() - conn.close() - - -def get_all_emails(): - """Return a list of all subscriber emails.""" - try: - conn = get_connection() - cursor = conn.cursor() - cursor.execute("SELECT email FROM subscribers") - results = cursor.fetchall() - emails = [row[0] for row in results] - logger.debug(f"Retrieved emails: {emails}") - return emails - except Exception as e: - logger.error(f"Error retrieving emails: {e}") - return [] - finally: - if conn: - cursor.close() - conn.close() - - -def add_email(email): - """Insert an email into the subscribers table.""" - conn = None - try: - conn = get_connection() - cursor = conn.cursor() - cursor.execute("INSERT INTO subscribers (email) VALUES (%s)", (email,)) - conn.commit() - logger.info(f"Email {email} added successfully.") - return True - except IntegrityError: - logger.warning(f"Attempted to add duplicate email: {email}") - return False - except Exception as e: - logger.error(f"Error adding email {email}: {e}") - return False - finally: - if conn: - cursor.close() - conn.close() - - -def remove_email(email): - """Remove an email from the subscribers table.""" - conn = None - try: - conn = get_connection() - cursor = conn.cursor() - cursor.execute("DELETE FROM subscribers WHERE email = %s", (email,)) - rowcount = cursor.rowcount - conn.commit() - logger.info(f"Email {email} removed successfully.") - return rowcount > 0 - except Exception as e: - logger.error(f"Error removing email {email}: {e}") - return False - finally: - if conn: - cursor.close() - conn.close() - - -def get_admin(username): - """Retrieve admin credentials for a given username. - Returns a tuple (username, password_hash) if found, otherwise None. - """ - conn = None - try: - conn = get_connection() - cursor = conn.cursor() - cursor.execute( - "SELECT username, password FROM admin_users WHERE username = %s", - (username,), - ) - result = cursor.fetchone() - return result # (username, password_hash) - except Exception as e: - logger.error(f"Error retrieving admin: {e}") - return None - finally: - if conn: - cursor.close() - conn.close() - - -def create_default_admin(): - """Create a default admin user if one doesn't already exist.""" - default_username = os.getenv("ADMIN_USERNAME", "admin") - default_password = os.getenv("ADMIN_PASSWORD", "changeme") - hashed_password = generate_password_hash(default_password, method="pbkdf2:sha256") - conn = None - try: - conn = get_connection() - cursor = conn.cursor() - - # Check if the admin already exists - cursor.execute( - "SELECT id FROM admin_users WHERE username = %s", (default_username,) - ) - if cursor.fetchone() is None: - cursor.execute( - "INSERT INTO admin_users (username, password) VALUES (%s, %s)", - (default_username, hashed_password), - ) - conn.commit() - logger.info("Default admin created successfully") - else: - logger.info("Default admin already exists") - except Exception as e: - logger.error(f"Error creating default admin: {e}") - if conn: - conn.rollback() - finally: - if conn: - cursor.close() - conn.close() - diff --git a/email.go b/email.go new file mode 100644 index 0000000..0d28bb2 --- /dev/null +++ b/email.go @@ -0,0 +1,86 @@ +package main + +import ( + "fmt" + "log" + "time" + + "github.com/wneessen/go-mail" +) + +func sendUpdateEmail(subject, body, recipient string) bool { + client, err := mail.NewClient( + config.SMTPServer, + mail.WithPort(config.SMTPPort), + mail.WithSMTPAuth(mail.SMTPAuthPlain), + mail.WithUsername(config.SMTPUser), + mail.WithPassword(config.SMTPPassword), + mail.WithTimeout(10*time.Second), + ) + if err != nil { + log.Printf("Failed to create mail client: %v", err) + return false + } + defer client.Close() + + m := mail.NewMsg() + if err := m.From(config.SenderEmail); err != nil { + log.Printf("Failed to set from: %v", err) + return false + } + if err := m.To(recipient); err != nil { + log.Printf("Failed to set to: %v", err) + return false + } + m.Subject(subject) + + unsubLink := fmt.Sprintf( + "https://%s/unsubscribe?email=%s", + config.BaseURL, + recipient, + ) + + htmlBody := fmt.Sprintf( + "%s

If you ever wish to unsubscribe, "+ + "please click here", + body, unsubLink, + ) + m.SetBodyString(mail.TypeTextHTML, htmlBody) + + if err := client.Send(m); err != nil { + log.Printf("Failed to send email to %s: %v", recipient, err) + return false + } + + log.Printf("Update email sent to: %s", recipient) + return true +} + +func processSendUpdateEmail(subject, body string) (string, error) { + subscribers, err := getAllEmails() + if err != nil { + return "Failed to retrieve subscribers", err + } + + if len(subscribers) == 0 { + return "No subscribers found.", nil + } + + for _, email := range subscribers { + if !sendUpdateEmail(subject, body, email) { + return fmt.Sprintf("Failed to send to %s", email), + nil + } + } + + // Log newsletter + _, err = db.Exec( + "INSERT INTO newsletters (subject, body) VALUES ($1, $2)", + subject, body, + ) + if err != nil { + log.Printf("Error logging newsletter: %v", err) + } + + return "Email has been sent to all subscribers.", nil +} \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..27518f1 --- /dev/null +++ b/go.mod @@ -0,0 +1,41 @@ +module github.com/rideaware/admin-panel + +go 1.23 + +toolchain go1.24.10 + +require ( + github.com/gin-gonic/gin v1.9.1 + github.com/gorilla/sessions v1.4.0 + github.com/joho/godotenv v1.5.1 + github.com/lib/pq v1.10.9 + github.com/wneessen/go-mail v0.4.0 + golang.org/x/crypto v0.14.0 +) + +require ( + github.com/bytedance/sonic v1.9.1 // indirect + github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect + github.com/gabriel-vasile/mimetype v1.4.2 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.14.0 // indirect + github.com/goccy/go-json v0.10.2 // indirect + github.com/gorilla/securecookie v1.1.2 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.4 // indirect + github.com/leodido/go-urn v1.2.4 // indirect + github.com/mattn/go-isatty v0.0.19 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.0.8 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.11 // indirect + golang.org/x/arch v0.3.0 // indirect + golang.org/x/net v0.10.0 // indirect + golang.org/x/sys v0.13.0 // indirect + golang.org/x/text v0.13.0 // indirect + google.golang.org/protobuf v1.30.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..9d55e3b --- /dev/null +++ b/go.sum @@ -0,0 +1,98 @@ +github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= +github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s= +github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= +github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= +github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= +github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js= +github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA= +github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo= +github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ= +github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= +github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= +github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= +github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ= +github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY= +github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU= +github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +github.com/wneessen/go-mail v0.4.0 h1:Oo4HLIV8My7G9JuZkoOX6eipXQD+ACvIqURYeIzUc88= +github.com/wneessen/go-mail v0.4.0/go.mod h1:zxOlafWCP/r6FEhAaRgH4IC1vg2YXxO0Nar9u0IScZ8= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k= +golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= +golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= +google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..a7795b7 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,81 @@ +package config + +import ( + "log" + "os" + "strconv" + + "github.com/joho/godotenv" +) + +type Config struct { + Port string + PGHost string + PGPort string + PGUser string + PGPassword string + PGDatabase string + SMTPServer string + SMTPPort int + SMTPUser string + SMTPPassword string + SenderEmail string + AdminUsername string + AdminPassword string + SecretKey string + BaseURL string +} + +var Current *Config + +func Load() *Config { + if err := godotenv.Load(); err != nil { + log.Println("No .env file found, using environment variables") + } + + cfg := &Config{ + Port: getEnv("PORT", "5001"), + PGHost: getEnv("PG_HOST", "localhost"), + PGPort: getEnv("PG_PORT", "5432"), + PGUser: getEnv("PG_USER", "postgres"), + PGPassword: getEnv("PG_PASSWORD", ""), + PGDatabase: getEnv("PG_DATABASE", "newsletter"), + SMTPServer: getEnv("SMTP_SERVER", ""), + SMTPPort: getEnvInt("SMTP_PORT", 465), + SMTPUser: getEnv("SMTP_USER", ""), + SMTPPassword: getEnv("SMTP_PASSWORD", ""), + SenderEmail: getEnv("SENDER_EMAIL", ""), + AdminUsername: getEnv("ADMIN_USERNAME", "admin"), + AdminPassword: getEnv("ADMIN_PASSWORD", "changeme"), + SecretKey: getEnv("SECRET_KEY", "your-secret-key"), + BaseURL: getEnv("BASE_URL", "localhost:5001"), + } + + if cfg.SenderEmail == "" { + cfg.SenderEmail = cfg.SMTPUser + } + + Current = cfg + return cfg +} + +func getEnv(key, defaultValue string) string { + value := os.Getenv(key) + if value == "" { + return defaultValue + } + return value +} + +func getEnvInt(key string, defaultValue int) int { + value := os.Getenv(key) + if value == "" { + return defaultValue + } + intVal, err := strconv.Atoi(value) + if err != nil { + log.Printf("Invalid integer for %s: %v", key, err) + return defaultValue + } + return intVal +} \ No newline at end of file diff --git a/internal/database/database.go b/internal/database/database.go new file mode 100644 index 0000000..1c6e253 --- /dev/null +++ b/internal/database/database.go @@ -0,0 +1,160 @@ +package database + +import ( + "database/sql" + "fmt" + "log" + "net/url" + + "github.com/rideaware/admin-panel/internal/config" + + _ "github.com/lib/pq" + "golang.org/x/crypto/bcrypt" +) + +var db *sql.DB + +type Admin struct { + Username string + Password string +} + +func Init(cfg *config.Config) { + password := url.QueryEscape(cfg.PGPassword) + + psqlInfo := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=require", + cfg.PGUser, password, cfg.PGHost, cfg.PGPort, cfg.PGDatabase, + ) + + log.Printf("Connecting to database: postgres://%s:***@%s:%s/%s", + cfg.PGUser, cfg.PGHost, cfg.PGPort, cfg.PGDatabase) + + var err error + db, err = sql.Open("postgres", psqlInfo) + if err != nil { + log.Fatalf("Database connection error: %v", err) + } + + db.SetMaxOpenConns(25) + db.SetMaxIdleConns(5) + + if err = db.Ping(); err != nil { + log.Fatalf("Failed to ping database: %v", err) + } + + log.Println("Database connection successful!") + createTables() + createDefaultAdmin(cfg) +} + +func Close() { + if db != nil { + db.Close() + } +} + +func createTables() { + queries := []string{ + `CREATE TABLE IF NOT EXISTS subscribers ( + id SERIAL PRIMARY KEY, + email TEXT UNIQUE NOT NULL + )`, + `CREATE TABLE IF NOT EXISTS admin_users ( + id SERIAL PRIMARY KEY, + username TEXT UNIQUE NOT NULL, + password TEXT NOT NULL + )`, + `CREATE TABLE IF NOT EXISTS newsletters ( + id SERIAL PRIMARY KEY, + subject TEXT NOT NULL, + body TEXT NOT NULL, + sent_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP + )`, + } + + for _, query := range queries { + if _, err := db.Exec(query); err != nil { + log.Printf("Error creating table: %v", err) + } + } + + log.Println("Database tables ready.") +} + +func GetAllEmails() ([]string, error) { + rows, err := db.Query("SELECT email FROM subscribers") + if err != nil { + log.Printf("Error retrieving emails: %v", err) + return nil, err + } + defer rows.Close() + + var emails []string + for rows.Next() { + var email string + if err := rows.Scan(&email); err != nil { + return nil, err + } + emails = append(emails, email) + } + + return emails, rows.Err() +} + +func GetAdmin(username string) (*Admin, error) { + var admin Admin + err := db.QueryRow( + "SELECT username, password FROM admin_users WHERE username=$1", + username, + ).Scan(&admin.Username, &admin.Password) + + if err != nil { + if err == sql.ErrNoRows { + return nil, fmt.Errorf("admin not found") + } + return nil, err + } + + return &admin, nil +} + +func createDefaultAdmin(cfg *config.Config) { + hashedPassword, err := hashPassword(cfg.AdminPassword) + if err != nil { + log.Fatalf("Error hashing password: %v", err) + } + + _, err = db.Exec( + "INSERT INTO admin_users (username, password) VALUES ($1, $2) "+ + "ON CONFLICT (username) DO NOTHING", + cfg.AdminUsername, hashedPassword, + ) + if err != nil { + log.Printf("Error creating default admin: %v", err) + } else { + log.Println("Default admin user ready.") + } +} + +func LogNewsletter(subject, body string) error { + _, err := db.Exec( + "INSERT INTO newsletters (subject, body) VALUES ($1, $2)", + subject, body, + ) + return err +} + +func hashPassword(password string) (string, error) { + hash, err := bcrypt.GenerateFromPassword( + []byte(password), + bcrypt.DefaultCost, + ) + return string(hash), err +} + +func VerifyPassword(hash, password string) bool { + return bcrypt.CompareHashAndPassword( + []byte(hash), + []byte(password), + ) == nil +} \ No newline at end of file diff --git a/internal/email/email.go b/internal/email/email.go new file mode 100644 index 0000000..0045e0b --- /dev/null +++ b/internal/email/email.go @@ -0,0 +1,81 @@ +package email + +import ( + "fmt" + "log" + "time" + + "github.com/rideaware/admin-panel/internal/config" + "github.com/rideaware/admin-panel/internal/database" + + "github.com/wneessen/go-mail" +) + +func SendUpdate(subject, body string) (string, error) { + subscribers, err := database.GetAllEmails() + if err != nil { + return "Failed to retrieve subscribers", err + } + + if len(subscribers) == 0 { + return "No subscribers found.", nil + } + + for _, email := range subscribers { + if !send(subject, body, email) { + return fmt.Sprintf("Failed to send to %s", email), nil + } + } + + if err := database.LogNewsletter(subject, body); err != nil { + log.Printf("Error logging newsletter: %v", err) + } + + return "Email has been sent to all subscribers.", nil +} + +func send(subject, body, recipient string) bool { + cfg := config.Current + + client, err := mail.NewClient( + cfg.SMTPServer, + mail.WithPort(cfg.SMTPPort), + mail.WithSMTPAuth(mail.SMTPAuthPlain), + mail.WithUsername(cfg.SMTPUser), + mail.WithPassword(cfg.SMTPPassword), + mail.WithTimeout(10*time.Second), + ) + if err != nil { + log.Printf("Failed to create mail client: %v", err) + return false + } + defer client.Close() + + m := mail.NewMsg() + if err := m.From(cfg.SenderEmail); err != nil { + log.Printf("Failed to set from: %v", err) + return false + } + if err := m.To(recipient); err != nil { + log.Printf("Failed to set to: %v", err) + return false + } + m.Subject(subject) + + unsubLink := fmt.Sprintf("https://%s/unsubscribe?email=%s", + cfg.BaseURL, recipient) + + htmlBody := fmt.Sprintf( + "%s

If you ever wish to unsubscribe, "+ + "please click here", + body, unsubLink) + m.SetBodyString(mail.TypeTextHTML, htmlBody) + + if err := client.Send(m); err != nil { + log.Printf("Failed to send email to %s: %v", recipient, err) + return false + } + + log.Printf("Update email sent to: %s", recipient) + return true +} \ No newline at end of file diff --git a/internal/handlers/auth.go b/internal/handlers/auth.go new file mode 100644 index 0000000..d8e0ded --- /dev/null +++ b/internal/handlers/auth.go @@ -0,0 +1,49 @@ +package handlers + +import ( + "net/http" + + "github.com/rideaware/admin-panel/internal/database" + "github.com/rideaware/admin-panel/internal/middleware" + + "github.com/gin-gonic/gin" +) + +func LoginGet(c *gin.Context) { + c.HTML(http.StatusOK, "login.html", gin.H{}) +} + +func LoginPost(c *gin.Context) { + username := c.PostForm("username") + password := c.PostForm("password") + + admin, err := database.GetAdmin(username) + if err != nil || !database.VerifyPassword(admin.Password, password) { + c.HTML(http.StatusUnauthorized, "login.html", + gin.H{"error": "Invalid username or password"}) + return + } + + session, err := middleware.GetStore().Get(c.Request, "session") + if err != nil { + c.AbortWithError(http.StatusInternalServerError, err) + return + } + + session.Values["username"] = username + if err := session.Save(c.Request, c.Writer); err != nil { + c.AbortWithError(http.StatusInternalServerError, err) + return + } + + c.Redirect(http.StatusFound, "/") +} + +func Logout(c *gin.Context) { + session, err := middleware.GetStore().Get(c.Request, "session") + if err == nil { + session.Options.MaxAge = -1 + session.Save(c.Request, c.Writer) + } + c.Redirect(http.StatusFound, "/login") +} \ No newline at end of file diff --git a/internal/handlers/newsletter.go b/internal/handlers/newsletter.go new file mode 100644 index 0000000..c4b02dd --- /dev/null +++ b/internal/handlers/newsletter.go @@ -0,0 +1,28 @@ +package handlers + +import ( + "net/http" + + "github.com/rideaware/admin-panel/internal/email" + + "github.com/gin-gonic/gin" +) + +func SendUpdateGet(c *gin.Context) { + c.HTML(http.StatusOK, "send_update.html", gin.H{}) +} + +func SendUpdatePost(c *gin.Context) { + subject := c.PostForm("subject") + body := c.PostForm("body") + + message, err := email.SendUpdate(subject, body) + if err != nil { + c.HTML(http.StatusOK, "send_update.html", + gin.H{"error": message}) + return + } + + c.HTML(http.StatusOK, "send_update.html", + gin.H{"success": message}) +} \ No newline at end of file diff --git a/internal/handlers/subscribers.go b/internal/handlers/subscribers.go new file mode 100644 index 0000000..076b432 --- /dev/null +++ b/internal/handlers/subscribers.go @@ -0,0 +1,19 @@ +package handlers + +import ( + "net/http" + + "github.com/rideaware/admin-panel/internal/database" + + "github.com/gin-gonic/gin" +) + +func IndexGet(c *gin.Context) { + emails, err := database.GetAllEmails() + if err != nil { + c.AbortWithError(http.StatusInternalServerError, err) + return + } + c.HTML(http.StatusOK, "admin_index.html", + gin.H{"emails": emails}) +} \ No newline at end of file diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go new file mode 100644 index 0000000..5ee4132 --- /dev/null +++ b/internal/middleware/auth.go @@ -0,0 +1,42 @@ +package middleware + +import ( + "net/http" + + "github.com/rideaware/admin-panel/internal/config" + + "github.com/gin-gonic/gin" + "github.com/gorilla/sessions" +) + +var store *sessions.CookieStore + +func Init() { + if config.Current.SecretKey == "" { + panic("SECRET_KEY not set") + } + store = sessions.NewCookieStore([]byte(config.Current.SecretKey)) + store.Options = &sessions.Options{ + Path: "/", + MaxAge: 86400 * 7, + HttpOnly: true, + Secure: false, + SameSite: 0, + } +} + +func GetStore() *sessions.CookieStore { + return store +} + +func Auth() gin.HandlerFunc { + return func(c *gin.Context) { + session, err := store.Get(c.Request, "session") + if err != nil || session.Values["username"] == nil { + c.Redirect(http.StatusFound, "/login") + c.Abort() + return + } + c.Next() + } +} \ No newline at end of file diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 26fcaf5..0000000 --- a/requirements.txt +++ /dev/null @@ -1,5 +0,0 @@ -gunicorn -flask -python-dotenv -Werkzeug -psycopg2-binary diff --git a/sessions.go b/sessions.go new file mode 100644 index 0000000..0d42a40 --- /dev/null +++ b/sessions.go @@ -0,0 +1,24 @@ +package main + +import ( + "log" + + "github.com/gorilla/sessions" +) + +var store *sessions.CookieStore + +func initSessions() { + if config.SecretKey == "" { + log.Fatal("SECRET_KEY not set in configuration") + } + store = sessions.NewCookieStore([]byte(config.SecretKey)) + store.Options = &sessions.Options{ + Path: "/", + MaxAge: 86400 * 7, // 7 days + HttpOnly: true, + Secure: false, // Set to true in production with HTTPS + SameSite: 0, + } + log.Println("Sessions initialized") +} \ No newline at end of file diff --git a/templates/admin_index.html b/templates/admin_index.html deleted file mode 100644 index c4620af..0000000 --- a/templates/admin_index.html +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - Admin Center - Subscribers - - - - -

Subscribers

-

- Send Update Email| - Logout -

- - {% with messages = get_flashed_messages(with_categories=true) %} - {% if messages %} - {% for category, message in messages %} -
{{ message }}
- {% endfor %} - {% endif %} - {% endwith %} - - {% if emails %} - - - - - - - - {% for email in emails %} - - - - {% endfor %} - -
Email Address
{{ email }}
- {% else %} -

No subscribers found.

- {% endif %} - - diff --git a/templates/login.html b/templates/login.html deleted file mode 100644 index 97fefdd..0000000 --- a/templates/login.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - Admin Login - - - - -

Admin Login

- {% with messages = get_flashed_messages(with_categories=true) %} - {% if messages %} - {% for category, message in messages %} -
{{ message }}
- {% endfor %} - {% endif %} - {% endwith %} -
- - - - - -
- - - diff --git a/templates/send_update.html b/templates/send_update.html deleted file mode 100644 index fccd7ff..0000000 --- a/templates/send_update.html +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - Admin Center - Send Update - - - - -

Send Update Email

-

- Back to Subscribers List | - Logout -

- {% with messages = get_flashed_messages() %} - {% if messages %} - {% for message in messages %} -
{{ message }}
- {% endfor %} - {% endif %} - {% endwith %} - -
- - - - - - - -
- - - - diff --git a/static/css/style.css b/web/static/css/style.css similarity index 100% rename from static/css/style.css rename to web/static/css/style.css diff --git a/web/templates/admin_index.html b/web/templates/admin_index.html new file mode 100644 index 0000000..616ce74 --- /dev/null +++ b/web/templates/admin_index.html @@ -0,0 +1,32 @@ + + + + Admin Panel - Subscribers + + + +

Admin Panel

+ Logout + Send Update + +

Subscribers ({{ len .emails }})

+ + + + + {{ range .emails }} + + + + {{ end }} +
Email
{{ . }}
+ + \ No newline at end of file diff --git a/web/templates/login.html b/web/templates/login.html new file mode 100644 index 0000000..b423837 --- /dev/null +++ b/web/templates/login.html @@ -0,0 +1,28 @@ + + + + Admin Login + + + + + + \ No newline at end of file diff --git a/web/templates/send_update.html b/web/templates/send_update.html new file mode 100644 index 0000000..0458121 --- /dev/null +++ b/web/templates/send_update.html @@ -0,0 +1,42 @@ + + + + Send Update + + + +
+

Send Newsletter Update

+ Back to Subscribers + Logout + + {{ if .success }} +
{{ .success }}
+ {{ end }} + {{ if .error }} +
{{ .error }}
+ {{ end }} + +
+ + + + + + + +
+
+ + \ No newline at end of file