user.py 6.5 KB

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