You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

account_service.py 48KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  1. import base64
  2. import json
  3. import logging
  4. import secrets
  5. import uuid
  6. from datetime import UTC, datetime, timedelta
  7. from hashlib import sha256
  8. from typing import Any, Optional, cast
  9. from pydantic import BaseModel
  10. from sqlalchemy import func
  11. from sqlalchemy.orm import Session
  12. from werkzeug.exceptions import Unauthorized
  13. from configs import dify_config
  14. from constants.languages import language_timezone_mapping, languages
  15. from events.tenant_event import tenant_was_created
  16. from extensions.ext_database import db
  17. from extensions.ext_redis import redis_client, redis_fallback
  18. from libs.helper import RateLimiter, TokenManager
  19. from libs.passport import PassportService
  20. from libs.password import compare_password, hash_password, valid_password
  21. from libs.rsa import generate_key_pair
  22. from models.account import (
  23. Account,
  24. AccountIntegrate,
  25. AccountStatus,
  26. Tenant,
  27. TenantAccountJoin,
  28. TenantAccountRole,
  29. TenantStatus,
  30. )
  31. from models.model import DifySetup
  32. from services.billing_service import BillingService
  33. from services.errors.account import (
  34. AccountAlreadyInTenantError,
  35. AccountLoginError,
  36. AccountNotFoundError,
  37. AccountNotLinkTenantError,
  38. AccountPasswordError,
  39. AccountRegisterError,
  40. CannotOperateSelfError,
  41. CurrentPasswordIncorrectError,
  42. InvalidActionError,
  43. LinkAccountIntegrateError,
  44. MemberNotInTenantError,
  45. NoPermissionError,
  46. RoleAlreadyAssignedError,
  47. TenantNotFoundError,
  48. )
  49. from services.errors.workspace import WorkSpaceNotAllowedCreateError, WorkspacesLimitExceededError
  50. from services.feature_service import FeatureService
  51. from tasks.delete_account_task import delete_account_task
  52. from tasks.mail_account_deletion_task import send_account_deletion_verification_code
  53. from tasks.mail_change_mail_task import send_change_mail_task
  54. from tasks.mail_email_code_login import send_email_code_login_mail_task
  55. from tasks.mail_invite_member_task import send_invite_member_mail_task
  56. from tasks.mail_owner_transfer_task import (
  57. send_new_owner_transfer_notify_email_task,
  58. send_old_owner_transfer_notify_email_task,
  59. send_owner_transfer_confirm_task,
  60. )
  61. from tasks.mail_reset_password_task import send_reset_password_mail_task
  62. class TokenPair(BaseModel):
  63. access_token: str
  64. refresh_token: str
  65. REFRESH_TOKEN_PREFIX = "refresh_token:"
  66. ACCOUNT_REFRESH_TOKEN_PREFIX = "account_refresh_token:"
  67. REFRESH_TOKEN_EXPIRY = timedelta(days=dify_config.REFRESH_TOKEN_EXPIRE_DAYS)
  68. class AccountService:
  69. reset_password_rate_limiter = RateLimiter(prefix="reset_password_rate_limit", max_attempts=1, time_window=60 * 1)
  70. email_code_login_rate_limiter = RateLimiter(
  71. prefix="email_code_login_rate_limit", max_attempts=1, time_window=60 * 1
  72. )
  73. email_code_account_deletion_rate_limiter = RateLimiter(
  74. prefix="email_code_account_deletion_rate_limit", max_attempts=1, time_window=60 * 1
  75. )
  76. change_email_rate_limiter = RateLimiter(prefix="change_email_rate_limit", max_attempts=1, time_window=60 * 1)
  77. owner_transfer_rate_limiter = RateLimiter(prefix="owner_transfer_rate_limit", max_attempts=1, time_window=60 * 1)
  78. LOGIN_MAX_ERROR_LIMITS = 5
  79. FORGOT_PASSWORD_MAX_ERROR_LIMITS = 5
  80. CHANGE_EMAIL_MAX_ERROR_LIMITS = 5
  81. OWNER_TRANSFER_MAX_ERROR_LIMITS = 5
  82. @staticmethod
  83. def _get_refresh_token_key(refresh_token: str) -> str:
  84. return f"{REFRESH_TOKEN_PREFIX}{refresh_token}"
  85. @staticmethod
  86. def _get_account_refresh_token_key(account_id: str) -> str:
  87. return f"{ACCOUNT_REFRESH_TOKEN_PREFIX}{account_id}"
  88. @staticmethod
  89. def _store_refresh_token(refresh_token: str, account_id: str) -> None:
  90. redis_client.setex(AccountService._get_refresh_token_key(refresh_token), REFRESH_TOKEN_EXPIRY, account_id)
  91. redis_client.setex(
  92. AccountService._get_account_refresh_token_key(account_id), REFRESH_TOKEN_EXPIRY, refresh_token
  93. )
  94. @staticmethod
  95. def _delete_refresh_token(refresh_token: str, account_id: str) -> None:
  96. redis_client.delete(AccountService._get_refresh_token_key(refresh_token))
  97. redis_client.delete(AccountService._get_account_refresh_token_key(account_id))
  98. @staticmethod
  99. def load_user(user_id: str) -> None | Account:
  100. account = db.session.query(Account).filter_by(id=user_id).first()
  101. if not account:
  102. return None
  103. if account.status == AccountStatus.BANNED.value:
  104. raise Unauthorized("Account is banned.")
  105. current_tenant = db.session.query(TenantAccountJoin).filter_by(account_id=account.id, current=True).first()
  106. if current_tenant:
  107. account.set_tenant_id(current_tenant.tenant_id)
  108. else:
  109. available_ta = (
  110. db.session.query(TenantAccountJoin)
  111. .filter_by(account_id=account.id)
  112. .order_by(TenantAccountJoin.id.asc())
  113. .first()
  114. )
  115. if not available_ta:
  116. return None
  117. account.set_tenant_id(available_ta.tenant_id)
  118. available_ta.current = True
  119. db.session.commit()
  120. if datetime.now(UTC).replace(tzinfo=None) - account.last_active_at > timedelta(minutes=10):
  121. account.last_active_at = datetime.now(UTC).replace(tzinfo=None)
  122. db.session.commit()
  123. return cast(Account, account)
  124. @staticmethod
  125. def get_account_jwt_token(account: Account) -> str:
  126. exp_dt = datetime.now(UTC) + timedelta(minutes=dify_config.ACCESS_TOKEN_EXPIRE_MINUTES)
  127. exp = int(exp_dt.timestamp())
  128. payload = {
  129. "user_id": account.id,
  130. "exp": exp,
  131. "iss": dify_config.EDITION,
  132. "sub": "Console API Passport",
  133. }
  134. token: str = PassportService().issue(payload)
  135. return token
  136. @staticmethod
  137. def authenticate(email: str, password: str, invite_token: Optional[str] = None) -> Account:
  138. """authenticate account with email and password"""
  139. account = db.session.query(Account).filter_by(email=email).first()
  140. if not account:
  141. raise AccountNotFoundError()
  142. if account.status == AccountStatus.BANNED.value:
  143. raise AccountLoginError("Account is banned.")
  144. if password and invite_token and account.password is None:
  145. # if invite_token is valid, set password and password_salt
  146. salt = secrets.token_bytes(16)
  147. base64_salt = base64.b64encode(salt).decode()
  148. password_hashed = hash_password(password, salt)
  149. base64_password_hashed = base64.b64encode(password_hashed).decode()
  150. account.password = base64_password_hashed
  151. account.password_salt = base64_salt
  152. if account.password is None or not compare_password(password, account.password, account.password_salt):
  153. raise AccountPasswordError("Invalid email or password.")
  154. if account.status == AccountStatus.PENDING.value:
  155. account.status = AccountStatus.ACTIVE.value
  156. account.initialized_at = datetime.now(UTC).replace(tzinfo=None)
  157. db.session.commit()
  158. return cast(Account, account)
  159. @staticmethod
  160. def update_account_password(account, password, new_password):
  161. """update account password"""
  162. if account.password and not compare_password(password, account.password, account.password_salt):
  163. raise CurrentPasswordIncorrectError("Current password is incorrect.")
  164. # may be raised
  165. valid_password(new_password)
  166. # generate password salt
  167. salt = secrets.token_bytes(16)
  168. base64_salt = base64.b64encode(salt).decode()
  169. # encrypt password with salt
  170. password_hashed = hash_password(new_password, salt)
  171. base64_password_hashed = base64.b64encode(password_hashed).decode()
  172. account.password = base64_password_hashed
  173. account.password_salt = base64_salt
  174. db.session.commit()
  175. return account
  176. @staticmethod
  177. def create_account(
  178. email: str,
  179. name: str,
  180. interface_language: str,
  181. password: Optional[str] = None,
  182. interface_theme: str = "light",
  183. is_setup: Optional[bool] = False,
  184. ) -> Account:
  185. """create account"""
  186. if not FeatureService.get_system_features().is_allow_register and not is_setup:
  187. from controllers.console.error import AccountNotFound
  188. raise AccountNotFound()
  189. if dify_config.BILLING_ENABLED and BillingService.is_email_in_freeze(email):
  190. raise AccountRegisterError(
  191. description=(
  192. "This email account has been deleted within the past "
  193. "30 days and is temporarily unavailable for new account registration"
  194. )
  195. )
  196. account = Account()
  197. account.email = email
  198. account.name = name
  199. if password:
  200. # generate password salt
  201. salt = secrets.token_bytes(16)
  202. base64_salt = base64.b64encode(salt).decode()
  203. # encrypt password with salt
  204. password_hashed = hash_password(password, salt)
  205. base64_password_hashed = base64.b64encode(password_hashed).decode()
  206. account.password = base64_password_hashed
  207. account.password_salt = base64_salt
  208. account.interface_language = interface_language
  209. account.interface_theme = interface_theme
  210. # Set timezone based on language
  211. account.timezone = language_timezone_mapping.get(interface_language, "UTC")
  212. db.session.add(account)
  213. db.session.commit()
  214. return account
  215. @staticmethod
  216. def create_account_and_tenant(
  217. email: str, name: str, interface_language: str, password: Optional[str] = None
  218. ) -> Account:
  219. """create account"""
  220. account = AccountService.create_account(
  221. email=email, name=name, interface_language=interface_language, password=password
  222. )
  223. TenantService.create_owner_tenant_if_not_exist(account=account)
  224. return account
  225. @staticmethod
  226. def generate_account_deletion_verification_code(account: Account) -> tuple[str, str]:
  227. code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])
  228. token = TokenManager.generate_token(
  229. account=account, token_type="account_deletion", additional_data={"code": code}
  230. )
  231. return token, code
  232. @classmethod
  233. def send_account_deletion_verification_email(cls, account: Account, code: str):
  234. email = account.email
  235. if cls.email_code_account_deletion_rate_limiter.is_rate_limited(email):
  236. from controllers.console.auth.error import EmailCodeAccountDeletionRateLimitExceededError
  237. raise EmailCodeAccountDeletionRateLimitExceededError()
  238. send_account_deletion_verification_code.delay(to=email, code=code)
  239. cls.email_code_account_deletion_rate_limiter.increment_rate_limit(email)
  240. @staticmethod
  241. def verify_account_deletion_code(token: str, code: str) -> bool:
  242. token_data = TokenManager.get_token_data(token, "account_deletion")
  243. if token_data is None:
  244. return False
  245. if token_data["code"] != code:
  246. return False
  247. return True
  248. @staticmethod
  249. def delete_account(account: Account) -> None:
  250. """Delete account. This method only adds a task to the queue for deletion."""
  251. delete_account_task.delay(account.id)
  252. @staticmethod
  253. def link_account_integrate(provider: str, open_id: str, account: Account) -> None:
  254. """Link account integrate"""
  255. try:
  256. # Query whether there is an existing binding record for the same provider
  257. account_integrate: Optional[AccountIntegrate] = (
  258. db.session.query(AccountIntegrate).filter_by(account_id=account.id, provider=provider).first()
  259. )
  260. if account_integrate:
  261. # If it exists, update the record
  262. account_integrate.open_id = open_id
  263. account_integrate.encrypted_token = "" # todo
  264. account_integrate.updated_at = datetime.now(UTC).replace(tzinfo=None)
  265. else:
  266. # If it does not exist, create a new record
  267. account_integrate = AccountIntegrate(
  268. account_id=account.id, provider=provider, open_id=open_id, encrypted_token=""
  269. )
  270. db.session.add(account_integrate)
  271. db.session.commit()
  272. logging.info(f"Account {account.id} linked {provider} account {open_id}.")
  273. except Exception as e:
  274. logging.exception(f"Failed to link {provider} account {open_id} to Account {account.id}")
  275. raise LinkAccountIntegrateError("Failed to link account.") from e
  276. @staticmethod
  277. def close_account(account: Account) -> None:
  278. """Close account"""
  279. account.status = AccountStatus.CLOSED.value
  280. db.session.commit()
  281. @staticmethod
  282. def update_account(account, **kwargs):
  283. """Update account fields"""
  284. for field, value in kwargs.items():
  285. if hasattr(account, field):
  286. setattr(account, field, value)
  287. else:
  288. raise AttributeError(f"Invalid field: {field}")
  289. db.session.commit()
  290. return account
  291. @staticmethod
  292. def update_login_info(account: Account, *, ip_address: str) -> None:
  293. """Update last login time and ip"""
  294. account.last_login_at = datetime.now(UTC).replace(tzinfo=None)
  295. account.last_login_ip = ip_address
  296. db.session.add(account)
  297. db.session.commit()
  298. @staticmethod
  299. def login(account: Account, *, ip_address: Optional[str] = None) -> TokenPair:
  300. if ip_address:
  301. AccountService.update_login_info(account=account, ip_address=ip_address)
  302. if account.status == AccountStatus.PENDING.value:
  303. account.status = AccountStatus.ACTIVE.value
  304. db.session.commit()
  305. access_token = AccountService.get_account_jwt_token(account=account)
  306. refresh_token = _generate_refresh_token()
  307. AccountService._store_refresh_token(refresh_token, account.id)
  308. return TokenPair(access_token=access_token, refresh_token=refresh_token)
  309. @staticmethod
  310. def logout(*, account: Account) -> None:
  311. refresh_token = redis_client.get(AccountService._get_account_refresh_token_key(account.id))
  312. if refresh_token:
  313. AccountService._delete_refresh_token(refresh_token.decode("utf-8"), account.id)
  314. @staticmethod
  315. def refresh_token(refresh_token: str) -> TokenPair:
  316. # Verify the refresh token
  317. account_id = redis_client.get(AccountService._get_refresh_token_key(refresh_token))
  318. if not account_id:
  319. raise ValueError("Invalid refresh token")
  320. account = AccountService.load_user(account_id.decode("utf-8"))
  321. if not account:
  322. raise ValueError("Invalid account")
  323. # Generate new access token and refresh token
  324. new_access_token = AccountService.get_account_jwt_token(account)
  325. new_refresh_token = _generate_refresh_token()
  326. AccountService._delete_refresh_token(refresh_token, account.id)
  327. AccountService._store_refresh_token(new_refresh_token, account.id)
  328. return TokenPair(access_token=new_access_token, refresh_token=new_refresh_token)
  329. @staticmethod
  330. def load_logged_in_account(*, account_id: str):
  331. return AccountService.load_user(account_id)
  332. @classmethod
  333. def send_reset_password_email(
  334. cls,
  335. account: Optional[Account] = None,
  336. email: Optional[str] = None,
  337. language: Optional[str] = "en-US",
  338. ):
  339. account_email = account.email if account else email
  340. if account_email is None:
  341. raise ValueError("Email must be provided.")
  342. if cls.reset_password_rate_limiter.is_rate_limited(account_email):
  343. from controllers.console.auth.error import PasswordResetRateLimitExceededError
  344. raise PasswordResetRateLimitExceededError()
  345. code, token = cls.generate_reset_password_token(account_email, account)
  346. send_reset_password_mail_task.delay(
  347. language=language,
  348. to=account_email,
  349. code=code,
  350. )
  351. cls.reset_password_rate_limiter.increment_rate_limit(account_email)
  352. return token
  353. @classmethod
  354. def send_change_email_email(
  355. cls,
  356. account: Optional[Account] = None,
  357. email: Optional[str] = None,
  358. old_email: Optional[str] = None,
  359. language: Optional[str] = "en-US",
  360. phase: Optional[str] = None,
  361. ):
  362. account_email = account.email if account else email
  363. if account_email is None:
  364. raise ValueError("Email must be provided.")
  365. if cls.change_email_rate_limiter.is_rate_limited(account_email):
  366. from controllers.console.auth.error import EmailChangeRateLimitExceededError
  367. raise EmailChangeRateLimitExceededError()
  368. code, token = cls.generate_change_email_token(account_email, account, old_email=old_email)
  369. send_change_mail_task.delay(
  370. language=language,
  371. to=account_email,
  372. code=code,
  373. phase=phase,
  374. )
  375. cls.change_email_rate_limiter.increment_rate_limit(account_email)
  376. return token
  377. @classmethod
  378. def send_owner_transfer_email(
  379. cls,
  380. account: Optional[Account] = None,
  381. email: Optional[str] = None,
  382. language: Optional[str] = "en-US",
  383. workspace_name: Optional[str] = "",
  384. ):
  385. account_email = account.email if account else email
  386. if account_email is None:
  387. raise ValueError("Email must be provided.")
  388. if cls.owner_transfer_rate_limiter.is_rate_limited(account_email):
  389. from controllers.console.auth.error import OwnerTransferRateLimitExceededError
  390. raise OwnerTransferRateLimitExceededError()
  391. code, token = cls.generate_owner_transfer_token(account_email, account)
  392. send_owner_transfer_confirm_task.delay(
  393. language=language,
  394. to=account_email,
  395. code=code,
  396. workspace=workspace_name,
  397. )
  398. cls.owner_transfer_rate_limiter.increment_rate_limit(account_email)
  399. return token
  400. @classmethod
  401. def send_old_owner_transfer_notify_email(
  402. cls,
  403. account: Optional[Account] = None,
  404. email: Optional[str] = None,
  405. language: Optional[str] = "en-US",
  406. workspace_name: Optional[str] = "",
  407. new_owner_email: Optional[str] = "",
  408. ):
  409. account_email = account.email if account else email
  410. if account_email is None:
  411. raise ValueError("Email must be provided.")
  412. send_old_owner_transfer_notify_email_task.delay(
  413. language=language,
  414. to=account_email,
  415. workspace=workspace_name,
  416. new_owner_email=new_owner_email,
  417. )
  418. @classmethod
  419. def send_new_owner_transfer_notify_email(
  420. cls,
  421. account: Optional[Account] = None,
  422. email: Optional[str] = None,
  423. language: Optional[str] = "en-US",
  424. workspace_name: Optional[str] = "",
  425. ):
  426. account_email = account.email if account else email
  427. if account_email is None:
  428. raise ValueError("Email must be provided.")
  429. send_new_owner_transfer_notify_email_task.delay(
  430. language=language,
  431. to=account_email,
  432. workspace=workspace_name,
  433. )
  434. @classmethod
  435. def generate_reset_password_token(
  436. cls,
  437. email: str,
  438. account: Optional[Account] = None,
  439. code: Optional[str] = None,
  440. additional_data: dict[str, Any] = {},
  441. ):
  442. if not code:
  443. code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])
  444. additional_data["code"] = code
  445. token = TokenManager.generate_token(
  446. account=account, email=email, token_type="reset_password", additional_data=additional_data
  447. )
  448. return code, token
  449. @classmethod
  450. def generate_change_email_token(
  451. cls,
  452. email: str,
  453. account: Optional[Account] = None,
  454. code: Optional[str] = None,
  455. old_email: Optional[str] = None,
  456. additional_data: dict[str, Any] = {},
  457. ):
  458. if not code:
  459. code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])
  460. additional_data["code"] = code
  461. additional_data["old_email"] = old_email
  462. token = TokenManager.generate_token(
  463. account=account, email=email, token_type="change_email", additional_data=additional_data
  464. )
  465. return code, token
  466. @classmethod
  467. def generate_owner_transfer_token(
  468. cls,
  469. email: str,
  470. account: Optional[Account] = None,
  471. code: Optional[str] = None,
  472. additional_data: dict[str, Any] = {},
  473. ):
  474. if not code:
  475. code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])
  476. additional_data["code"] = code
  477. token = TokenManager.generate_token(
  478. account=account, email=email, token_type="owner_transfer", additional_data=additional_data
  479. )
  480. return code, token
  481. @classmethod
  482. def revoke_reset_password_token(cls, token: str):
  483. TokenManager.revoke_token(token, "reset_password")
  484. @classmethod
  485. def revoke_change_email_token(cls, token: str):
  486. TokenManager.revoke_token(token, "change_email")
  487. @classmethod
  488. def revoke_owner_transfer_token(cls, token: str):
  489. TokenManager.revoke_token(token, "owner_transfer")
  490. @classmethod
  491. def get_reset_password_data(cls, token: str) -> Optional[dict[str, Any]]:
  492. return TokenManager.get_token_data(token, "reset_password")
  493. @classmethod
  494. def get_change_email_data(cls, token: str) -> Optional[dict[str, Any]]:
  495. return TokenManager.get_token_data(token, "change_email")
  496. @classmethod
  497. def get_owner_transfer_data(cls, token: str) -> Optional[dict[str, Any]]:
  498. return TokenManager.get_token_data(token, "owner_transfer")
  499. @classmethod
  500. def send_email_code_login_email(
  501. cls, account: Optional[Account] = None, email: Optional[str] = None, language: Optional[str] = "en-US"
  502. ):
  503. email = account.email if account else email
  504. if email is None:
  505. raise ValueError("Email must be provided.")
  506. if cls.email_code_login_rate_limiter.is_rate_limited(email):
  507. from controllers.console.auth.error import EmailCodeLoginRateLimitExceededError
  508. raise EmailCodeLoginRateLimitExceededError()
  509. code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])
  510. token = TokenManager.generate_token(
  511. account=account, email=email, token_type="email_code_login", additional_data={"code": code}
  512. )
  513. send_email_code_login_mail_task.delay(
  514. language=language,
  515. to=account.email if account else email,
  516. code=code,
  517. )
  518. cls.email_code_login_rate_limiter.increment_rate_limit(email)
  519. return token
  520. @classmethod
  521. def get_email_code_login_data(cls, token: str) -> Optional[dict[str, Any]]:
  522. return TokenManager.get_token_data(token, "email_code_login")
  523. @classmethod
  524. def revoke_email_code_login_token(cls, token: str):
  525. TokenManager.revoke_token(token, "email_code_login")
  526. @classmethod
  527. def get_user_through_email(cls, email: str):
  528. if dify_config.BILLING_ENABLED and BillingService.is_email_in_freeze(email):
  529. raise AccountRegisterError(
  530. description=(
  531. "This email account has been deleted within the past "
  532. "30 days and is temporarily unavailable for new account registration"
  533. )
  534. )
  535. account = db.session.query(Account).filter(Account.email == email).first()
  536. if not account:
  537. return None
  538. if account.status == AccountStatus.BANNED.value:
  539. raise Unauthorized("Account is banned.")
  540. return account
  541. @staticmethod
  542. @redis_fallback(default_return=None)
  543. def add_login_error_rate_limit(email: str) -> None:
  544. key = f"login_error_rate_limit:{email}"
  545. count = redis_client.get(key)
  546. if count is None:
  547. count = 0
  548. count = int(count) + 1
  549. redis_client.setex(key, dify_config.LOGIN_LOCKOUT_DURATION, count)
  550. @staticmethod
  551. @redis_fallback(default_return=False)
  552. def is_login_error_rate_limit(email: str) -> bool:
  553. key = f"login_error_rate_limit:{email}"
  554. count = redis_client.get(key)
  555. if count is None:
  556. return False
  557. count = int(count)
  558. if count > AccountService.LOGIN_MAX_ERROR_LIMITS:
  559. return True
  560. return False
  561. @staticmethod
  562. @redis_fallback(default_return=None)
  563. def reset_login_error_rate_limit(email: str):
  564. key = f"login_error_rate_limit:{email}"
  565. redis_client.delete(key)
  566. @staticmethod
  567. @redis_fallback(default_return=None)
  568. def add_forgot_password_error_rate_limit(email: str) -> None:
  569. key = f"forgot_password_error_rate_limit:{email}"
  570. count = redis_client.get(key)
  571. if count is None:
  572. count = 0
  573. count = int(count) + 1
  574. redis_client.setex(key, dify_config.FORGOT_PASSWORD_LOCKOUT_DURATION, count)
  575. @staticmethod
  576. @redis_fallback(default_return=False)
  577. def is_forgot_password_error_rate_limit(email: str) -> bool:
  578. key = f"forgot_password_error_rate_limit:{email}"
  579. count = redis_client.get(key)
  580. if count is None:
  581. return False
  582. count = int(count)
  583. if count > AccountService.FORGOT_PASSWORD_MAX_ERROR_LIMITS:
  584. return True
  585. return False
  586. @staticmethod
  587. @redis_fallback(default_return=None)
  588. def reset_forgot_password_error_rate_limit(email: str):
  589. key = f"forgot_password_error_rate_limit:{email}"
  590. redis_client.delete(key)
  591. @staticmethod
  592. @redis_fallback(default_return=None)
  593. def add_change_email_error_rate_limit(email: str) -> None:
  594. key = f"change_email_error_rate_limit:{email}"
  595. count = redis_client.get(key)
  596. if count is None:
  597. count = 0
  598. count = int(count) + 1
  599. redis_client.setex(key, dify_config.CHANGE_EMAIL_LOCKOUT_DURATION, count)
  600. @staticmethod
  601. @redis_fallback(default_return=False)
  602. def is_change_email_error_rate_limit(email: str) -> bool:
  603. key = f"change_email_error_rate_limit:{email}"
  604. count = redis_client.get(key)
  605. if count is None:
  606. return False
  607. count = int(count)
  608. if count > AccountService.CHANGE_EMAIL_MAX_ERROR_LIMITS:
  609. return True
  610. return False
  611. @staticmethod
  612. @redis_fallback(default_return=None)
  613. def reset_change_email_error_rate_limit(email: str):
  614. key = f"change_email_error_rate_limit:{email}"
  615. redis_client.delete(key)
  616. @staticmethod
  617. @redis_fallback(default_return=None)
  618. def add_owner_transfer_error_rate_limit(email: str) -> None:
  619. key = f"owner_transfer_error_rate_limit:{email}"
  620. count = redis_client.get(key)
  621. if count is None:
  622. count = 0
  623. count = int(count) + 1
  624. redis_client.setex(key, dify_config.OWNER_TRANSFER_LOCKOUT_DURATION, count)
  625. @staticmethod
  626. @redis_fallback(default_return=False)
  627. def is_owner_transfer_error_rate_limit(email: str) -> bool:
  628. key = f"owner_transfer_error_rate_limit:{email}"
  629. count = redis_client.get(key)
  630. if count is None:
  631. return False
  632. count = int(count)
  633. if count > AccountService.OWNER_TRANSFER_MAX_ERROR_LIMITS:
  634. return True
  635. return False
  636. @staticmethod
  637. @redis_fallback(default_return=None)
  638. def reset_owner_transfer_error_rate_limit(email: str):
  639. key = f"owner_transfer_error_rate_limit:{email}"
  640. redis_client.delete(key)
  641. @staticmethod
  642. @redis_fallback(default_return=False)
  643. def is_email_send_ip_limit(ip_address: str):
  644. minute_key = f"email_send_ip_limit_minute:{ip_address}"
  645. freeze_key = f"email_send_ip_limit_freeze:{ip_address}"
  646. hour_limit_key = f"email_send_ip_limit_hour:{ip_address}"
  647. # check ip is frozen
  648. if redis_client.get(freeze_key):
  649. return True
  650. # check current minute count
  651. current_minute_count = redis_client.get(minute_key)
  652. if current_minute_count is None:
  653. current_minute_count = 0
  654. current_minute_count = int(current_minute_count)
  655. # check current hour count
  656. if current_minute_count > dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE:
  657. hour_limit_count = redis_client.get(hour_limit_key)
  658. if hour_limit_count is None:
  659. hour_limit_count = 0
  660. hour_limit_count = int(hour_limit_count)
  661. if hour_limit_count >= 1:
  662. redis_client.setex(freeze_key, 60 * 60, 1)
  663. return True
  664. else:
  665. redis_client.setex(hour_limit_key, 60 * 10, hour_limit_count + 1) # first time limit 10 minutes
  666. # add hour limit count
  667. redis_client.incr(hour_limit_key)
  668. redis_client.expire(hour_limit_key, 60 * 60)
  669. return True
  670. redis_client.setex(minute_key, 60, current_minute_count + 1)
  671. redis_client.expire(minute_key, 60)
  672. return False
  673. @staticmethod
  674. def check_email_unique(email: str) -> bool:
  675. return db.session.query(Account).filter_by(email=email).first() is None
  676. class TenantService:
  677. @staticmethod
  678. def create_tenant(name: str, is_setup: Optional[bool] = False, is_from_dashboard: Optional[bool] = False) -> Tenant:
  679. """Create tenant"""
  680. if (
  681. not FeatureService.get_system_features().is_allow_create_workspace
  682. and not is_setup
  683. and not is_from_dashboard
  684. ):
  685. from controllers.console.error import NotAllowedCreateWorkspace
  686. raise NotAllowedCreateWorkspace()
  687. tenant = Tenant(name=name)
  688. db.session.add(tenant)
  689. db.session.commit()
  690. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  691. db.session.commit()
  692. return tenant
  693. @staticmethod
  694. def create_owner_tenant_if_not_exist(
  695. account: Account, name: Optional[str] = None, is_setup: Optional[bool] = False
  696. ):
  697. """Check if user have a workspace or not"""
  698. available_ta = (
  699. db.session.query(TenantAccountJoin)
  700. .filter_by(account_id=account.id)
  701. .order_by(TenantAccountJoin.id.asc())
  702. .first()
  703. )
  704. if available_ta:
  705. return
  706. """Create owner tenant if not exist"""
  707. if not FeatureService.get_system_features().is_allow_create_workspace and not is_setup:
  708. raise WorkSpaceNotAllowedCreateError()
  709. workspaces = FeatureService.get_system_features().license.workspaces
  710. if not workspaces.is_available():
  711. raise WorkspacesLimitExceededError()
  712. if name:
  713. tenant = TenantService.create_tenant(name=name, is_setup=is_setup)
  714. else:
  715. tenant = TenantService.create_tenant(name=f"{account.name}'s Workspace", is_setup=is_setup)
  716. TenantService.create_tenant_member(tenant, account, role="owner")
  717. account.current_tenant = tenant
  718. db.session.commit()
  719. tenant_was_created.send(tenant)
  720. @staticmethod
  721. def create_tenant_member(tenant: Tenant, account: Account, role: str = "normal") -> TenantAccountJoin:
  722. """Create tenant member"""
  723. if role == TenantAccountRole.OWNER.value:
  724. if TenantService.has_roles(tenant, [TenantAccountRole.OWNER]):
  725. logging.error(f"Tenant {tenant.id} has already an owner.")
  726. raise Exception("Tenant already has an owner.")
  727. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  728. if ta:
  729. ta.role = role
  730. else:
  731. ta = TenantAccountJoin(tenant_id=tenant.id, account_id=account.id, role=role)
  732. db.session.add(ta)
  733. db.session.commit()
  734. return ta
  735. @staticmethod
  736. def get_join_tenants(account: Account) -> list[Tenant]:
  737. """Get account join tenants"""
  738. return (
  739. db.session.query(Tenant)
  740. .join(TenantAccountJoin, Tenant.id == TenantAccountJoin.tenant_id)
  741. .filter(TenantAccountJoin.account_id == account.id, Tenant.status == TenantStatus.NORMAL)
  742. .all()
  743. )
  744. @staticmethod
  745. def get_current_tenant_by_account(account: Account):
  746. """Get tenant by account and add the role"""
  747. tenant = account.current_tenant
  748. if not tenant:
  749. raise TenantNotFoundError("Tenant not found.")
  750. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  751. if ta:
  752. tenant.role = ta.role
  753. else:
  754. raise TenantNotFoundError("Tenant not found for the account.")
  755. return tenant
  756. @staticmethod
  757. def switch_tenant(account: Account, tenant_id: Optional[str] = None) -> None:
  758. """Switch the current workspace for the account"""
  759. # Ensure tenant_id is provided
  760. if tenant_id is None:
  761. raise ValueError("Tenant ID must be provided.")
  762. tenant_account_join = (
  763. db.session.query(TenantAccountJoin)
  764. .join(Tenant, TenantAccountJoin.tenant_id == Tenant.id)
  765. .filter(
  766. TenantAccountJoin.account_id == account.id,
  767. TenantAccountJoin.tenant_id == tenant_id,
  768. Tenant.status == TenantStatus.NORMAL,
  769. )
  770. .first()
  771. )
  772. if not tenant_account_join:
  773. raise AccountNotLinkTenantError("Tenant not found or account is not a member of the tenant.")
  774. else:
  775. db.session.query(TenantAccountJoin).filter(
  776. TenantAccountJoin.account_id == account.id, TenantAccountJoin.tenant_id != tenant_id
  777. ).update({"current": False})
  778. tenant_account_join.current = True
  779. # Set the current tenant for the account
  780. account.set_tenant_id(tenant_account_join.tenant_id)
  781. db.session.commit()
  782. @staticmethod
  783. def get_tenant_members(tenant: Tenant) -> list[Account]:
  784. """Get tenant members"""
  785. query = (
  786. db.session.query(Account, TenantAccountJoin.role)
  787. .select_from(Account)
  788. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  789. .filter(TenantAccountJoin.tenant_id == tenant.id)
  790. )
  791. # Initialize an empty list to store the updated accounts
  792. updated_accounts = []
  793. for account, role in query:
  794. account.role = role
  795. updated_accounts.append(account)
  796. return updated_accounts
  797. @staticmethod
  798. def get_dataset_operator_members(tenant: Tenant) -> list[Account]:
  799. """Get dataset admin members"""
  800. query = (
  801. db.session.query(Account, TenantAccountJoin.role)
  802. .select_from(Account)
  803. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  804. .filter(TenantAccountJoin.tenant_id == tenant.id)
  805. .filter(TenantAccountJoin.role == "dataset_operator")
  806. )
  807. # Initialize an empty list to store the updated accounts
  808. updated_accounts = []
  809. for account, role in query:
  810. account.role = role
  811. updated_accounts.append(account)
  812. return updated_accounts
  813. @staticmethod
  814. def has_roles(tenant: Tenant, roles: list[TenantAccountRole]) -> bool:
  815. """Check if user has any of the given roles for a tenant"""
  816. if not all(isinstance(role, TenantAccountRole) for role in roles):
  817. raise ValueError("all roles must be TenantAccountRole")
  818. return (
  819. db.session.query(TenantAccountJoin)
  820. .filter(
  821. TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.role.in_([role.value for role in roles])
  822. )
  823. .first()
  824. is not None
  825. )
  826. @staticmethod
  827. def get_user_role(account: Account, tenant: Tenant) -> Optional[TenantAccountRole]:
  828. """Get the role of the current account for a given tenant"""
  829. join = (
  830. db.session.query(TenantAccountJoin)
  831. .filter(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == account.id)
  832. .first()
  833. )
  834. return join.role if join else None
  835. @staticmethod
  836. def get_tenant_count() -> int:
  837. """Get tenant count"""
  838. return cast(int, db.session.query(func.count(Tenant.id)).scalar())
  839. @staticmethod
  840. def check_member_permission(tenant: Tenant, operator: Account, member: Account | None, action: str) -> None:
  841. """Check member permission"""
  842. perms = {
  843. "add": [TenantAccountRole.OWNER, TenantAccountRole.ADMIN],
  844. "remove": [TenantAccountRole.OWNER],
  845. "update": [TenantAccountRole.OWNER],
  846. }
  847. if action not in {"add", "remove", "update"}:
  848. raise InvalidActionError("Invalid action.")
  849. if member:
  850. if operator.id == member.id:
  851. raise CannotOperateSelfError("Cannot operate self.")
  852. ta_operator = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=operator.id).first()
  853. if not ta_operator or ta_operator.role not in perms[action]:
  854. raise NoPermissionError(f"No permission to {action} member.")
  855. @staticmethod
  856. def remove_member_from_tenant(tenant: Tenant, account: Account, operator: Account) -> None:
  857. """Remove member from tenant"""
  858. if operator.id == account.id:
  859. raise CannotOperateSelfError("Cannot operate self.")
  860. TenantService.check_member_permission(tenant, operator, account, "remove")
  861. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  862. if not ta:
  863. raise MemberNotInTenantError("Member not in tenant.")
  864. db.session.delete(ta)
  865. db.session.commit()
  866. @staticmethod
  867. def update_member_role(tenant: Tenant, member: Account, new_role: str, operator: Account) -> None:
  868. """Update member role"""
  869. TenantService.check_member_permission(tenant, operator, member, "update")
  870. target_member_join = (
  871. db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=member.id).first()
  872. )
  873. if not target_member_join:
  874. raise MemberNotInTenantError("Member not in tenant.")
  875. if target_member_join.role == new_role:
  876. raise RoleAlreadyAssignedError("The provided role is already assigned to the member.")
  877. if new_role == "owner":
  878. # Find the current owner and change their role to 'admin'
  879. current_owner_join = (
  880. db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, role="owner").first()
  881. )
  882. if current_owner_join:
  883. current_owner_join.role = "admin"
  884. # Update the role of the target member
  885. target_member_join.role = new_role
  886. db.session.commit()
  887. @staticmethod
  888. def dissolve_tenant(tenant: Tenant, operator: Account) -> None:
  889. """Dissolve tenant"""
  890. if not TenantService.check_member_permission(tenant, operator, operator, "remove"):
  891. raise NoPermissionError("No permission to dissolve tenant.")
  892. db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id).delete()
  893. db.session.delete(tenant)
  894. db.session.commit()
  895. @staticmethod
  896. def get_custom_config(tenant_id: str) -> dict:
  897. tenant = db.get_or_404(Tenant, tenant_id)
  898. return cast(dict, tenant.custom_config_dict)
  899. @staticmethod
  900. def is_owner(account: Account, tenant: Tenant) -> bool:
  901. return TenantService.get_user_role(account, tenant) == TenantAccountRole.OWNER
  902. @staticmethod
  903. def is_member(account: Account, tenant: Tenant) -> bool:
  904. """Check if the account is a member of the tenant"""
  905. return TenantService.get_user_role(account, tenant) is not None
  906. class RegisterService:
  907. @classmethod
  908. def _get_invitation_token_key(cls, token: str) -> str:
  909. return f"member_invite:token:{token}"
  910. @classmethod
  911. def setup(cls, email: str, name: str, password: str, ip_address: str) -> None:
  912. """
  913. Setup dify
  914. :param email: email
  915. :param name: username
  916. :param password: password
  917. :param ip_address: ip address
  918. """
  919. try:
  920. # Register
  921. account = AccountService.create_account(
  922. email=email,
  923. name=name,
  924. interface_language=languages[0],
  925. password=password,
  926. is_setup=True,
  927. )
  928. account.last_login_ip = ip_address
  929. account.initialized_at = datetime.now(UTC).replace(tzinfo=None)
  930. TenantService.create_owner_tenant_if_not_exist(account=account, is_setup=True)
  931. dify_setup = DifySetup(version=dify_config.project.version)
  932. db.session.add(dify_setup)
  933. db.session.commit()
  934. except Exception as e:
  935. db.session.query(DifySetup).delete()
  936. db.session.query(TenantAccountJoin).delete()
  937. db.session.query(Account).delete()
  938. db.session.query(Tenant).delete()
  939. db.session.commit()
  940. logging.exception(f"Setup account failed, email: {email}, name: {name}")
  941. raise ValueError(f"Setup failed: {e}")
  942. @classmethod
  943. def register(
  944. cls,
  945. email,
  946. name,
  947. password: Optional[str] = None,
  948. open_id: Optional[str] = None,
  949. provider: Optional[str] = None,
  950. language: Optional[str] = None,
  951. status: Optional[AccountStatus] = None,
  952. is_setup: Optional[bool] = False,
  953. create_workspace_required: Optional[bool] = True,
  954. ) -> Account:
  955. db.session.begin_nested()
  956. """Register account"""
  957. try:
  958. account = AccountService.create_account(
  959. email=email,
  960. name=name,
  961. interface_language=language or languages[0],
  962. password=password,
  963. is_setup=is_setup,
  964. )
  965. account.status = AccountStatus.ACTIVE.value if not status else status.value
  966. account.initialized_at = datetime.now(UTC).replace(tzinfo=None)
  967. if open_id is not None and provider is not None:
  968. AccountService.link_account_integrate(provider, open_id, account)
  969. if (
  970. FeatureService.get_system_features().is_allow_create_workspace
  971. and create_workspace_required
  972. and FeatureService.get_system_features().license.workspaces.is_available()
  973. ):
  974. tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  975. TenantService.create_tenant_member(tenant, account, role="owner")
  976. account.current_tenant = tenant
  977. tenant_was_created.send(tenant)
  978. db.session.commit()
  979. except WorkSpaceNotAllowedCreateError:
  980. db.session.rollback()
  981. logging.exception("Register failed")
  982. raise AccountRegisterError("Workspace is not allowed to create.")
  983. except AccountRegisterError as are:
  984. db.session.rollback()
  985. logging.exception("Register failed")
  986. raise are
  987. except Exception as e:
  988. db.session.rollback()
  989. logging.exception("Register failed")
  990. raise AccountRegisterError(f"Registration failed: {e}") from e
  991. return account
  992. @classmethod
  993. def invite_new_member(
  994. cls, tenant: Tenant, email: str, language: str, role: str = "normal", inviter: Account | None = None
  995. ) -> str:
  996. if not inviter:
  997. raise ValueError("Inviter is required")
  998. """Invite new member"""
  999. with Session(db.engine) as session:
  1000. account = session.query(Account).filter_by(email=email).first()
  1001. if not account:
  1002. TenantService.check_member_permission(tenant, inviter, None, "add")
  1003. name = email.split("@")[0]
  1004. account = cls.register(
  1005. email=email, name=name, language=language, status=AccountStatus.PENDING, is_setup=True
  1006. )
  1007. # Create new tenant member for invited tenant
  1008. TenantService.create_tenant_member(tenant, account, role)
  1009. TenantService.switch_tenant(account, tenant.id)
  1010. else:
  1011. TenantService.check_member_permission(tenant, inviter, account, "add")
  1012. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  1013. if not ta:
  1014. TenantService.create_tenant_member(tenant, account, role)
  1015. # Support resend invitation email when the account is pending status
  1016. if account.status != AccountStatus.PENDING.value:
  1017. raise AccountAlreadyInTenantError("Account already in tenant.")
  1018. token = cls.generate_invite_token(tenant, account)
  1019. # send email
  1020. send_invite_member_mail_task.delay(
  1021. language=account.interface_language,
  1022. to=email,
  1023. token=token,
  1024. inviter_name=inviter.name if inviter else "Dify",
  1025. workspace_name=tenant.name,
  1026. )
  1027. return token
  1028. @classmethod
  1029. def generate_invite_token(cls, tenant: Tenant, account: Account) -> str:
  1030. token = str(uuid.uuid4())
  1031. invitation_data = {
  1032. "account_id": account.id,
  1033. "email": account.email,
  1034. "workspace_id": tenant.id,
  1035. }
  1036. expiry_hours = dify_config.INVITE_EXPIRY_HOURS
  1037. redis_client.setex(cls._get_invitation_token_key(token), expiry_hours * 60 * 60, json.dumps(invitation_data))
  1038. return token
  1039. @classmethod
  1040. def is_valid_invite_token(cls, token: str) -> bool:
  1041. data = redis_client.get(cls._get_invitation_token_key(token))
  1042. return data is not None
  1043. @classmethod
  1044. def revoke_token(cls, workspace_id: str, email: str, token: str):
  1045. if workspace_id and email:
  1046. email_hash = sha256(email.encode()).hexdigest()
  1047. cache_key = "member_invite_token:{}, {}:{}".format(workspace_id, email_hash, token)
  1048. redis_client.delete(cache_key)
  1049. else:
  1050. redis_client.delete(cls._get_invitation_token_key(token))
  1051. @classmethod
  1052. def get_invitation_if_token_valid(
  1053. cls, workspace_id: Optional[str], email: str, token: str
  1054. ) -> Optional[dict[str, Any]]:
  1055. invitation_data = cls._get_invitation_by_token(token, workspace_id, email)
  1056. if not invitation_data:
  1057. return None
  1058. tenant = (
  1059. db.session.query(Tenant)
  1060. .filter(Tenant.id == invitation_data["workspace_id"], Tenant.status == "normal")
  1061. .first()
  1062. )
  1063. if not tenant:
  1064. return None
  1065. tenant_account = (
  1066. db.session.query(Account, TenantAccountJoin.role)
  1067. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  1068. .filter(Account.email == invitation_data["email"], TenantAccountJoin.tenant_id == tenant.id)
  1069. .first()
  1070. )
  1071. if not tenant_account:
  1072. return None
  1073. account = tenant_account[0]
  1074. if not account:
  1075. return None
  1076. if invitation_data["account_id"] != str(account.id):
  1077. return None
  1078. return {
  1079. "account": account,
  1080. "data": invitation_data,
  1081. "tenant": tenant,
  1082. }
  1083. @classmethod
  1084. def _get_invitation_by_token(
  1085. cls, token: str, workspace_id: Optional[str] = None, email: Optional[str] = None
  1086. ) -> Optional[dict[str, str]]:
  1087. if workspace_id is not None and email is not None:
  1088. email_hash = sha256(email.encode()).hexdigest()
  1089. cache_key = f"member_invite_token:{workspace_id}, {email_hash}:{token}"
  1090. account_id = redis_client.get(cache_key)
  1091. if not account_id:
  1092. return None
  1093. return {
  1094. "account_id": account_id.decode("utf-8"),
  1095. "email": email,
  1096. "workspace_id": workspace_id,
  1097. }
  1098. else:
  1099. data = redis_client.get(cls._get_invitation_token_key(token))
  1100. if not data:
  1101. return None
  1102. invitation: dict = json.loads(data)
  1103. return invitation
  1104. def _generate_refresh_token(length: int = 64):
  1105. token = secrets.token_hex(length)
  1106. return token