account_service.py 26 KB

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