authelia: allow password reset writes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rope 2026-10-22 13:19:58 +01:00
parent c57ca59f25
commit 8fe9e98300
3 changed files with 46 additions and 13 deletions

View file

@ -113,18 +113,26 @@ def write_atomic(path: Path, text: str, mode: int, gid: int = -1) -> None:
raise
def user_indent(text: str) -> str:
"""The indent of the existing user keys. Authelia rewrites the whole file
with four spaces when someone resets their password; by hand it's two."""
match = re.search(r"^users:[ \t]*\n(?:[ \t]*(?:#.*)?\n)*( +)\S", text, re.M)
return match.group(1) if match else " "
def add_user(path: Path, username: str, display: str, password_hash: str) -> None:
"""Append one user; refuse unless every existing user parses back unchanged."""
text = path.read_text()
before = yaml.safe_load(text)["users"]
if username.lower() in (name.lower() for name in before):
raise Refused("That username is taken.")
i = user_indent(text)
block = (
f" {username}:\n"
f" displayname: {json.dumps(display)}\n"
f" password: {json.dumps(password_hash)}\n"
f" groups:\n"
f" - {GROUP}\n"
f"{i}{username}:\n"
f"{i * 2}displayname: {json.dumps(display)}\n"
f"{i * 2}password: {json.dumps(password_hash)}\n"
f"{i * 2}groups:\n"
f"{i * 3}- {GROUP}\n"
)
new_text = text.rstrip("\n") + "\n\n" + block
after = yaml.safe_load(new_text)["users"]