account_service.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. import base64
  2. import json
  3. import logging
  4. import secrets
  5. import uuid
  6. from datetime import datetime, timedelta, timezone
  7. from hashlib import sha256
  8. from typing import Any, Optional
  9. from sqlalchemy import func
  10. from werkzeug.exceptions import Unauthorized
  11. from configs import dify_config
  12. from constants.languages import language_timezone_mapping, languages
  13. from events.tenant_event import tenant_was_created
  14. from extensions.ext_database import db
  15. from extensions.ext_redis import redis_client
  16. from libs.helper import RateLimiter, TokenManager
  17. from libs.passport import PassportService
  18. from libs.password import compare_password, hash_password, valid_password
  19. from libs.rsa import generate_key_pair
  20. from models.account import (
  21. Account,
  22. AccountIntegrate,
  23. AccountStatus,
  24. Tenant,
  25. TenantAccountJoin,
  26. TenantAccountJoinRole,
  27. TenantAccountRole,
  28. TenantStatus,
  29. )
  30. from models.model import DifySetup
  31. from services.errors.account import (
  32. AccountAlreadyInTenantError,
  33. AccountLoginError,
  34. AccountNotLinkTenantError,
  35. AccountRegisterError,
  36. CannotOperateSelfError,
  37. CurrentPasswordIncorrectError,
  38. InvalidActionError,
  39. LinkAccountIntegrateError,
  40. MemberNotInTenantError,
  41. NoPermissionError,
  42. RateLimitExceededError,
  43. RoleAlreadyAssignedError,
  44. TenantNotFoundError,
  45. )
  46. from tasks.mail_invite_member_task import send_invite_member_mail_task
  47. from tasks.mail_reset_password_task import send_reset_password_mail_task
  48. class AccountService:
  49. reset_password_rate_limiter = RateLimiter(prefix="reset_password_rate_limit", max_attempts=5, time_window=60 * 60)
  50. @staticmethod
  51. def load_user(user_id: str) -> None | Account:
  52. account = Account.query.filter_by(id=user_id).first()
  53. if not account:
  54. return None
  55. if account.status in {AccountStatus.BANNED.value, AccountStatus.CLOSED.value}:
  56. raise Unauthorized("Account is banned or closed.")
  57. current_tenant: TenantAccountJoin = TenantAccountJoin.query.filter_by(
  58. account_id=account.id, current=True
  59. ).first()
  60. if current_tenant:
  61. account.current_tenant_id = current_tenant.tenant_id
  62. else:
  63. available_ta = (
  64. TenantAccountJoin.query.filter_by(account_id=account.id).order_by(TenantAccountJoin.id.asc()).first()
  65. )
  66. if not available_ta:
  67. return None
  68. account.current_tenant_id = available_ta.tenant_id
  69. available_ta.current = True
  70. db.session.commit()
  71. if datetime.now(timezone.utc).replace(tzinfo=None) - account.last_active_at > timedelta(minutes=10):
  72. account.last_active_at = datetime.now(timezone.utc).replace(tzinfo=None)
  73. db.session.commit()
  74. return account
  75. @staticmethod
  76. def get_account_jwt_token(account, *, exp: timedelta = timedelta(days=30)):
  77. payload = {
  78. "user_id": account.id,
  79. "exp": datetime.now(timezone.utc).replace(tzinfo=None) + exp,
  80. "iss": dify_config.EDITION,
  81. "sub": "Console API Passport",
  82. }
  83. token = PassportService().issue(payload)
  84. return token
  85. @staticmethod
  86. def authenticate(email: str, password: str) -> Account:
  87. """authenticate account with email and password"""
  88. account = Account.query.filter_by(email=email).first()
  89. if not account:
  90. raise AccountLoginError("Invalid email or password.")
  91. if account.status in {AccountStatus.BANNED.value, AccountStatus.CLOSED.value}:
  92. raise AccountLoginError("Account is banned or closed.")
  93. if account.status == AccountStatus.PENDING.value:
  94. account.status = AccountStatus.ACTIVE.value
  95. account.initialized_at = datetime.now(timezone.utc).replace(tzinfo=None)
  96. db.session.commit()
  97. if account.password is None or not compare_password(password, account.password, account.password_salt):
  98. raise AccountLoginError("Invalid email or password.")
  99. return account
  100. @staticmethod
  101. def update_account_password(account, password, new_password):
  102. """update account password"""
  103. if account.password and not compare_password(password, account.password, account.password_salt):
  104. raise CurrentPasswordIncorrectError("Current password is incorrect.")
  105. # may be raised
  106. valid_password(new_password)
  107. # generate password salt
  108. salt = secrets.token_bytes(16)
  109. base64_salt = base64.b64encode(salt).decode()
  110. # encrypt password with salt
  111. password_hashed = hash_password(new_password, salt)
  112. base64_password_hashed = base64.b64encode(password_hashed).decode()
  113. account.password = base64_password_hashed
  114. account.password_salt = base64_salt
  115. db.session.commit()
  116. return account
  117. @staticmethod
  118. def create_account(
  119. email: str, name: str, interface_language: str, password: Optional[str] = None, interface_theme: str = "light"
  120. ) -> Account:
  121. """create account"""
  122. account = Account()
  123. account.email = email
  124. account.name = name
  125. if password:
  126. # generate password salt
  127. salt = secrets.token_bytes(16)
  128. base64_salt = base64.b64encode(salt).decode()
  129. # encrypt password with salt
  130. password_hashed = hash_password(password, salt)
  131. base64_password_hashed = base64.b64encode(password_hashed).decode()
  132. account.password = base64_password_hashed
  133. account.password_salt = base64_salt
  134. account.interface_language = interface_language
  135. account.interface_theme = interface_theme
  136. # Set timezone based on language
  137. account.timezone = language_timezone_mapping.get(interface_language, "UTC")
  138. db.session.add(account)
  139. db.session.commit()
  140. return account
  141. @staticmethod
  142. def link_account_integrate(provider: str, open_id: str, account: Account) -> None:
  143. """Link account integrate"""
  144. try:
  145. # Query whether there is an existing binding record for the same provider
  146. account_integrate: Optional[AccountIntegrate] = AccountIntegrate.query.filter_by(
  147. account_id=account.id, provider=provider
  148. ).first()
  149. if account_integrate:
  150. # If it exists, update the record
  151. account_integrate.open_id = open_id
  152. account_integrate.encrypted_token = "" # todo
  153. account_integrate.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
  154. else:
  155. # If it does not exist, create a new record
  156. account_integrate = AccountIntegrate(
  157. account_id=account.id, provider=provider, open_id=open_id, encrypted_token=""
  158. )
  159. db.session.add(account_integrate)
  160. db.session.commit()
  161. logging.info(f"Account {account.id} linked {provider} account {open_id}.")
  162. except Exception as e:
  163. logging.exception(f"Failed to link {provider} account {open_id} to Account {account.id}")
  164. raise LinkAccountIntegrateError("Failed to link account.") from e
  165. @staticmethod
  166. def close_account(account: Account) -> None:
  167. """Close account"""
  168. account.status = AccountStatus.CLOSED.value
  169. db.session.commit()
  170. @staticmethod
  171. def update_account(account, **kwargs):
  172. """Update account fields"""
  173. for field, value in kwargs.items():
  174. if hasattr(account, field):
  175. setattr(account, field, value)
  176. else:
  177. raise AttributeError(f"Invalid field: {field}")
  178. db.session.commit()
  179. return account
  180. @staticmethod
  181. def update_last_login(account: Account, *, ip_address: str) -> None:
  182. """Update last login time and ip"""
  183. account.last_login_at = datetime.now(timezone.utc).replace(tzinfo=None)
  184. account.last_login_ip = ip_address
  185. db.session.add(account)
  186. db.session.commit()
  187. @staticmethod
  188. def login(account: Account, *, ip_address: Optional[str] = None):
  189. if ip_address:
  190. AccountService.update_last_login(account, ip_address=ip_address)
  191. exp = timedelta(days=30)
  192. token = AccountService.get_account_jwt_token(account, exp=exp)
  193. redis_client.set(_get_login_cache_key(account_id=account.id, token=token), "1", ex=int(exp.total_seconds()))
  194. return token
  195. @staticmethod
  196. def logout(*, account: Account, token: str):
  197. redis_client.delete(_get_login_cache_key(account_id=account.id, token=token))
  198. @staticmethod
  199. def load_logged_in_account(*, account_id: str, token: str):
  200. if not redis_client.get(_get_login_cache_key(account_id=account_id, token=token)):
  201. return None
  202. return AccountService.load_user(account_id)
  203. @classmethod
  204. def send_reset_password_email(cls, account):
  205. if cls.reset_password_rate_limiter.is_rate_limited(account.email):
  206. raise RateLimitExceededError(f"Rate limit exceeded for email: {account.email}. Please try again later.")
  207. token = TokenManager.generate_token(account, "reset_password")
  208. send_reset_password_mail_task.delay(language=account.interface_language, to=account.email, token=token)
  209. cls.reset_password_rate_limiter.increment_rate_limit(account.email)
  210. return token
  211. @classmethod
  212. def revoke_reset_password_token(cls, token: str):
  213. TokenManager.revoke_token(token, "reset_password")
  214. @classmethod
  215. def get_reset_password_data(cls, token: str) -> Optional[dict[str, Any]]:
  216. return TokenManager.get_token_data(token, "reset_password")
  217. def _get_login_cache_key(*, account_id: str, token: str):
  218. return f"account_login:{account_id}:{token}"
  219. class TenantService:
  220. @staticmethod
  221. def create_tenant(name: str) -> Tenant:
  222. """Create tenant"""
  223. tenant = Tenant(name=name)
  224. db.session.add(tenant)
  225. db.session.commit()
  226. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  227. db.session.commit()
  228. return tenant
  229. @staticmethod
  230. def create_owner_tenant_if_not_exist(account: Account, name: Optional[str] = None):
  231. """Create owner tenant if not exist"""
  232. available_ta = (
  233. TenantAccountJoin.query.filter_by(account_id=account.id).order_by(TenantAccountJoin.id.asc()).first()
  234. )
  235. if available_ta:
  236. return
  237. if name:
  238. tenant = TenantService.create_tenant(name)
  239. else:
  240. tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  241. TenantService.create_tenant_member(tenant, account, role="owner")
  242. account.current_tenant = tenant
  243. db.session.commit()
  244. tenant_was_created.send(tenant)
  245. @staticmethod
  246. def create_tenant_member(tenant: Tenant, account: Account, role: str = "normal") -> TenantAccountJoin:
  247. """Create tenant member"""
  248. if role == TenantAccountJoinRole.OWNER.value:
  249. if TenantService.has_roles(tenant, [TenantAccountJoinRole.OWNER]):
  250. logging.error(f"Tenant {tenant.id} has already an owner.")
  251. raise Exception("Tenant already has an owner.")
  252. ta = TenantAccountJoin(tenant_id=tenant.id, account_id=account.id, role=role)
  253. db.session.add(ta)
  254. db.session.commit()
  255. return ta
  256. @staticmethod
  257. def get_join_tenants(account: Account) -> list[Tenant]:
  258. """Get account join tenants"""
  259. return (
  260. db.session.query(Tenant)
  261. .join(TenantAccountJoin, Tenant.id == TenantAccountJoin.tenant_id)
  262. .filter(TenantAccountJoin.account_id == account.id, Tenant.status == TenantStatus.NORMAL)
  263. .all()
  264. )
  265. @staticmethod
  266. def get_current_tenant_by_account(account: Account):
  267. """Get tenant by account and add the role"""
  268. tenant = account.current_tenant
  269. if not tenant:
  270. raise TenantNotFoundError("Tenant not found.")
  271. ta = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=account.id).first()
  272. if ta:
  273. tenant.role = ta.role
  274. else:
  275. raise TenantNotFoundError("Tenant not found for the account.")
  276. return tenant
  277. @staticmethod
  278. def switch_tenant(account: Account, tenant_id: Optional[int] = None) -> None:
  279. """Switch the current workspace for the account"""
  280. # Ensure tenant_id is provided
  281. if tenant_id is None:
  282. raise ValueError("Tenant ID must be provided.")
  283. tenant_account_join = (
  284. db.session.query(TenantAccountJoin)
  285. .join(Tenant, TenantAccountJoin.tenant_id == Tenant.id)
  286. .filter(
  287. TenantAccountJoin.account_id == account.id,
  288. TenantAccountJoin.tenant_id == tenant_id,
  289. Tenant.status == TenantStatus.NORMAL,
  290. )
  291. .first()
  292. )
  293. if not tenant_account_join:
  294. raise AccountNotLinkTenantError("Tenant not found or account is not a member of the tenant.")
  295. else:
  296. TenantAccountJoin.query.filter(
  297. TenantAccountJoin.account_id == account.id, TenantAccountJoin.tenant_id != tenant_id
  298. ).update({"current": False})
  299. tenant_account_join.current = True
  300. # Set the current tenant for the account
  301. account.current_tenant_id = tenant_account_join.tenant_id
  302. db.session.commit()
  303. @staticmethod
  304. def get_tenant_members(tenant: Tenant) -> list[Account]:
  305. """Get tenant members"""
  306. query = (
  307. db.session.query(Account, TenantAccountJoin.role)
  308. .select_from(Account)
  309. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  310. .filter(TenantAccountJoin.tenant_id == tenant.id)
  311. )
  312. # Initialize an empty list to store the updated accounts
  313. updated_accounts = []
  314. for account, role in query:
  315. account.role = role
  316. updated_accounts.append(account)
  317. return updated_accounts
  318. @staticmethod
  319. def get_dataset_operator_members(tenant: Tenant) -> list[Account]:
  320. """Get dataset admin members"""
  321. query = (
  322. db.session.query(Account, TenantAccountJoin.role)
  323. .select_from(Account)
  324. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  325. .filter(TenantAccountJoin.tenant_id == tenant.id)
  326. .filter(TenantAccountJoin.role == "dataset_operator")
  327. )
  328. # Initialize an empty list to store the updated accounts
  329. updated_accounts = []
  330. for account, role in query:
  331. account.role = role
  332. updated_accounts.append(account)
  333. return updated_accounts
  334. @staticmethod
  335. def has_roles(tenant: Tenant, roles: list[TenantAccountJoinRole]) -> bool:
  336. """Check if user has any of the given roles for a tenant"""
  337. if not all(isinstance(role, TenantAccountJoinRole) for role in roles):
  338. raise ValueError("all roles must be TenantAccountJoinRole")
  339. return (
  340. db.session.query(TenantAccountJoin)
  341. .filter(
  342. TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.role.in_([role.value for role in roles])
  343. )
  344. .first()
  345. is not None
  346. )
  347. @staticmethod
  348. def get_user_role(account: Account, tenant: Tenant) -> Optional[TenantAccountJoinRole]:
  349. """Get the role of the current account for a given tenant"""
  350. join = (
  351. db.session.query(TenantAccountJoin)
  352. .filter(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == account.id)
  353. .first()
  354. )
  355. return join.role if join else None
  356. @staticmethod
  357. def get_tenant_count() -> int:
  358. """Get tenant count"""
  359. return db.session.query(func.count(Tenant.id)).scalar()
  360. @staticmethod
  361. def check_member_permission(tenant: Tenant, operator: Account, member: Account, action: str) -> None:
  362. """Check member permission"""
  363. perms = {
  364. "add": [TenantAccountRole.OWNER, TenantAccountRole.ADMIN],
  365. "remove": [TenantAccountRole.OWNER],
  366. "update": [TenantAccountRole.OWNER],
  367. }
  368. if action not in {"add", "remove", "update"}:
  369. raise InvalidActionError("Invalid action.")
  370. if member:
  371. if operator.id == member.id:
  372. raise CannotOperateSelfError("Cannot operate self.")
  373. ta_operator = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=operator.id).first()
  374. if not ta_operator or ta_operator.role not in perms[action]:
  375. raise NoPermissionError(f"No permission to {action} member.")
  376. @staticmethod
  377. def remove_member_from_tenant(tenant: Tenant, account: Account, operator: Account) -> None:
  378. """Remove member from tenant"""
  379. if operator.id == account.id and TenantService.check_member_permission(tenant, operator, account, "remove"):
  380. raise CannotOperateSelfError("Cannot operate self.")
  381. ta = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=account.id).first()
  382. if not ta:
  383. raise MemberNotInTenantError("Member not in tenant.")
  384. db.session.delete(ta)
  385. db.session.commit()
  386. @staticmethod
  387. def update_member_role(tenant: Tenant, member: Account, new_role: str, operator: Account) -> None:
  388. """Update member role"""
  389. TenantService.check_member_permission(tenant, operator, member, "update")
  390. target_member_join = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=member.id).first()
  391. if target_member_join.role == new_role:
  392. raise RoleAlreadyAssignedError("The provided role is already assigned to the member.")
  393. if new_role == "owner":
  394. # Find the current owner and change their role to 'admin'
  395. current_owner_join = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, role="owner").first()
  396. current_owner_join.role = "admin"
  397. # Update the role of the target member
  398. target_member_join.role = new_role
  399. db.session.commit()
  400. @staticmethod
  401. def dissolve_tenant(tenant: Tenant, operator: Account) -> None:
  402. """Dissolve tenant"""
  403. if not TenantService.check_member_permission(tenant, operator, operator, "remove"):
  404. raise NoPermissionError("No permission to dissolve tenant.")
  405. db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id).delete()
  406. db.session.delete(tenant)
  407. db.session.commit()
  408. @staticmethod
  409. def get_custom_config(tenant_id: str) -> None:
  410. tenant = db.session.query(Tenant).filter(Tenant.id == tenant_id).one_or_404()
  411. return tenant.custom_config_dict
  412. class RegisterService:
  413. @classmethod
  414. def _get_invitation_token_key(cls, token: str) -> str:
  415. return f"member_invite:token:{token}"
  416. @classmethod
  417. def setup(cls, email: str, name: str, password: str, ip_address: str) -> None:
  418. """
  419. Setup dify
  420. :param email: email
  421. :param name: username
  422. :param password: password
  423. :param ip_address: ip address
  424. """
  425. try:
  426. # Register
  427. account = AccountService.create_account(
  428. email=email,
  429. name=name,
  430. interface_language=languages[0],
  431. password=password,
  432. )
  433. account.last_login_ip = ip_address
  434. account.initialized_at = datetime.now(timezone.utc).replace(tzinfo=None)
  435. TenantService.create_owner_tenant_if_not_exist(account)
  436. dify_setup = DifySetup(version=dify_config.CURRENT_VERSION)
  437. db.session.add(dify_setup)
  438. db.session.commit()
  439. except Exception as e:
  440. db.session.query(DifySetup).delete()
  441. db.session.query(TenantAccountJoin).delete()
  442. db.session.query(Account).delete()
  443. db.session.query(Tenant).delete()
  444. db.session.commit()
  445. logging.exception(f"Setup failed: {e}")
  446. raise ValueError(f"Setup failed: {e}")
  447. @classmethod
  448. def register(
  449. cls,
  450. email,
  451. name,
  452. password: Optional[str] = None,
  453. open_id: Optional[str] = None,
  454. provider: Optional[str] = None,
  455. language: Optional[str] = None,
  456. status: Optional[AccountStatus] = None,
  457. ) -> Account:
  458. db.session.begin_nested()
  459. """Register account"""
  460. try:
  461. account = AccountService.create_account(
  462. email=email, name=name, interface_language=language or languages[0], password=password
  463. )
  464. account.status = AccountStatus.ACTIVE.value if not status else status.value
  465. account.initialized_at = datetime.now(timezone.utc).replace(tzinfo=None)
  466. if open_id is not None or provider is not None:
  467. AccountService.link_account_integrate(provider, open_id, account)
  468. if dify_config.EDITION != "SELF_HOSTED":
  469. tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  470. TenantService.create_tenant_member(tenant, account, role="owner")
  471. account.current_tenant = tenant
  472. tenant_was_created.send(tenant)
  473. db.session.commit()
  474. except Exception as e:
  475. db.session.rollback()
  476. logging.error(f"Register failed: {e}")
  477. raise AccountRegisterError(f"Registration failed: {e}") from e
  478. return account
  479. @classmethod
  480. def invite_new_member(
  481. cls, tenant: Tenant, email: str, language: str, role: str = "normal", inviter: Account = None
  482. ) -> str:
  483. """Invite new member"""
  484. account = Account.query.filter_by(email=email).first()
  485. if not account:
  486. TenantService.check_member_permission(tenant, inviter, None, "add")
  487. name = email.split("@")[0]
  488. account = cls.register(email=email, name=name, language=language, status=AccountStatus.PENDING)
  489. # Create new tenant member for invited tenant
  490. TenantService.create_tenant_member(tenant, account, role)
  491. TenantService.switch_tenant(account, tenant.id)
  492. else:
  493. TenantService.check_member_permission(tenant, inviter, account, "add")
  494. ta = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=account.id).first()
  495. if not ta:
  496. TenantService.create_tenant_member(tenant, account, role)
  497. # Support resend invitation email when the account is pending status
  498. if account.status != AccountStatus.PENDING.value:
  499. raise AccountAlreadyInTenantError("Account already in tenant.")
  500. token = cls.generate_invite_token(tenant, account)
  501. # send email
  502. send_invite_member_mail_task.delay(
  503. language=account.interface_language,
  504. to=email,
  505. token=token,
  506. inviter_name=inviter.name if inviter else "Dify",
  507. workspace_name=tenant.name,
  508. )
  509. return token
  510. @classmethod
  511. def generate_invite_token(cls, tenant: Tenant, account: Account) -> str:
  512. token = str(uuid.uuid4())
  513. invitation_data = {
  514. "account_id": account.id,
  515. "email": account.email,
  516. "workspace_id": tenant.id,
  517. }
  518. expiry_hours = dify_config.INVITE_EXPIRY_HOURS
  519. redis_client.setex(cls._get_invitation_token_key(token), expiry_hours * 60 * 60, json.dumps(invitation_data))
  520. return token
  521. @classmethod
  522. def revoke_token(cls, workspace_id: str, email: str, token: str):
  523. if workspace_id and email:
  524. email_hash = sha256(email.encode()).hexdigest()
  525. cache_key = "member_invite_token:{}, {}:{}".format(workspace_id, email_hash, token)
  526. redis_client.delete(cache_key)
  527. else:
  528. redis_client.delete(cls._get_invitation_token_key(token))
  529. @classmethod
  530. def get_invitation_if_token_valid(cls, workspace_id: str, email: str, token: str) -> Optional[dict[str, Any]]:
  531. invitation_data = cls._get_invitation_by_token(token, workspace_id, email)
  532. if not invitation_data:
  533. return None
  534. tenant = (
  535. db.session.query(Tenant)
  536. .filter(Tenant.id == invitation_data["workspace_id"], Tenant.status == "normal")
  537. .first()
  538. )
  539. if not tenant:
  540. return None
  541. tenant_account = (
  542. db.session.query(Account, TenantAccountJoin.role)
  543. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  544. .filter(Account.email == invitation_data["email"], TenantAccountJoin.tenant_id == tenant.id)
  545. .first()
  546. )
  547. if not tenant_account:
  548. return None
  549. account = tenant_account[0]
  550. if not account:
  551. return None
  552. if invitation_data["account_id"] != str(account.id):
  553. return None
  554. return {
  555. "account": account,
  556. "data": invitation_data,
  557. "tenant": tenant,
  558. }
  559. @classmethod
  560. def _get_invitation_by_token(cls, token: str, workspace_id: str, email: str) -> Optional[dict[str, str]]:
  561. if workspace_id is not None and email is not None:
  562. email_hash = sha256(email.encode()).hexdigest()
  563. cache_key = f"member_invite_token:{workspace_id}, {email_hash}:{token}"
  564. account_id = redis_client.get(cache_key)
  565. if not account_id:
  566. return None
  567. return {
  568. "account_id": account_id.decode("utf-8"),
  569. "email": email,
  570. "workspace_id": workspace_id,
  571. }
  572. else:
  573. data = redis_client.get(cls._get_invitation_token_key(token))
  574. if not data:
  575. return None
  576. invitation = json.loads(data)
  577. return invitation