inferyx-codegate 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codegate/__init__.py +8 -0
- codegate/__main__.py +3 -0
- codegate/api/__init__.py +0 -0
- codegate/api/admin.py +457 -0
- codegate/api/deps.py +36 -0
- codegate/api/devproxy.py +132 -0
- codegate/api/public.py +371 -0
- codegate/app.py +115 -0
- codegate/auth/__init__.py +0 -0
- codegate/auth/csrf.py +43 -0
- codegate/auth/native.py +111 -0
- codegate/auth/passwords.py +88 -0
- codegate/auth/saml.py +222 -0
- codegate/auth/sessions.py +121 -0
- codegate/cli/__init__.py +0 -0
- codegate/cli/auth_cmd.py +168 -0
- codegate/cli/backup_cmd.py +114 -0
- codegate/cli/common.py +103 -0
- codegate/cli/doctor_cmd.py +136 -0
- codegate/cli/main.py +526 -0
- codegate/cli/nginx_setup.py +220 -0
- codegate/cli/setup_cmd.py +401 -0
- codegate/cli/ssh_setup.py +114 -0
- codegate/cli/upgrade_cmd.py +209 -0
- codegate/config.py +161 -0
- codegate/db.py +297 -0
- codegate/errors.py +122 -0
- codegate/jobs.py +133 -0
- codegate/pages.py +177 -0
- codegate/resources/__init__.py +20 -0
- codegate/resources/docker/Dockerfile +36 -0
- codegate/resources/nginx/codegate.conf.tmpl +51 -0
- codegate/resources/nginx/map.conf +5 -0
- codegate/resources/nginx/site.conf.tmpl +9 -0
- codegate/resources/nginx/user.conf.tmpl +19 -0
- codegate/resources/systemd/codegate-backup.service.tmpl +7 -0
- codegate/resources/systemd/codegate-backup.timer +10 -0
- codegate/resources/systemd/codegate.service.tmpl +20 -0
- codegate/static/admin/3rdpartylicenses.txt +614 -0
- codegate/static/admin/chunk-0r_p7pcB.js +672 -0
- codegate/static/admin/chunk-BoGqYCjO.js +1260 -0
- codegate/static/admin/chunk-BqiJ460N.js +1269 -0
- codegate/static/admin/chunk-BtoaIoDj.js +449 -0
- codegate/static/admin/chunk-CB4E-q63.js +255 -0
- codegate/static/admin/chunk-CMN75K3s.js +181 -0
- codegate/static/admin/chunk-CW_CPa20.js +106 -0
- codegate/static/admin/chunk-CcgsCK7w.js +393 -0
- codegate/static/admin/chunk-Cjwyuum6.js +375 -0
- codegate/static/admin/chunk-D6j6hnz3.js +1 -0
- codegate/static/admin/chunk-D9RytJgO.js +1 -0
- codegate/static/admin/chunk-DA6TldFU.js +35 -0
- codegate/static/admin/chunk-DFGdyoNb.js +1 -0
- codegate/static/admin/chunk-DXvCZ3pT.js +1 -0
- codegate/static/admin/chunk-DstgVdtz.js +27 -0
- codegate/static/admin/chunk-kPDFCwHP.js +102 -0
- codegate/static/admin/chunk-yikJ2ObQ.js +1 -0
- codegate/static/admin/favicon.ico +0 -0
- codegate/static/admin/index.html +14 -0
- codegate/static/admin/main-LWBML7JF.js +2347 -0
- codegate/static/admin/media/material-icons-JLIDJUWE.woff +0 -0
- codegate/static/admin/media/material-icons-LEZCGFVT.woff2 +0 -0
- codegate/static/admin/styles-YWRWGLKG.css +1 -0
- codegate/system/__init__.py +27 -0
- codegate/system/base.py +165 -0
- codegate/system/devdocker.py +90 -0
- codegate/system/fake.py +199 -0
- codegate/system/real.py +493 -0
- codegate/system/shell.py +40 -0
- codegate/users.py +262 -0
- codegate/workspace.py +355 -0
- inferyx_codegate-1.1.0.dist-info/METADATA +217 -0
- inferyx_codegate-1.1.0.dist-info/RECORD +74 -0
- inferyx_codegate-1.1.0.dist-info/WHEEL +4 -0
- inferyx_codegate-1.1.0.dist-info/entry_points.txt +2 -0
codegate/cli/main.py
ADDED
|
@@ -0,0 +1,526 @@
|
|
|
1
|
+
"""`codegate` command line."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import typer
|
|
11
|
+
from rich.table import Table
|
|
12
|
+
|
|
13
|
+
from .. import __version__
|
|
14
|
+
from ..config import env_file_path, get_settings, reset_settings_cache
|
|
15
|
+
from ..errors import AppError
|
|
16
|
+
from .common import console, die, require_root
|
|
17
|
+
|
|
18
|
+
app = typer.Typer(help="CodeGate: browser VS Code with AWS SSO, per-user Docker workspaces.",
|
|
19
|
+
no_args_is_help=True, pretty_exceptions_show_locals=False)
|
|
20
|
+
user_app = typer.Typer(help="Manage users (works even if the web UI is down).", no_args_is_help=True)
|
|
21
|
+
admin_app = typer.Typer(help="Manage admins.", no_args_is_help=True)
|
|
22
|
+
image_app = typer.Typer(help="Workspace Docker image.", no_args_is_help=True)
|
|
23
|
+
nginx_app = typer.Typer(help="Nginx routes.", no_args_is_help=True)
|
|
24
|
+
config_app = typer.Typer(help="View / change configuration.", no_args_is_help=True)
|
|
25
|
+
app.add_typer(user_app, name="user")
|
|
26
|
+
app.add_typer(admin_app, name="admin")
|
|
27
|
+
app.add_typer(image_app, name="image")
|
|
28
|
+
app.add_typer(nginx_app, name="nginx")
|
|
29
|
+
app.add_typer(config_app, name="config")
|
|
30
|
+
|
|
31
|
+
from .auth_cmd import auth_app, user_passwd, user_unlock # noqa: E402
|
|
32
|
+
|
|
33
|
+
app.add_typer(auth_app, name="auth")
|
|
34
|
+
user_app.command("passwd")(user_passwd)
|
|
35
|
+
user_app.command("unlock")(user_unlock)
|
|
36
|
+
|
|
37
|
+
from .backup_cmd import create_backup, prune, restore_backup # noqa: E402
|
|
38
|
+
from .doctor_cmd import doctor # noqa: E402
|
|
39
|
+
from .setup_cmd import build_workspace_image, setup # noqa: E402
|
|
40
|
+
from .upgrade_cmd import post_upgrade, upgrade # noqa: E402
|
|
41
|
+
|
|
42
|
+
app.command()(setup)
|
|
43
|
+
app.command()(upgrade)
|
|
44
|
+
app.command(name="post-upgrade", hidden=True)(post_upgrade)
|
|
45
|
+
app.command()(doctor)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _logging(level=logging.INFO):
|
|
49
|
+
logging.basicConfig(level=level, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _guard(fn):
|
|
53
|
+
"""Turn AppErrors into clean CLI messages."""
|
|
54
|
+
import functools
|
|
55
|
+
|
|
56
|
+
@functools.wraps(fn)
|
|
57
|
+
def wrapper(*a, **kw):
|
|
58
|
+
try:
|
|
59
|
+
return fn(*a, **kw)
|
|
60
|
+
except AppError as exc:
|
|
61
|
+
console.print(f"[red]✗ {exc.message}[/]")
|
|
62
|
+
if exc.details:
|
|
63
|
+
console.print(f"[dim]{exc.details}[/]")
|
|
64
|
+
raise typer.Exit(1)
|
|
65
|
+
return wrapper
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# ------------------------------------------------------------------ basics
|
|
69
|
+
@app.command()
|
|
70
|
+
def version(short: bool = typer.Option(False, "--short")):
|
|
71
|
+
"""Show version."""
|
|
72
|
+
console.print(__version__ if short else f"CodeGate v{__version__}")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@app.command()
|
|
76
|
+
def run(host: str = typer.Option(None), port: int = typer.Option(None),
|
|
77
|
+
reload: bool = typer.Option(False, hidden=True)):
|
|
78
|
+
"""Run the server in the foreground (systemd uses this)."""
|
|
79
|
+
import uvicorn
|
|
80
|
+
s = get_settings()
|
|
81
|
+
_logging()
|
|
82
|
+
uvicorn.run("codegate.app:create_app", factory=True, host=host or s.listen_host,
|
|
83
|
+
port=port or s.listen_port, proxy_headers=True, forwarded_allow_ips="127.0.0.1",
|
|
84
|
+
reload=reload, log_level="info")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@app.command()
|
|
88
|
+
def dev(port: int = typer.Option(8700), data_dir: Path = typer.Option(Path("./codegate-dev")),
|
|
89
|
+
admin_email: str = typer.Option(None, help="Default admin email (first run only)"),
|
|
90
|
+
docker: bool = typer.Option(False, "--docker",
|
|
91
|
+
help="Run REAL VS Code containers with local Docker "
|
|
92
|
+
"(build the image first)")):
|
|
93
|
+
"""Run locally in DEV MODE (simulated Linux users/nginx). Login is the real password login."""
|
|
94
|
+
data_dir = data_dir.resolve()
|
|
95
|
+
if docker:
|
|
96
|
+
os.environ.update({"CODEGATE_DEV_DOCKER": "true",
|
|
97
|
+
"CODEGATE_HOME_ROOT": str(data_dir / "homes")})
|
|
98
|
+
# laptops often have dev tools on 9100+; keep workspace ports out of the way
|
|
99
|
+
os.environ.setdefault("CODEGATE_PORT_RANGE_START", "19100")
|
|
100
|
+
os.environ.setdefault("CODEGATE_PORT_RANGE_END", "19999")
|
|
101
|
+
if not os.environ.get("DOCKER_HOST"):
|
|
102
|
+
# docker-py ignores `docker context`; Docker Desktop's socket is not the default
|
|
103
|
+
r = subprocess.run(["docker", "context", "inspect", "--format",
|
|
104
|
+
"{{.Endpoints.docker.Host}}"], capture_output=True, text=True)
|
|
105
|
+
if r.returncode == 0 and r.stdout.strip():
|
|
106
|
+
os.environ["DOCKER_HOST"] = r.stdout.strip()
|
|
107
|
+
os.environ.update({
|
|
108
|
+
"CODEGATE_DEV_MODE": "true", "CODEGATE_DATA_DIR": str(data_dir),
|
|
109
|
+
"CODEGATE_PUBLIC_SCHEME": "http", "CODEGATE_DOMAIN": f"localhost:{port}",
|
|
110
|
+
"CODEGATE_ENV_FILE": str(data_dir / "dev.env"), "CODEGATE_LISTEN_PORT": str(port),
|
|
111
|
+
})
|
|
112
|
+
reset_settings_cache()
|
|
113
|
+
s = get_settings()
|
|
114
|
+
from .auth_cmd import _db, admin_with_password_exists, ensure_default_admin
|
|
115
|
+
with _db() as db:
|
|
116
|
+
has_admin = admin_with_password_exists(db)
|
|
117
|
+
if not has_admin:
|
|
118
|
+
if not admin_email:
|
|
119
|
+
die("First run: pass --admin-email you@company.com to create the default admin")
|
|
120
|
+
interactive = sys.stdin.isatty() and not os.environ.get("CODEGATE_DEV_ADMIN_PASSWORD")
|
|
121
|
+
console.print("[bold]Creating the default admin[/]")
|
|
122
|
+
console.print(" ✓ " + ensure_default_admin(
|
|
123
|
+
admin_email, os.environ.get("CODEGATE_DEV_ADMIN_PASSWORD") or None,
|
|
124
|
+
interactive=interactive, actor="dev"))
|
|
125
|
+
console.print(f"[bold yellow]DEV MODE{' + Docker' if docker else ''}[/] → "
|
|
126
|
+
f"http://localhost:{port}{s.base_path}/login")
|
|
127
|
+
if docker:
|
|
128
|
+
from ..system import get_system
|
|
129
|
+
sysm = get_system()
|
|
130
|
+
if not sysm.docker_ok():
|
|
131
|
+
die("Docker is not reachable. Start Docker Desktop (or set DOCKER_HOST).")
|
|
132
|
+
if not sysm.image_exists(s.workspace_image):
|
|
133
|
+
die(f"Image {s.workspace_image} missing. Build it: docker build -t {s.workspace_image} "
|
|
134
|
+
"src/codegate/resources/docker")
|
|
135
|
+
run(host="127.0.0.1", port=port)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _systemctl(*args: str) -> None:
|
|
139
|
+
require_root()
|
|
140
|
+
r = subprocess.run(["systemctl", *args, "codegate"])
|
|
141
|
+
if r.returncode != 0:
|
|
142
|
+
raise typer.Exit(r.returncode)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@app.command()
|
|
146
|
+
def start():
|
|
147
|
+
"""Start the service."""
|
|
148
|
+
_systemctl("start")
|
|
149
|
+
console.print("[green]✓ started[/]")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@app.command()
|
|
153
|
+
def stop():
|
|
154
|
+
"""Stop the service (user containers keep running)."""
|
|
155
|
+
_systemctl("stop")
|
|
156
|
+
console.print("[green]✓ stopped[/]")
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@app.command()
|
|
160
|
+
def restart():
|
|
161
|
+
"""Restart the service."""
|
|
162
|
+
_systemctl("restart")
|
|
163
|
+
console.print("[green]✓ restarted[/]")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@app.command()
|
|
167
|
+
def status():
|
|
168
|
+
"""Service status + summary."""
|
|
169
|
+
from .common import read_marker
|
|
170
|
+
s = get_settings()
|
|
171
|
+
active = subprocess.run(["systemctl", "is-active", "codegate"], capture_output=True,
|
|
172
|
+
text=True).stdout.strip() or "unknown"
|
|
173
|
+
m = read_marker()
|
|
174
|
+
t = Table(show_header=False, box=None)
|
|
175
|
+
t.add_row("Service", f"[{'green' if active == 'active' else 'red'}]{active}[/]")
|
|
176
|
+
t.add_row("Version", f"package v{__version__} / installed v{m.get('version', '-')}")
|
|
177
|
+
t.add_row("URL", f"{s.public_url}/")
|
|
178
|
+
try:
|
|
179
|
+
from sqlalchemy import func, select
|
|
180
|
+
from ..db import LoginSession, Usage, User, session_scope
|
|
181
|
+
with session_scope() as db:
|
|
182
|
+
t.add_row("Users", str(db.scalar(select(func.count()).select_from(User))))
|
|
183
|
+
t.add_row("Pending", str(db.scalar(select(func.count()).select_from(User)
|
|
184
|
+
.where(User.status == "pending"))))
|
|
185
|
+
t.add_row("Running workspaces", str(db.scalar(select(func.count()).select_from(Usage)
|
|
186
|
+
.where(Usage.running.is_(True)))))
|
|
187
|
+
t.add_row("Sessions", str(db.scalar(select(func.count()).select_from(LoginSession))))
|
|
188
|
+
except Exception as exc: # noqa: BLE001
|
|
189
|
+
t.add_row("Database", f"[red]{exc}[/]")
|
|
190
|
+
console.print(t)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
@app.command()
|
|
194
|
+
def logs(follow: bool = typer.Option(False, "--follow", "-f"), lines: int = 100):
|
|
195
|
+
"""Show service logs."""
|
|
196
|
+
f = get_settings().log_dir / "codegate.log"
|
|
197
|
+
if not f.exists():
|
|
198
|
+
die(f"No log file at {f}")
|
|
199
|
+
os.execvp("tail", ["tail", f"-n{lines}", *(["-f"] if follow else []), str(f)])
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
@app.command()
|
|
203
|
+
@_guard
|
|
204
|
+
def migrate():
|
|
205
|
+
"""Create / upgrade the database schema."""
|
|
206
|
+
from ..db import migrate as _m
|
|
207
|
+
old, new = _m()
|
|
208
|
+
console.print(f"[green]✓ schema v{old} -> v{new}[/]")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
@app.command()
|
|
212
|
+
def backup(homes: bool = typer.Option(False, help="Also back up user home folders"),
|
|
213
|
+
do_prune: bool = typer.Option(False, "--prune", help="Delete backups older than "
|
|
214
|
+
"backup_keep_days")):
|
|
215
|
+
"""Back up DB, config and nginx files."""
|
|
216
|
+
require_root()
|
|
217
|
+
f = create_backup(include_homes=homes, label="auto" if do_prune else "manual")
|
|
218
|
+
console.print(f"[green]✓ backup:[/] {f}")
|
|
219
|
+
if do_prune:
|
|
220
|
+
from ..db import get_setting, session_scope
|
|
221
|
+
with session_scope() as db:
|
|
222
|
+
keep = int(get_setting(db, "backup_keep_days") or 7)
|
|
223
|
+
console.print(f" pruned {prune(keep)} old backup(s)")
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
@app.command()
|
|
227
|
+
def restore(file: Path, homes: bool = typer.Option(False), yes: bool = typer.Option(False, "-y")):
|
|
228
|
+
"""Restore from a backup file (stops the service while restoring)."""
|
|
229
|
+
require_root()
|
|
230
|
+
if not file.exists():
|
|
231
|
+
die(f"{file} not found")
|
|
232
|
+
if not yes and not typer.confirm(f"Restore {file}? Current DB/config will be replaced"):
|
|
233
|
+
raise typer.Exit(0)
|
|
234
|
+
subprocess.run(["systemctl", "stop", "codegate"])
|
|
235
|
+
restore_backup(file, include_homes=homes)
|
|
236
|
+
subprocess.run(["systemctl", "start", "codegate"])
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
@app.command()
|
|
240
|
+
def uninstall(purge: bool = typer.Option(False, help="Also delete DB, config and backups "
|
|
241
|
+
"(user homes are never deleted)")):
|
|
242
|
+
"""Remove CodeGate service, nginx integration and containers."""
|
|
243
|
+
require_root()
|
|
244
|
+
if not typer.confirm("Stop and remove CodeGate (user containers will be removed)?"):
|
|
245
|
+
raise typer.Exit(0)
|
|
246
|
+
from . import nginx_setup
|
|
247
|
+
subprocess.run(["systemctl", "disable", "--now", "codegate", "codegate-backup.timer"])
|
|
248
|
+
for f in ("codegate.service", "codegate-backup.service", "codegate-backup.timer"):
|
|
249
|
+
Path("/etc/systemd/system", f).unlink(missing_ok=True)
|
|
250
|
+
subprocess.run(["systemctl", "daemon-reload"])
|
|
251
|
+
try:
|
|
252
|
+
nginx_setup.remove()
|
|
253
|
+
console.print(" [green]✓[/] nginx integration removed")
|
|
254
|
+
except Exception as exc: # noqa: BLE001
|
|
255
|
+
console.print(f" [yellow]! nginx: {exc}[/]")
|
|
256
|
+
subprocess.run("docker ps -aq --filter label=codegate.managed=1 | xargs -r docker rm -f",
|
|
257
|
+
shell=True)
|
|
258
|
+
if purge:
|
|
259
|
+
import shutil
|
|
260
|
+
s = get_settings()
|
|
261
|
+
shutil.rmtree(s.data_dir, ignore_errors=True)
|
|
262
|
+
env_file_path().unlink(missing_ok=True)
|
|
263
|
+
console.print("[green]✓ CodeGate removed.[/] Linux users and /home folders were kept. "
|
|
264
|
+
"Remove the package with: pip uninstall inferyx-codegate")
|
|
265
|
+
console.print(f" [dim]SSH stays blocked for the kept workspace users "
|
|
266
|
+
f"({get_settings().sshd_dropin}); delete that file to allow it.[/]")
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
# ------------------------------------------------------------------ config
|
|
270
|
+
@config_app.command("show")
|
|
271
|
+
def config_show():
|
|
272
|
+
"""Show effective configuration (secrets hidden)."""
|
|
273
|
+
s = get_settings()
|
|
274
|
+
t = Table(show_header=True)
|
|
275
|
+
t.add_column("Setting")
|
|
276
|
+
t.add_column("Value")
|
|
277
|
+
for k, v in s.model_dump().items():
|
|
278
|
+
t.add_row(k, "********" if "secret" in k and v else str(v))
|
|
279
|
+
console.print(t)
|
|
280
|
+
console.print(f"[dim]file: {env_file_path()}[/]")
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
@config_app.command("set")
|
|
284
|
+
def config_set(key: str, value: str, no_restart: bool = typer.Option(False)):
|
|
285
|
+
"""Set a value in the env file, e.g. CODEGATE_SAML_IDP_METADATA_URL <url>."""
|
|
286
|
+
require_root()
|
|
287
|
+
from .setup_cmd import _read_env, _write_env
|
|
288
|
+
key = key.upper()
|
|
289
|
+
if not key.startswith("CODEGATE_"):
|
|
290
|
+
key = "CODEGATE_" + key
|
|
291
|
+
env = _read_env()
|
|
292
|
+
env[key] = value
|
|
293
|
+
_write_env(env)
|
|
294
|
+
console.print(f"[green]✓ {key} saved[/]")
|
|
295
|
+
if not no_restart and subprocess.run(["systemctl", "is-active", "--quiet", "codegate"]).returncode == 0:
|
|
296
|
+
subprocess.run(["systemctl", "restart", "codegate"])
|
|
297
|
+
console.print("[green]✓ service restarted[/]")
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
# ------------------------------------------------------------------ image / nginx
|
|
301
|
+
@image_app.command("build")
|
|
302
|
+
def image_build(no_cache: bool = typer.Option(False)):
|
|
303
|
+
"""Build the workspace image (code-server + Python + AWS CLI)."""
|
|
304
|
+
require_root()
|
|
305
|
+
from .common import dockerfile_sha, write_marker
|
|
306
|
+
with console.status("docker build…"):
|
|
307
|
+
console.print(f"[green]✓ built {build_workspace_image(no_cache)}[/]")
|
|
308
|
+
write_marker(dockerfile_sha=dockerfile_sha())
|
|
309
|
+
console.print("Recreate running workspaces to use it: sudo codegate user rebuild --all")
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
@nginx_app.command("sync")
|
|
313
|
+
@_guard
|
|
314
|
+
def nginx_sync():
|
|
315
|
+
"""Regenerate all user nginx routes from the DB (test + reload)."""
|
|
316
|
+
require_root()
|
|
317
|
+
from ..db import audit, session_scope
|
|
318
|
+
from ..workspace import nginx_sync_all
|
|
319
|
+
with session_scope() as db:
|
|
320
|
+
res = nginx_sync_all(db)
|
|
321
|
+
audit(db, "nginx.sync", actor="cli", **res)
|
|
322
|
+
console.print(f"[green]✓ {len(res['written'])} routes written, {len(res['removed'])} removed[/]")
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
# ------------------------------------------------------------------ users
|
|
326
|
+
def _db():
|
|
327
|
+
from ..db import migrate, session_scope
|
|
328
|
+
migrate()
|
|
329
|
+
return session_scope()
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
@user_app.command("list")
|
|
333
|
+
def user_list(status: str = typer.Option(None, help="pending|active|disabled")):
|
|
334
|
+
"""List users."""
|
|
335
|
+
from sqlalchemy import select
|
|
336
|
+
from ..db import User
|
|
337
|
+
with _db() as db:
|
|
338
|
+
q = select(User).order_by(User.created_at)
|
|
339
|
+
if status:
|
|
340
|
+
q = q.where(User.status == status)
|
|
341
|
+
t = Table()
|
|
342
|
+
for c in ("username", "email", "status", "role", "plan", "cpu", "ram", "disk", "port"):
|
|
343
|
+
t.add_column(c)
|
|
344
|
+
for u in db.scalars(q):
|
|
345
|
+
role = "admin" + ("+user" if u.has_workspace else "") if u.is_admin else "user"
|
|
346
|
+
t.add_row(u.username, u.email, u.status, role, u.plan, str(u.cpu), f"{u.mem_mb}M",
|
|
347
|
+
f"{u.disk_gb}G", str(u.port or "-"))
|
|
348
|
+
console.print(t)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
@user_app.command("add")
|
|
352
|
+
@_guard
|
|
353
|
+
def user_add(email: str, username: str = typer.Option(None), plan: str = typer.Option(None),
|
|
354
|
+
password: bool = typer.Option(False, "--password",
|
|
355
|
+
help="Prompt for a password (native login)"),
|
|
356
|
+
cpu: float = typer.Option(None), mem_mb: int = typer.Option(None),
|
|
357
|
+
disk_gb: int = typer.Option(None), sudo: bool = typer.Option(False),
|
|
358
|
+
no_internet: bool = typer.Option(False), shared: bool = typer.Option(False)):
|
|
359
|
+
"""Add an approved user and create their workspace."""
|
|
360
|
+
require_root()
|
|
361
|
+
from ..users import create_user
|
|
362
|
+
opts = {k: v for k, v in dict(cpu=cpu, mem_mb=mem_mb, disk_gb=disk_gb).items() if v is not None}
|
|
363
|
+
with _db() as db:
|
|
364
|
+
if password:
|
|
365
|
+
from .auth_cmd import prompt_new_password
|
|
366
|
+
opts["password"] = prompt_new_password(db, email=email)
|
|
367
|
+
opts["must_change_password"] = True
|
|
368
|
+
u = create_user(db, email=email, actor="cli", username=username, plan=plan, sudo=sudo,
|
|
369
|
+
internet=not no_internet, shared_folder=shared, **opts)
|
|
370
|
+
console.print(f"[green]✓ {u.email} → {u.username} (uid {u.uid}, port {u.port}, plan {u.plan})[/]")
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
@user_app.command("show")
|
|
374
|
+
@_guard
|
|
375
|
+
def user_show(ident: str):
|
|
376
|
+
"""Show one user."""
|
|
377
|
+
from ..users import get_user, user_dict
|
|
378
|
+
with _db() as db:
|
|
379
|
+
d = user_dict(get_user(db, ident))
|
|
380
|
+
t = Table(show_header=False)
|
|
381
|
+
for k, v in d.items():
|
|
382
|
+
t.add_row(k, str(v))
|
|
383
|
+
console.print(t)
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
@user_app.command("set")
|
|
387
|
+
@_guard
|
|
388
|
+
def user_set(ident: str, plan: str = typer.Option(None), cpu: float = typer.Option(None),
|
|
389
|
+
mem_mb: int = typer.Option(None), disk_gb: int = typer.Option(None),
|
|
390
|
+
sudo: bool = typer.Option(None), internet: bool = typer.Option(None),
|
|
391
|
+
shared: bool = typer.Option(None)):
|
|
392
|
+
"""Change a user's plan / limits / permissions."""
|
|
393
|
+
require_root()
|
|
394
|
+
from ..users import get_user, update_user
|
|
395
|
+
data = {k: v for k, v in dict(plan=plan, cpu=cpu, mem_mb=mem_mb, disk_gb=disk_gb, sudo=sudo,
|
|
396
|
+
internet=internet, shared_folder=shared).items() if v is not None}
|
|
397
|
+
with _db() as db:
|
|
398
|
+
res = update_user(db, get_user(db, ident), data, "cli")
|
|
399
|
+
console.print(f"[green]✓ changed: {res['changed']} actions: {res['actions']}[/]")
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
@user_app.command("approve")
|
|
403
|
+
@_guard
|
|
404
|
+
def user_approve(ident: str, plan: str = typer.Option(None)):
|
|
405
|
+
"""Approve a pending user."""
|
|
406
|
+
require_root()
|
|
407
|
+
from ..users import approve, get_user
|
|
408
|
+
with _db() as db:
|
|
409
|
+
u = approve(db, get_user(db, ident), "cli", plan)
|
|
410
|
+
console.print(f"[green]✓ approved {u.email}[/]")
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
@user_app.command("disable")
|
|
414
|
+
@_guard
|
|
415
|
+
def user_disable(ident: str):
|
|
416
|
+
"""Disable a user (ends sessions, stops workspace)."""
|
|
417
|
+
require_root()
|
|
418
|
+
from ..users import disable, get_user
|
|
419
|
+
with _db() as db:
|
|
420
|
+
disable(db, get_user(db, ident), "cli")
|
|
421
|
+
console.print("[green]✓ disabled[/]")
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
@user_app.command("enable")
|
|
425
|
+
@_guard
|
|
426
|
+
def user_enable(ident: str):
|
|
427
|
+
"""Enable a user."""
|
|
428
|
+
require_root()
|
|
429
|
+
from ..users import enable, get_user
|
|
430
|
+
with _db() as db:
|
|
431
|
+
enable(db, get_user(db, ident), "cli")
|
|
432
|
+
console.print("[green]✓ enabled[/]")
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
@user_app.command("delete")
|
|
436
|
+
@_guard
|
|
437
|
+
def user_delete(ident: str, remove_home: bool = typer.Option(False, help="Archive + delete home"),
|
|
438
|
+
yes: bool = typer.Option(False, "-y")):
|
|
439
|
+
"""Delete a user (home kept unless --remove-home)."""
|
|
440
|
+
require_root()
|
|
441
|
+
if not yes and not typer.confirm(f"Delete {ident}?"):
|
|
442
|
+
raise typer.Exit(0)
|
|
443
|
+
from ..users import delete, get_user
|
|
444
|
+
with _db() as db:
|
|
445
|
+
res = delete(db, get_user(db, ident), "cli", keep_home=not remove_home)
|
|
446
|
+
console.print(f"[green]✓ deleted[/] {res}")
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
@user_app.command("rebuild")
|
|
450
|
+
@_guard
|
|
451
|
+
def user_rebuild(ident: str = typer.Argument(None), all_: bool = typer.Option(False, "--all")):
|
|
452
|
+
"""Recreate workspace container(s) (home kept)."""
|
|
453
|
+
require_root()
|
|
454
|
+
from sqlalchemy import select
|
|
455
|
+
from ..db import User
|
|
456
|
+
from ..users import get_user
|
|
457
|
+
from ..workspace import rebuild
|
|
458
|
+
with _db() as db:
|
|
459
|
+
targets = list(db.scalars(select(User).where(User.provisioned.is_(True)))) if all_ \
|
|
460
|
+
else [get_user(db, ident)] if ident else []
|
|
461
|
+
if not targets:
|
|
462
|
+
die("give a username or --all")
|
|
463
|
+
for u in targets:
|
|
464
|
+
rebuild(db, u, "cli")
|
|
465
|
+
console.print(f"[green]✓ {u.username}[/]")
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
@user_app.command("logout")
|
|
469
|
+
@_guard
|
|
470
|
+
def user_logout(ident: str):
|
|
471
|
+
"""Force logout (ends sessions and disconnects open VS Code)."""
|
|
472
|
+
require_root()
|
|
473
|
+
from ..users import force_logout, get_user
|
|
474
|
+
with _db() as db:
|
|
475
|
+
n = force_logout(db, get_user(db, ident), "cli")
|
|
476
|
+
console.print(f"[green]✓ {n} session(s) ended[/]")
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
# ------------------------------------------------------------------ admins
|
|
480
|
+
@admin_app.command("add")
|
|
481
|
+
@_guard
|
|
482
|
+
def admin_add(email: str):
|
|
483
|
+
"""Make an email an admin (creates the account if needed)."""
|
|
484
|
+
require_root()
|
|
485
|
+
from sqlalchemy import select
|
|
486
|
+
from ..db import User, audit
|
|
487
|
+
from ..users import create_user
|
|
488
|
+
with _db() as db:
|
|
489
|
+
u = db.scalar(select(User).where(User.email == email.lower()))
|
|
490
|
+
if u is None:
|
|
491
|
+
create_user(db, email=email, actor="cli", is_admin=True, has_workspace=False,
|
|
492
|
+
provision=False)
|
|
493
|
+
else:
|
|
494
|
+
u.is_admin = True
|
|
495
|
+
u.status = "active"
|
|
496
|
+
audit(db, "admin.add", actor="cli", target=u.email)
|
|
497
|
+
console.print(f"[green]✓ {email} is admin[/]")
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
@admin_app.command("remove")
|
|
501
|
+
@_guard
|
|
502
|
+
def admin_remove(email: str):
|
|
503
|
+
"""Remove admin role."""
|
|
504
|
+
require_root()
|
|
505
|
+
from ..users import get_user, update_user
|
|
506
|
+
with _db() as db:
|
|
507
|
+
update_user(db, get_user(db, email), {"is_admin": False}, "cli")
|
|
508
|
+
console.print(f"[green]✓ {email} is no longer admin[/]")
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
@admin_app.command("list")
|
|
512
|
+
def admin_list():
|
|
513
|
+
"""List admins."""
|
|
514
|
+
from sqlalchemy import select
|
|
515
|
+
from ..db import User
|
|
516
|
+
with _db() as db:
|
|
517
|
+
for u in db.scalars(select(User).where(User.is_admin.is_(True))):
|
|
518
|
+
console.print(f"{u.email} [dim]{u.status}[/]")
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def main(): # pragma: no cover
|
|
522
|
+
app()
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
if __name__ == "__main__": # pragma: no cover
|
|
526
|
+
sys.exit(app())
|