aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/auth.py
diff options
context:
space:
mode:
Diffstat (limited to 'webmentions_ssg/auth.py')
-rw-r--r--webmentions_ssg/auth.py53
1 files changed, 52 insertions, 1 deletions
diff --git a/webmentions_ssg/auth.py b/webmentions_ssg/auth.py
index 147220e..633aa82 100644
--- a/webmentions_ssg/auth.py
+++ b/webmentions_ssg/auth.py
@@ -4,17 +4,43 @@
"""Configure user authentication and session loading."""
+import hashlib
+import secrets
from hmac import compare_digest
+from urllib.parse import urlsplit
+from flask import request
+from flask_limiter.util import get_remote_address
from flask_login import LoginManager
-from . import DATABASE as db
+from .extensions import DATABASE as db
from .models import User
AUTH = LoginManager()
AUTH.login_view = "root.login" # pyright: ignore[reportAttributeAccessIssue]
+MIN_PASSWORD_LENGTH = 8
+
+DUMMY_USER = User(username=secrets.token_urlsafe())
+DUMMY_USER.password = secrets.token_urlsafe()
+
+
+def validate_password(password: str) -> None:
+ """Validate newly chosen passwords without arbitrary composition rules.
+
+ Allow Unicode, whitespace-only passwords, and arbitrarily long passphrases,
+ but reject empty passwords and control characters.
+ """
+ if not password:
+ raise ValueError("Password must not be empty.")
+ if len(password) < MIN_PASSWORD_LENGTH:
+ raise ValueError(
+ f"Password must be at least {MIN_PASSWORD_LENGTH} characters long."
+ )
+ if any(ord(char) < 32 or ord(char) == 127 for char in password):
+ raise ValueError("Password must not contain control characters.")
+
@AUTH.user_loader
def load_user(session_id: str) -> User | None:
@@ -44,3 +70,28 @@ def load_user(session_id: str) -> User | None:
if not compare_digest(session_id, user.get_id()):
return None
return user
+
+
+def login_username_limit_key() -> str:
+ """Group usernames across IPs without exposing plaintext to rate-limit storage."""
+ username = request.form.get("username", "").strip().casefold()
+ if not username:
+ return f"missing-username:{get_remote_address()}"
+ digest = hashlib.sha256(username.encode("utf-8")).hexdigest()
+ return f"username:{digest}"
+
+
+def is_safe_next_url(next_url: str) -> bool:
+ """Allow redirects only to paths on this site."""
+ if "\\" in next_url or not next_url.startswith("/") or next_url.startswith("//"):
+ return False
+ try:
+ target = urlsplit(next_url)
+ except ValueError:
+ return False
+ return (
+ not target.scheme
+ and not target.netloc
+ and target.path.startswith("/")
+ and not target.path.startswith("//")
+ )