"""Service token CLI commands.""" from __future__ import annotations import typer from app.cli.core.output import mask_token_text, render_service_token_result from app.schemas.auth import ServiceTokenIssueCliResponse, ServiceTokenRevokeCliResponse from app.services.auth_service import AuthService token_app = typer.Typer(help="Service token lifecycle commands.") def _with_service(ctx: typer.Context, callback): app_context = ctx.obj repository = app_context.repository_factory(app_context.settings) service = AuthService(repository, app_context.settings) try: from app.cli.core.utils import execute_command return execute_command(app_context.console, callback=lambda: callback(service, app_context)) finally: if callable(getattr(type(repository), "close", None)): repository.close() @token_app.command("issue") def issue_service_token( ctx: typer.Context, name: str = typer.Argument(..., help="Unique service token name."), user: str = typer.Option(..., "--user", help="Username to associate with this service token."), permission: str = typer.Option("read", "--permission", help="Token permission: read or trade-write."), ttl_days: int | None = typer.Option(None, "--ttl-days", help="Token TTL in days. Default: 365."), no_expiry: bool = typer.Option(False, "--no-expiry", help="Issue a token with no expiry."), ) -> None: def _issue(service: AuthService, app_context): return service.issue_service_token( name, user, permission=permission, expires_in_days=ttl_days, no_expiry=no_expiry, ) issued = _with_service(ctx, _issue) response = ServiceTokenIssueCliResponse( token_id=issued.auth_token.id, name=name, expires_at=issued.auth_token.expires_at, revoked=issued.auth_token.revoked_at is not None, token=issued.token, ) render_service_token_result(ctx.obj.console, ctx.obj.output_format, response) if ctx.obj.output_format != "json": ctx.obj.console.print(f"masked_token: {mask_token_text(issued.token)}") @token_app.command("revoke") def revoke_service_token( ctx: typer.Context, name: str = typer.Argument(..., help="Service token name to revoke."), force: bool = typer.Option(False, "--force", "-f", help="Skip confirmation prompt."), ) -> None: if not force: confirmed = typer.confirm(f"서비스 토큰 '{name}'을 폐기하시겠습니까?") if not confirmed: raise typer.Exit(code=0) def _revoke(service: AuthService, app_context): return service.revoke_service_token(name) revoked_at = _with_service(ctx, _revoke) response = ServiceTokenRevokeCliResponse( token_id="", name=name, revoked=True, revoked_at=revoked_at, ) render_service_token_result(ctx.obj.console, ctx.obj.output_format, response)