Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

account_service.py 49KB

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