aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/cli.py
blob: b26b35b7c3d139131da7caf0448a0fe895f3fe7f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

"""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 .auth import validate_new_password
from .extensions import db, mail
from .models import User

USERS_CLI = AppGroup("users", help="Manage users.")
MAIL_CLI = AppGroup("mail", help="Handle mail")
DB_CLI = AppGroup("db", help="Handle database")


def _get_user_or_fail(username: str):
    """Return a user by username or report a CLI-friendly error.

    :param username: Username to look up in the database.
    :returns: Matching user record.
    :raises click.ClickException: If no matching username exists.
    """
    user = db.session.scalar(sa.select(User).where(User.username == username))
    if user is None:
        raise click.ClickException(f"User {username!r} does not exist.")
    return user


@USERS_CLI.command("create", help="Create a user.")
@click.option("--username", prompt="Username", help="Username for the new user.")
@click.password_option(confirmation_prompt=True)
def create_user(username: str, password: str) -> None:
    """Create a user with a securely hashed password.

    :param username: Username for the new user.
    :param password: Plain-text password to hash and store.
    :raises click.ClickException: If the credentials are invalid or the user exists.
    """
    username = username.strip()
    if not username:
        raise click.ClickException("Username must not be empty.")

    try:
        validate_new_password(password)
    except ValueError as exc:
        raise click.ClickException(str(exc)) from exc

    db.session.add(User(username=username, password=password))
    try:
        db.session.commit()
    except IntegrityError as exc:
        db.session.rollback()
        raise click.ClickException(f"User {username!r} already exists.") from exc

    click.echo(f"Created user {username!r}.")


@USERS_CLI.command("list", help="List registered users.")
def list_users() -> None:
    """List user IDs and usernames in alphabetical order.

    Write either a sorted ID/username table or a message if no accounts exist.
    """
    users = db.session.scalars(sa.select(User).order_by(User.username)).all()
    if not users:
        click.echo("No users found.")
        return

    click.echo("ID\tUSERNAME")
    for user in users:
        click.echo(f"{user.id}\t{user.username}")


@USERS_CLI.command("set-password", help="Reset a user's password.")
@click.argument("username")
@click.password_option(confirmation_prompt=True)
def set_user_password(username: str, password: str) -> None:
    """Change a user's password without displaying it.

    :param username: Username of the account to update.
    :param password: New plain-text password to hash and store.
    :raises click.ClickException: If the account is missing or the password is invalid.
    """
    try:
        validate_new_password(password)
    except ValueError as exc:
        raise click.ClickException(str(exc)) from exc

    user = _get_user_or_fail(username)
    user.password = password
    db.session.commit()
    click.echo(f"Updated password for user {username!r}.")


@USERS_CLI.command("delete", help="Delete a user.")
@click.argument("username")
@click.option("-y", "--yes", is_flag=True, help="Skip the deletion confirmation.")
def delete_user(username: str, yes: bool) -> None:
    """Permanently delete a user after confirmation, unless --yes is passed.

    :param username: Username of the account to remove.
    :param yes: Whether to skip the confirmation prompt.
    :raises click.ClickException: If the account does not exist.
    """
    user = _get_user_or_fail(username)
    if not yes:
        click.confirm(f"Delete user {username!r}?", abort=True)

    db.session.delete(user)
    db.session.commit()
    click.echo(f"Deleted user {username!r}.")


@MAIL_CLI.command("test", help="Send an email to test the SMTP configuration")
@click.option("--to", "recipient", help="Recipient address (defaults to DIGEST_EMAIL).")
def send_test_mail(recipient: str | None) -> None:
    """Send a test email using the configured SMTP server.

    :param recipient: Optional recipient overriding DIGEST_EMAIL.
    :raises click.ClickException: If configuration is missing or sending fails.
    """
    recipient = recipient or current_app.config.get("DIGEST_EMAIL")
    if not recipient:
        raise click.ClickException(
            "No recipient specified. Set DIGEST_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}.")


def _existing_table_names() -> set[str]:
    """Return existing table names without modifying the database schema.

    :returns: Names of tables in the configured database.
    """
    with db.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.

    Refuse to initialize a nonempty schema, then run the complete Alembic upgrade chain.

    :raises click.ClickException: If the database already contains tables.
    """
    if _existing_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.

    Require a previously migrated schema before applying pending Alembic revisions.

    :raises click.ClickException: If the database has no Alembic revision table.
    """
    if "alembic_version" not in _existing_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 stamp its revision "
            "only if appropriate (the 'flask migrate' CLI is development-only)."
        )

    migrate_upgrade()
    click.echo("Database upgraded to the latest migration revision.")