SHA256
initial commit
This commit is contained in:
@@ -0,0 +1,222 @@
|
||||
"""users 命令: 用户管理(批量创建/列出/删除)"""
|
||||
|
||||
import csv
|
||||
import secrets
|
||||
import string
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
|
||||
from tjhlp.client import GiteaClient, GiteaClientError
|
||||
from tjhlp.config import get_gitea_config
|
||||
from tjhlp.models import CredentialRecord, MemberRecord, MemberRole
|
||||
|
||||
app = typer.Typer(no_args_is_help=True)
|
||||
console = Console()
|
||||
|
||||
|
||||
def _generate_password(length: int = 12) -> str:
|
||||
"""生成随机密码: 至少包含大小写字母、数字和特殊字符"""
|
||||
if length < 8:
|
||||
length = 8
|
||||
alphabet = string.ascii_letters + string.digits + "!@#$%&*"
|
||||
while True:
|
||||
password = "".join(secrets.choice(alphabet) for _ in range(length))
|
||||
if (
|
||||
any(c.islower() for c in password)
|
||||
and any(c.isupper() for c in password)
|
||||
and any(c.isdigit() for c in password)
|
||||
and any(c in "!@#$%&*" for c in password)
|
||||
):
|
||||
return password
|
||||
|
||||
|
||||
def _read_members_csv(filepath: Path) -> list[MemberRecord]:
|
||||
"""读取 members CSV 文件"""
|
||||
records: list[MemberRecord] = []
|
||||
with open(filepath, encoding="utf-8-sig") as f:
|
||||
reader = csv.DictReader(f)
|
||||
for row in reader:
|
||||
records.append(MemberRecord.model_validate(row))
|
||||
return records
|
||||
|
||||
|
||||
@app.command("create")
|
||||
def create_users(
|
||||
file: Path = typer.Option(..., "--file", "-f", help="成员名单 CSV 文件路径"),
|
||||
org: str = typer.Option("", "--org", help="自动添加到指定组织的对应团队"),
|
||||
output: Path = typer.Option(None, "--output", "-o", help="凭据输出文件路径(默认自动生成)"),
|
||||
dry_run: bool = typer.Option(False, "--dry-run", help="仅预览, 不实际创建"),
|
||||
) -> None:
|
||||
"""从 CSV 批量创建用户账号, 生成随机密码并输出到凭据文件"""
|
||||
if not file.exists():
|
||||
console.print(f"[red]文件不存在: {file}[/red]")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
cfg = get_gitea_config()
|
||||
members = _read_members_csv(file)
|
||||
console.print(
|
||||
f"读取到 {len(members)} 条记录 "
|
||||
f"(学生: {sum(1 for m in members if m.role == MemberRole.STUDENT)}, "
|
||||
f"助教: {sum(1 for m in members if m.role == MemberRole.TA)})"
|
||||
)
|
||||
|
||||
if dry_run:
|
||||
table = Table(title="预览(dry-run)")
|
||||
table.add_column("ID")
|
||||
table.add_column("姓名")
|
||||
table.add_column("角色")
|
||||
table.add_column("邮箱")
|
||||
for m in members:
|
||||
table.add_row(m.id, m.name, m.role, m.email)
|
||||
console.print(table)
|
||||
return
|
||||
|
||||
credentials: list[CredentialRecord] = []
|
||||
stats = {"created": 0, "skipped": 0, "failed": 0}
|
||||
|
||||
with GiteaClient(cfg) as client:
|
||||
# 获取团队 ID(如果指定了组织)
|
||||
ta_team = None
|
||||
students_team = None
|
||||
if org:
|
||||
ta_team = client.get_team_by_name(org, "ta")
|
||||
students_team = client.get_team_by_name(org, "students")
|
||||
|
||||
for member in members:
|
||||
# 检查用户是否已存在
|
||||
existing = client.get_user(member.username)
|
||||
if existing:
|
||||
console.print(f" [yellow]跳过[/yellow] {member.username}({member.name})- 已存在")
|
||||
stats["skipped"] += 1
|
||||
continue
|
||||
|
||||
password = _generate_password(cfg.password_length)
|
||||
|
||||
try:
|
||||
client.create_user(
|
||||
username=member.username,
|
||||
password=password,
|
||||
email=member.email,
|
||||
full_name=member.name,
|
||||
must_change_password=True,
|
||||
)
|
||||
console.print(f" [green]创建[/green] {member.username}({member.name})")
|
||||
stats["created"] += 1
|
||||
|
||||
credentials.append(
|
||||
CredentialRecord(
|
||||
id=member.id,
|
||||
name=member.name,
|
||||
role=member.role.value,
|
||||
username=member.username,
|
||||
password=password,
|
||||
email=member.email,
|
||||
)
|
||||
)
|
||||
|
||||
# 添加到团队
|
||||
if org:
|
||||
team = ta_team if member.role == MemberRole.TA else students_team
|
||||
if team:
|
||||
try:
|
||||
client.add_team_member(team.id, member.username)
|
||||
except GiteaClientError as e:
|
||||
console.print(f" [yellow]添加到团队失败: {e.message}[/yellow]")
|
||||
|
||||
except GiteaClientError as e:
|
||||
console.print(f" [red]失败[/red] {member.username}({member.name}): {e.message}")
|
||||
stats["failed"] += 1
|
||||
|
||||
# 写出凭据文件
|
||||
if credentials:
|
||||
if output is None:
|
||||
ts = datetime.now(tz=UTC).strftime("%Y%m%d_%H%M%S")
|
||||
output = Path(f"credentials_{ts}.csv")
|
||||
with open(output, "w", newline="", encoding="utf-8") as f:
|
||||
writer = csv.DictWriter(
|
||||
f,
|
||||
fieldnames=["id", "name", "role", "username", "password", "email"],
|
||||
)
|
||||
writer.writeheader()
|
||||
for cred in credentials:
|
||||
writer.writerow(cred.model_dump())
|
||||
console.print(f"\n凭据已保存到 [bold]{output}[/bold]")
|
||||
|
||||
console.print(
|
||||
f"\n完成: 创建 {stats['created']}, 跳过 {stats['skipped']}, 失败 {stats['failed']}"
|
||||
)
|
||||
|
||||
|
||||
@app.command("list")
|
||||
def list_users() -> None:
|
||||
"""列出 Gitea 上的所有用户"""
|
||||
cfg = get_gitea_config()
|
||||
|
||||
with GiteaClient(cfg) as client:
|
||||
users = client.list_users()
|
||||
table = Table(title=f"用户列表(共 {len(users)} 个)")
|
||||
table.add_column("ID", style="dim")
|
||||
table.add_column("用户名")
|
||||
table.add_column("姓名")
|
||||
table.add_column("邮箱")
|
||||
table.add_column("管理员")
|
||||
table.add_column("活跃")
|
||||
for u in users:
|
||||
table.add_row(
|
||||
str(u.id),
|
||||
u.login,
|
||||
u.full_name,
|
||||
u.email,
|
||||
"[green]是[/green]" if u.is_admin else "",
|
||||
"[green]是[/green]" if u.active else "[red]否[/red]",
|
||||
)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command("delete")
|
||||
def delete_users(
|
||||
file: Path = typer.Option(..., "--file", "-f", help="成员名单 CSV 文件路径"),
|
||||
confirm: bool = typer.Option(False, "--yes", "-y", help="跳过确认提示"),
|
||||
) -> None:
|
||||
"""根据 CSV 名单批量删除用户(危险操作)"""
|
||||
if not file.exists():
|
||||
console.print(f"[red]文件不存在: {file}[/red]")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
members = _read_members_csv(file)
|
||||
console.print(f"[red bold]即将删除 {len(members)} 个用户![/red bold]")
|
||||
|
||||
if not confirm:
|
||||
typer.confirm("确认删除?此操作不可恢复", abort=True)
|
||||
|
||||
cfg = get_gitea_config()
|
||||
stats = {"deleted": 0, "skipped": 0, "failed": 0}
|
||||
|
||||
with GiteaClient(cfg) as client:
|
||||
for member in members:
|
||||
existing = client.get_user(member.username)
|
||||
if not existing:
|
||||
console.print(f" [yellow]跳过[/yellow] {member.username} - 不存在")
|
||||
stats["skipped"] += 1
|
||||
continue
|
||||
|
||||
if existing.is_admin:
|
||||
console.print(f" [yellow]跳过[/yellow] {member.username} - 管理员账号")
|
||||
stats["skipped"] += 1
|
||||
continue
|
||||
|
||||
try:
|
||||
client.delete_user(member.username)
|
||||
console.print(f" [red]已删除[/red] {member.username}({member.name})")
|
||||
stats["deleted"] += 1
|
||||
except GiteaClientError as e:
|
||||
console.print(f" [red]失败[/red] {member.username}: {e.message}")
|
||||
stats["failed"] += 1
|
||||
|
||||
console.print(
|
||||
f"\n完成: 删除 {stats['deleted']}, 跳过 {stats['skipped']}, 失败 {stats['failed']}"
|
||||
)
|
||||
Reference in New Issue
Block a user