user.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. # Personal access code for a virtual printer (#1430): entered in the user's
  40. # slicer instead of the virtual printer's own code, it tells the virtual
  41. # printer whose upload it is. Kept readable (as printers' and virtual
  42. # printers' codes are), since the user has to read it back to type it in.
  43. # NULL until the user first opens it. A credential: never logged, never in
  44. # an API response other than the user's own.
  45. slicer_access_code: Mapped[str | None] = mapped_column(String(8), nullable=True, unique=True, index=True)
  46. # Per-user Bambu Cloud credentials (when auth is enabled, each user has their own)
  47. cloud_token: Mapped[str | None] = mapped_column(String(500), nullable=True, default=None)
  48. cloud_email: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
  49. # "global" or "china"; NULL treated as "global" for legacy rows.
  50. cloud_region: Mapped[str | None] = mapped_column(String(10), nullable=True, default=None)
  51. # Set when Bambu answers 401 to a call made with ``cloud_token`` — the token
  52. # has expired or been revoked. NULL means "not known to be dead". The token
  53. # itself is kept: clearing it would lose the email/region we show on the
  54. # re-login form, and a token can only be replaced by signing in again anyway.
  55. # Bambu's token is opaque and carries no expiry we can read, and Bambuddy
  56. # does not persist the refresh token, so this flag is the *only* record that
  57. # a stored credential has stopped working (#2562 follow-up).
  58. cloud_token_invalid_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
  59. # Per-user Orca Cloud credentials. Unlike Bambu Cloud, Orca uses Supabase PKCE
  60. # with short-lived access tokens (1h) and rotating single-use refresh tokens,
  61. # so we store the refresh token + expiry alongside the access token.
  62. orca_cloud_token: Mapped[str | None] = mapped_column(String(2000), nullable=True, default=None)
  63. orca_cloud_refresh_token: Mapped[str | None] = mapped_column(String(128), nullable=True, default=None)
  64. orca_cloud_expires_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
  65. orca_cloud_email: Mapped[str | None] = mapped_column(String(255), nullable=True, default=None)
  66. orca_cloud_user_id: Mapped[str | None] = mapped_column(String(64), nullable=True, default=None)
  67. # Transient PKCE state held between /orca-cloud/auth/start and /orca-cloud/auth/finish.
  68. # Cleared on successful finish; expires after 10 minutes if the user abandons the flow.
  69. orca_cloud_pending_verifier: Mapped[str | None] = mapped_column(String(64), nullable=True, default=None)
  70. orca_cloud_pending_state: Mapped[str | None] = mapped_column(String(32), nullable=True, default=None)
  71. orca_cloud_pending_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, default=None)
  72. # Relationship to groups through association table
  73. groups: Mapped[list[Group]] = relationship(
  74. "Group",
  75. secondary="user_groups",
  76. back_populates="users",
  77. lazy="selectin",
  78. )
  79. # Relationship to email notification preferences
  80. email_preferences: Mapped[UserEmailPreference | None] = relationship(
  81. "UserEmailPreference",
  82. back_populates="user",
  83. uselist=False,
  84. cascade="all, delete-orphan",
  85. lazy="select",
  86. )
  87. @property
  88. def is_admin(self) -> bool:
  89. """Check if user is an admin.
  90. Returns True if:
  91. - User has legacy role='admin', OR
  92. - User belongs to the Administrators group
  93. """
  94. if self.role == "admin":
  95. return True
  96. return any(g.name == ADMIN_GROUP_NAME for g in self.groups)
  97. def sync_role_to_groups(self) -> None:
  98. """Make the legacy ``role`` say what the groups say.
  99. ``is_admin`` honours either, so a user moved out of Administrators
  100. whose role still read "admin" stayed an admin, with nothing in the UI
  101. to change it (#3533). Call after every change to ``groups``; needs
  102. them loaded.
  103. """
  104. self.role = "admin" if any(g.name == ADMIN_GROUP_NAME for g in self.groups) else "user"
  105. def get_permissions(self) -> set[str]:
  106. """Get all permissions from all groups the user belongs to.
  107. Returns a set of permission strings. Permissions are additive across groups.
  108. """
  109. permissions: set[str] = set()
  110. for group in self.groups:
  111. if group.permissions:
  112. permissions.update(group.permissions)
  113. return permissions
  114. def has_permission(self, permission: str) -> bool:
  115. """Check if user has a specific permission.
  116. Admins have all permissions. For other users, checks if the permission
  117. exists in any of their groups.
  118. """
  119. if self.is_admin:
  120. return True
  121. return permission in self.get_permissions()
  122. def has_all_permissions(self, *permissions: str) -> bool:
  123. """Check if user has ALL specified permissions.
  124. Admins have all permissions. For other users, checks if all permissions
  125. exist in their combined group permissions.
  126. """
  127. if self.is_admin:
  128. return True
  129. user_permissions = self.get_permissions()
  130. return all(p in user_permissions for p in permissions)
  131. def has_any_permission(self, *permissions: str) -> bool:
  132. """Check if user has ANY of the specified permissions.
  133. Admins have all permissions. For other users, checks if at least one
  134. permission exists in their combined group permissions.
  135. """
  136. if self.is_admin:
  137. return True
  138. user_permissions = self.get_permissions()
  139. return any(p in user_permissions for p in permissions)
  140. def __repr__(self) -> str:
  141. return f"<User {self.username}>"