feat: add initial-admin CLI command
This commit is contained in:
parent
bcddf5d1c8
commit
4e83c3807e
2 changed files with 86 additions and 20 deletions
|
|
@ -6,8 +6,10 @@ import typer
|
|||
|
||||
from porchlight.config import Settings
|
||||
from porchlight.invite.service import MagicLinkService
|
||||
from porchlight.models import User
|
||||
from porchlight.store.sqlite.db import open_db
|
||||
from porchlight.store.sqlite.repositories import SQLiteMagicLinkRepository
|
||||
from porchlight.store.sqlite.repositories import SQLiteMagicLinkRepository, SQLiteUserRepository
|
||||
from porchlight.userid import generate_unique_userid
|
||||
|
||||
PACKAGE_DIR = Path(__file__).resolve().parent
|
||||
MIGRATIONS_DIR = PACKAGE_DIR / "store" / "sqlite" / "migrations"
|
||||
|
|
@ -24,6 +26,25 @@ async def _create_invite(settings: Settings, username: str, ttl: int, note: str
|
|||
return f"{settings.issuer}/register/{link.token}"
|
||||
|
||||
|
||||
async def _initial_admin(settings: Settings, username: str, groups: list[str]) -> str:
|
||||
"""Create an admin user and invite link, return the full registration URL."""
|
||||
async with open_db(settings.sqlite_path, MIGRATIONS_DIR) as db:
|
||||
user_repo = SQLiteUserRepository(db)
|
||||
|
||||
existing = await user_repo.get_by_username(username)
|
||||
if existing is not None:
|
||||
raise typer.BadParameter(f"User '{username}' already exists.")
|
||||
|
||||
userid = await generate_unique_userid(user_repo)
|
||||
user = User(userid=userid, username=username, groups=groups)
|
||||
await user_repo.create(user)
|
||||
|
||||
magic_link_repo = SQLiteMagicLinkRepository(db)
|
||||
service = MagicLinkService(magic_link_repo, ttl=settings.invite_ttl)
|
||||
link = await service.create(username=username, created_by="cli", note="initial admin setup")
|
||||
return f"{settings.issuer}/register/{link.token}"
|
||||
|
||||
|
||||
@app.command()
|
||||
def create_invite(
|
||||
username: str,
|
||||
|
|
@ -37,5 +58,17 @@ def create_invite(
|
|||
typer.echo(url)
|
||||
|
||||
|
||||
@app.command()
|
||||
def initial_admin(
|
||||
username: str,
|
||||
group: Annotated[Optional[list[str]], typer.Option(help="Groups to assign (repeatable)")] = None,
|
||||
) -> None:
|
||||
"""Bootstrap the first admin user with a registration link."""
|
||||
settings = Settings()
|
||||
groups = group if group is not None else ["admin", "users"]
|
||||
url = asyncio.run(_initial_admin(settings, username, groups))
|
||||
typer.echo(url)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
app()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue