diff options
Diffstat (limited to '')
| -rw-r--r-- | webmentions_ssg/models/user.py | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/webmentions_ssg/models/user.py b/webmentions_ssg/models/user.py new file mode 100644 index 0000000..b09c3d1 --- /dev/null +++ b/webmentions_ssg/models/user.py @@ -0,0 +1,66 @@ +# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me> +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Application user and session identity model.""" + +from hashlib import sha256 +from typing import Never + +from flask_login import UserMixin +from sqlalchemy import Text +from sqlalchemy.orm import Mapped, mapped_column +from werkzeug.security import check_password_hash, generate_password_hash + +from ..extensions import Base + + +class User(UserMixin, Base): + """Represent an authenticated application user.""" + + __tablename__ = "users" + + id: Mapped[int] = mapped_column(primary_key=True) + username: Mapped[str] = mapped_column(Text(), index=True, unique=True) + password_hash: Mapped[str] = mapped_column(Text(), nullable=False) + + def __repr__(self) -> str: + """Represent the user by username.""" + return f"<User {self.username}>" + + @property + def password(self) -> Never: + """Prevent access to the user's plain-text password. + + :raises AttributeError: Always, because the password is write-only. + """ + raise AttributeError("Password is write-only") + + @password.setter + def password(self, password: str) -> None: + """Hash and store a new password. + + :param password: Plain-text password to hash. + """ + self.password_hash = generate_password_hash(password) + + def get_id(self) -> str: + """Bind the login session to the current stored password hash. + + Only a one-way fingerprint is placed in Flask's signed cookie, never + the password hash itself. Rehashing the password invalidates all + previously issued session identifiers without a schema change. + + :returns: Session identifier combining the user ID and password-hash + fingerprint. + """ + fingerprint = sha256(self.password_hash.encode("utf-8")).hexdigest() + return f"{self.id}:{fingerprint}" + + def check_password(self, password: str) -> bool: + """Check a plain-text password against the stored password hash. + + :param password: Plain-text password to check. + :returns: Whether the password matches the stored hash. + """ + return check_password_hash(self.password_hash, password) |
