Spaces:
Running
Running
File size: 2,819 Bytes
cd61bf7 2c5de26 1d33ce6 cd61bf7 dd35b54 cd61bf7 | 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 67 68 69 70 71 72 73 74 75 76 77 78 | from sqlmodel import SQLModel, Field
from typing import Optional
from datetime import datetime
from uuid import UUID, uuid4
import bcrypt
from passlib.context import CryptContext
from enum import Enum
# Keep passlib for backward compatibility with old hashes
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
class UserRole(str, Enum):
"""User role in the organization."""
OWNER = "OWNER" # Full access, can edit settings
MANAGER = "MANAGER" # Limited access, can only use chats
class User(SQLModel, table=True):
"""User account with authentication."""
__tablename__ = "users"
id: UUID = Field(default_factory=uuid4, primary_key=True)
email: str = Field(unique=True, index=True)
hashed_password: str
full_name: Optional[str] = None
avatar_url: Optional[str] = Field(default=None, nullable=True)
phone: Optional[str] = Field(default=None, nullable=True)
telegram_chat_id: Optional[str] = Field(default=None, nullable=True) # Personal notification ID
# Tenant relationship
tenant_id: UUID = Field(foreign_key="tenants.id")
# Role
role: str = Field(default="OWNER") # UserRole.OWNER or UserRole.MANAGER
# Status
is_active: bool = Field(default=True)
is_superuser: bool = Field(default=False)
# Verification
is_verified: bool = Field(default=False)
verification_code: Optional[str] = None
verification_code_expires_at: Optional[datetime] = None
created_at: datetime = Field(default_factory=datetime.utcnow)
updated_at: datetime = Field(default_factory=datetime.utcnow)
@staticmethod
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Verify a password against a hash."""
# Bcrypt has a 72 byte password limit, truncate if necessary
password_bytes = plain_password.encode('utf-8')[:72]
# Try bcrypt direct verification first (new format)
try:
if isinstance(hashed_password, str):
hashed_bytes = hashed_password.encode('utf-8')
else:
hashed_bytes = hashed_password
return bcrypt.checkpw(password_bytes, hashed_bytes)
except (ValueError, TypeError):
# Fall back to passlib for old hashes
try:
return pwd_context.verify(plain_password[:72], hashed_password)
except Exception:
return False
@staticmethod
def get_password_hash(password: str) -> str:
"""Generate password hash."""
# Bcrypt has a 72 byte password limit, truncate if necessary
password_bytes = password.encode('utf-8')[:72]
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password_bytes, salt)
return hashed.decode('utf-8')
|