user.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. from __future__ import annotations
  2. from datetime import datetime
  3. from typing import TYPE_CHECKING
  4. from sqlalchemy import DateTime, String, func
  5. from sqlalchemy.orm import Mapped, mapped_column, relationship
  6. from backend.app.core.database import Base
  7. from backend.app.utils.local_time import utcnow_naive
  8. if TYPE_CHECKING:
  9. from backend.app.models.group import Group
  10. from backend.app.models.user_email_pref import UserEmailPreference
  11. # The system group whose members are admins.
  12. ADMIN_GROUP_NAME = "Administrators"
  13. class User(Base):
  14. """User model for authentication and authorization.
  15. Users can belong to multiple groups, and their permissions are additive
  16. across all groups. The legacy 'role' field is kept for backward compatibility
  17. but is_admin property now also considers group membership.
  18. """
  19. __tablename__ = "users"
  20. # SQLite would give a freed id to the next row; see core/database AUTOINCREMENT_TABLES
  21. __table_args__ = {"sqlite_autoincrement": True}
  22. id: Mapped[int] = mapped_column(primary_key=True)
  23. username: Mapped[str] = mapped_column(String(100), unique=True, index=True)
  24. email: Mapped[str | None] = mapped_column(String(255), unique=True, index=True, nullable=True)
  25. password_hash: Mapped[str | None] = mapped_column(String(255), nullable=True)
  26. role: Mapped[str] = mapped_column(
  27. String(20), default="user"
  28. ) # "admin" or "user" (legacy, kept for backward compat)
  29. auth_source: Mapped[str] = mapped_column(String(20), default="local") # "local", "ldap", or "oidc"
  30. is_active: Mapped[bool] = mapped_column(default=True)
  31. created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
  32. updated_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), onupdate=func.now())
  33. # Set whenever the local password is changed/reset — used to invalidate JWTs
  34. # issued before the change (M-R7-B). NULL means no password change recorded yet.
  35. # Set at creation too, whichever way the user is created: sessions name the
  36. # user by username, and a deleted user's still-valid JWTs must not sign in
  37. # whoever is given the name next.
  38. password_changed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=utcnow_naive)
  39. # Per-user Bambu Cloud credentials (when auth is enabled, each user has their own)
  40. cloud_token: Mapped[str | None] = mapped_column(String(500), nullable=True, default=None)
  41. cloud_email: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
  42. # "global" or "china"; NULL treated as "global" for legacy rows.
  43. cloud_region: Mapped[str | None] = mapped_column(String(10), nullable=True, default=None)
  44. # Set when Bambu answers 401 to a call made with ``cloud_token`` — the token
  45. # has expired or been revoked. NULL means "not known to be dead". The token
  46. # itself is kept: clearing it would lose the email/region we show on the
  47. # re-login form, and a token can only be replaced by signing in again anyway.
  48. # Bambu's token is opaque and carries no expiry we can read, and Bambuddy
  49. # does not persist the refresh token, so this flag is the *only* record that
  50. # a stored credential has stopped working (#2562 follow-up).
  51. cloud_token_invalid_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
  52. # Per-user Orca Cloud credentials. Unlike Bambu Cloud, Orca uses Supabase PKCE
  53. # with short-lived access tokens (1h) and rotating single-use refresh tokens,
  54. # so we store the refresh token + expiry alongside the access token.
  55. orca_cloud_token: Mapped[str | None] = mapped_column(String(2000), nullable=True, default=None)
  56. orca_cloud_refresh_token: Mapped[str | None] = mapped_column(String(128), nullable=True, default=None)
  57. orca_cloud_expires_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
  58. orca_cloud_email: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
  59. orca_cloud_user_id: Mapped[str | None] = mapped_column(String(64), nullable=True, default=None)
  60. # Transient PKCE state held between /orca-cloud/auth/start and /orca-cloud/auth/finish.
  61. # Cleared on successful finish; expires after 10 minutes if the user abandons the flow.
  62. orca_cloud_pending_verifier: Mapped[str | None] = mapped_column(String(64), nullable=True, default=None)
  63. orca_cloud_pending_state: Mapped[str | None] = mapped_column(String(32), nullable=True, default=None)
  64. orca_cloud_pending_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
  65. # Relationship to groups through association table
  66. groups: Mapped[list[Group]] = relationship(
  67. "Group",
  68. secondary="user_groups",
  69. back_populates="users",
  70. lazy="selectin",
  71. )
  72. # Relationship to email notification preferences
  73. email_preferences: Mapped[UserEmailPreference | None] = relationship(
  74. "UserEmailPreference",
  75. back_populates="user",
  76. uselist=False,
  77. cascade="all, delete-orphan",
  78. lazy="select",
  79. )
  80. @property
  81. def is_admin(self) -> bool:
  82. """Check if user is an admin.
  83. Returns True if:
  84. - User has legacy role='admin', OR
  85. - User belongs to the Administrators group
  86. """
  87. if self.role == "admin":
  88. return True
  89. return any(g.name == ADMIN_GROUP_NAME for g in self.groups)
  90. def sync_role_to_groups(self) -> None:
  91. """Make the legacy ``role`` say what the groups say.
  92. ``is_admin`` honours either, so a user moved out of Administrators
  93. whose role still read "admin" stayed an admin, with nothing in the UI
  94. to change it (#3533). Call after every change to ``groups``; needs
  95. them loaded.
  96. """
  97. self.role = "admin" if any(g.name == ADMIN_GROUP_NAME for g in self.groups) else "user"
  98. def get_permissions(self) -> set[str]:
  99. """Get all permissions from all groups the user belongs to.
  100. Returns a set of permission strings. Permissions are additive across groups.
  101. """
  102. permissions: set[str] = set()
  103. for group in self.groups:
  104. if group.permissions:
  105. permissions.update(group.permissions)
  106. return permissions
  107. def has_permission(self, permission: str) -> bool:
  108. """Check if user has a specific permission.
  109. Admins have all permissions. For other users, checks if the permission
  110. exists in any of their groups.
  111. """
  112. if self.is_admin:
  113. return True
  114. return permission in self.get_permissions()
  115. def has_all_permissions(self, *permissions: str) -> bool:
  116. """Check if user has ALL specified permissions.
  117. Admins have all permissions. For other users, checks if all permissions
  118. exist in their combined group permissions.
  119. """
  120. if self.is_admin:
  121. return True
  122. user_permissions = self.get_permissions()
  123. return all(p in user_permissions for p in permissions)
  124. def has_any_permission(self, *permissions: str) -> bool:
  125. """Check if user has ANY of the specified permissions.
  126. Admins have all permissions. For other users, checks if at least one
  127. permission exists in their combined group permissions.
  128. """
  129. if self.is_admin:
  130. return True
  131. user_permissions = self.get_permissions()
  132. return any(p in user_permissions for p in permissions)
  133. def __repr__(self) -> str:
  134. return f"<User {self.username}>"