aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/models/user.py
blob: b09c3d14a3152d7b3decf1ce8f1eefbe1a5c8944 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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)