account_service.py 25 KB

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