aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/cli.py
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--webmentions_ssg/cli.py (renamed from webmentions_ssg/cli/users.py)94
1 files changed, 88 insertions, 6 deletions
diff --git a/webmentions_ssg/cli/users.py b/webmentions_ssg/cli.py
index a48fc71..0387ba6 100644
--- a/webmentions_ssg/cli/users.py
+++ b/webmentions_ssg/cli.py
@@ -2,22 +2,26 @@
#
# SPDX-License-Identifier: BSD-3-Clause
-"""Provide commands for managing application user accounts."""
+"""Manage users, mail settings, and database migrations."""
import click
import sqlalchemy as sa
+from flask import current_app
from flask.cli import AppGroup
+from flask_mail import Message
+from flask_migrate import upgrade as migrate_upgrade
+from sqlalchemy import inspect
from sqlalchemy.exc import IntegrityError
-from .. import DATABASE
-from ..security import validate_password
+from .auth import validate_password
+from .extensions import DATABASE, MAIL
+from .models import User
USERS_CLI = AppGroup("users", help="Manage users.")
def _require_user(username: str):
"""Return a user by username or report a CLI-friendly error."""
- from ..models import User
user = DATABASE.session.scalar(sa.select(User).where(User.username == username))
if user is None:
@@ -36,7 +40,6 @@ def create_user(username: str, password: str) -> None:
:param password: Plain-text password to hash and store.
:raises click.ClickException: If the credentials are invalid or the user exists.
"""
- from ..models import User
username = username.strip()
if not username:
@@ -63,7 +66,6 @@ def create_user(username: str, password: str) -> None:
@USERS_CLI.command("list", help="List registered users.")
def list_users() -> None:
"""List user IDs and usernames in alphabetical order."""
- from ..models import User
users = DATABASE.session.scalars(sa.select(User).order_by(User.username)).all()
if not users:
@@ -115,3 +117,83 @@ def delete_user(username: str, yes: bool) -> None:
DATABASE.session.delete(user)
DATABASE.session.commit()
click.echo(f"Deleted user {username!r}.")
+
+
+MAIL_CLI = AppGroup("mail", help="Handle mail")
+
+
+@MAIL_CLI.command("test", help="Send an email to test the SMTP configuration")
+@click.option(
+ "--to", "recipient", help="Recipient address (defaults to NOTIFICATION_EMAIL)."
+)
+def send_test_mail(recipient: str | None) -> None:
+ """
+ Send a test email using the configured SMTP server.
+
+ :param recipient: Optional recipient overriding NOTIFICATION_EMAIL.
+ :raises click.ClickException: If configuration is missing or sending fails.
+ """
+ recipient = recipient or current_app.config.get("NOTIFICATION_EMAIL")
+ if not recipient:
+ raise click.ClickException(
+ "No recipient specified. Set NOTIFICATION_EMAIL or pass --to."
+ )
+
+ sender = current_app.config.get("MAIL_DEFAULT_SENDER")
+ if not sender:
+ raise click.ClickException("MAIL_DEFAULT_SENDER is not configured.")
+
+ message = Message(
+ subject="webmentions-ssg: test email",
+ sender=sender,
+ recipients=[recipient],
+ body=(
+ "This is a test email from webmentions-ssg.\n\n"
+ "If you received this message, the outgoing mail configuration works.\n"
+ ),
+ )
+
+ try:
+ MAIL.send(message)
+ except Exception as exc:
+ raise click.ClickException(f"Could not send test email: {exc}") from exc
+
+ click.echo(f"Test email sent to {recipient}.")
+
+
+DB_CLI = AppGroup("db", help="Handle database")
+
+
+def _table_names() -> set[str]:
+ """Return existing table names without modifying the database schema."""
+ with DATABASE.engine.connect() as connection:
+ return set(inspect(connection).get_table_names())
+
+
+@DB_CLI.command("create-db", help="Create a new database using all migrations")
+def create_db() -> None:
+ """Initialize an empty database and record its Alembic revision."""
+ if _table_names():
+ raise click.ClickException(
+ "The database already contains tables. "
+ "Use 'flask db upgrade' for an existing migrated database."
+ )
+
+ # Applying migrations (rather than create_all()) keeps alembic_version in sync.
+ migrate_upgrade()
+ click.echo("Database created at the latest migration revision.")
+
+
+@DB_CLI.command("upgrade", help="Upgrade an existing database to the latest revision")
+def upgrade_db() -> None:
+ """Apply pending migrations to a previously initialized database."""
+ if "alembic_version" not in _table_names():
+ raise click.ClickException(
+ "No Flask-Migrate revision table found. "
+ "For a new, empty database run 'flask db create-db'. "
+ "For a legacy database, inspect its schema and use "
+ "'flask migrate stamp' only if appropriate."
+ )
+
+ migrate_upgrade()
+ click.echo("Database upgraded to the latest migration revision.")