aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/cli/users.py
blob: 2dcb17ec44c9ca3ffbb6ea70982f99e8b5df0028 (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
import click
import sqlalchemy as sa
from flask.cli import AppGroup

from .. import DATABASE

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:
        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.
    """
    from ..models import User

    username = username.strip()
    if not username:
        raise click.ClickException("Username must not be empty.")

    if not password:
        raise click.ClickException("Password must not be empty.")

    if DATABASE.session.scalar(sa.select(User).where(User.username == username)):
        raise click.ClickException(f"User {username!r} already exists.")

    DATABASE.session.add(User(username=username, password=password))
    try:
        DATABASE.session.commit()
    except sa.exc.IntegrityError as exc:
        DATABASE.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."""
    from ..models import User

    users = DATABASE.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 empty.
    """
    if not password:
        raise click.ClickException("Password must not be empty.")

    user = _require_user(username)
    user.password = password
    DATABASE.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 = _require_user(username)
    if not yes:
        click.confirm(f"Delete user {username!r}?", abort=True)

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