Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/object_identity_cli.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
object_identity_cli.py · 7.3 KB · 200 lines
1"""Shell management for DBBASIC identity, in the spirit of Django manage.py.
2
3This CLI operates directly on the runtime data directory, so an operator on
4the VM can bootstrap the first admin user and manage accounts, users, and
5passwords over SSH without HTTP access or tokens. Passwords are prompted
6without echo (or read from stdin for scripting) and are never printed.
7"""
8
9from __future__ import annotations
10
11import argparse
12import getpass
13import json
14import os
15import sys
16from pathlib import Path
17
18import object_credentials
19import object_identity
20
21DATA_DIR_ENV = "DBBASIC_DATA_DIR"
22ADMIN_ROLE = "admin"
23
24
25def main(argv: list[str] | None = None) -> int:
26 parser = argparse.ArgumentParser(
27 description="Manage DBBASIC identity accounts, users, and passwords from the shell."
28 )
29 parser.add_argument(
30 "--data-dir",
31 type=Path,
32 default=None,
33 help=f"runtime data directory (default: ${DATA_DIR_ENV} or ./data)",
34 )
35 subcommands = parser.add_subparsers(dest="command", required=True)
36
37 create_account = subcommands.add_parser("create-account", help="create an account")
38 create_account.add_argument("--account-id", required=True)
39 create_account.add_argument("--name", default="")
40
41 create_user = subcommands.add_parser("create-user", help="create a user")
42 create_user.add_argument("--user-id", required=True)
43 create_user.add_argument("--email")
44 create_user.add_argument("--display-name")
45 create_user.add_argument("--account-id")
46 create_user.add_argument("--roles", help="comma-separated roles")
47
48 create_superuser = subcommands.add_parser(
49 "create-superuser",
50 help="create an admin-role user and prompt for its password",
51 )
52 create_superuser.add_argument("--user-id", required=True)
53 create_superuser.add_argument("--email")
54 create_superuser.add_argument("--display-name")
55 create_superuser.add_argument("--account-id")
56 create_superuser.add_argument(
57 "--password-stdin",
58 action="store_true",
59 help="read the password from stdin instead of prompting",
60 )
61
62 set_password = subcommands.add_parser("set-password", help="set or replace a user password")
63 set_password.add_argument("--user-id", required=True)
64 set_password.add_argument(
65 "--password-stdin",
66 action="store_true",
67 help="read the password from stdin instead of prompting",
68 )
69
70 remove_password = subcommands.add_parser("remove-password", help="remove a user password")
71 remove_password.add_argument("--user-id", required=True)
72
73 list_accounts = subcommands.add_parser("list-accounts", help="list accounts")
74 list_accounts.add_argument("--json", action="store_true")
75
76 list_users = subcommands.add_parser("list-users", help="list users")
77 list_users.add_argument("--account-id")
78 list_users.add_argument("--json", action="store_true")
79
80 args = parser.parse_args(argv)
81 base_dir = _base_dir(args.data_dir)
82
83 try:
84 if args.command == "create-account":
85 account = object_identity.create_account(
86 {"account_id": args.account_id, "name": args.name},
87 base_dir=base_dir,
88 )
89 print(f"Created account {account['account_id']}")
90 return 0
91
92 if args.command == "create-user":
93 user = object_identity.create_user(
94 _user_payload(args, roles=_split_roles(args.roles)),
95 base_dir=base_dir,
96 )
97 print(f"Created user {user['user_id']}")
98 return 0
99
100 if args.command == "create-superuser":
101 password = _read_password(password_stdin=args.password_stdin)
102 user = object_identity.create_user(
103 _user_payload(args, roles=[ADMIN_ROLE]),
104 base_dir=base_dir,
105 )
106 object_credentials.set_password(user["user_id"], password, base_dir=base_dir)
107 print(f"Created superuser {user['user_id']} with role {ADMIN_ROLE} and password set")
108 return 0
109
110 if args.command == "set-password":
111 object_identity.get_user(args.user_id, base_dir=base_dir)
112 password = _read_password(password_stdin=args.password_stdin)
113 result = object_credentials.set_password(args.user_id, password, base_dir=base_dir)
114 print(f"Password {result['operation']} for user {result['user_id']}")
115 return 0
116
117 if args.command == "remove-password":
118 object_identity.get_user(args.user_id, base_dir=base_dir)
119 removed = object_credentials.remove_password(args.user_id, base_dir=base_dir)
120 print(
121 f"Password removed for user {args.user_id}"
122 if removed
123 else f"User {args.user_id} had no password"
124 )
125 return 0
126
127 if args.command == "list-accounts":
128 accounts = object_identity.list_accounts(base_dir=base_dir)
129 if args.json:
130 print(json.dumps(accounts, indent=2))
131 else:
132 for account in accounts:
133 print(f"{account['account_id']}\t{account['status']}\t{account['name']}")
134 print(f"{len(accounts)} account(s)")
135 return 0
136
137 if args.command == "list-users":
138 users = object_identity.list_users(account_id=args.account_id, base_dir=base_dir)
139 if args.json:
140 print(json.dumps(users, indent=2))
141 else:
142 for user in users:
143 roles = ",".join(user["roles"])
144 has_password = object_credentials.has_password(
145 user["user_id"], base_dir=base_dir
146 )
147 password_state = "password" if has_password else "no-password"
148 print(
149 f"{user['user_id']}\t{user['status']}\t{user['email'] or '-'}"
150 f"\t{roles or '-'}\t{password_state}"
151 )
152 print(f"{len(users)} user(s)")
153 return 0
154 except (ValueError, LookupError) as exc:
155 print(f"Error: {exc}", file=sys.stderr)
156 return 1
157
158 parser.error(f"Unknown command: {args.command}")
159 return 2
160
161
162def _base_dir(data_dir: Path | None) -> Path:
163 if data_dir is not None:
164 return data_dir
165 return Path(os.environ.get(DATA_DIR_ENV, "data"))
166
167
168def _user_payload(args: argparse.Namespace, *, roles: list[str]) -> dict[str, object]:
169 payload: dict[str, object] = {"user_id": args.user_id, "roles": roles}
170 if args.email:
171 payload["email"] = args.email
172 if args.display_name:
173 payload["display_name"] = args.display_name
174 if args.account_id:
175 payload["account_id"] = args.account_id
176 return payload
177
178
179def _split_roles(value: str | None) -> list[str]:
180 if not value:
181 return []
182 return [role.strip() for role in value.split(",") if role.strip()]
183
184
185def _read_password(*, password_stdin: bool) -> str:
186 if password_stdin:
187 password = sys.stdin.readline().rstrip("\n")
188 if not password:
189 raise ValueError("password on stdin is empty")
190 return password
191
192 password = getpass.getpass("Password: ")
193 confirmation = getpass.getpass("Password (again): ")
194 if password != confirmation:
195 raise ValueError("passwords do not match")
196 return password
197
198
199if __name__ == "__main__":
200 raise SystemExit(main())