diff --git a/auth.py b/auth.py index ff3521d..c0ba416 100644 --- a/auth.py +++ b/auth.py @@ -85,6 +85,43 @@ def create_admin(username, password, conn=None): conn.close() +def reset_password(password, username=None, conn=None): + """Set the admin password without knowing the current one. + + Creates the admin account when there is none. Used by the + `set-admin-password` action, which generates the password in the container. + Returns the stored username. + """ + if len(password or "") < MIN_PASSWORD_LENGTH: + raise ValueError("password must be at least %d characters" % MIN_PASSWORD_LENGTH) + own = conn is None + if own: + conn = database.connect() + try: + row = conn.execute("SELECT username FROM admin WHERE id = 1").fetchone() + name = (username or "").strip() or (row["username"] if row else "admin") + salt = secrets.token_hex(SALT_BYTES) + digest = _hash_password(password, salt, ITERATIONS) + now = _stamp(_now()) + if row is None: + conn.execute( + "INSERT INTO admin (id, username, password_hash, salt, iterations," + " created_at, updated_at) VALUES (1, ?, ?, ?, ?, ?, ?)", + (name, digest, salt, ITERATIONS, now, now), + ) + else: + conn.execute( + "UPDATE admin SET username = ?, password_hash = ?, salt = ?," + " iterations = ?, updated_at = ? WHERE id = 1", + (name, digest, salt, ITERATIONS, now), + ) + conn.commit() + finally: + if own: + conn.close() + return name + + def verify_login(username, password, conn=None): """Return True when the username and password match the admin account.""" own = conn is None