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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  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("Account %s linked %s account %s.", account.id, provider, open_id)
  278. except Exception as e:
  279. logging.exception("Failed to link %s account %s to Account %s", provider, open_id, 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_account_email(account: Account, email: str) -> Account:
  298. """Update account email"""
  299. account.email = email
  300. account_integrate = db.session.query(AccountIntegrate).filter_by(account_id=account.id).first()
  301. if account_integrate:
  302. db.session.delete(account_integrate)
  303. db.session.add(account)
  304. db.session.commit()
  305. return account
  306. @staticmethod
  307. def update_login_info(account: Account, *, ip_address: str) -> None:
  308. """Update last login time and ip"""
  309. account.last_login_at = naive_utc_now()
  310. account.last_login_ip = ip_address
  311. db.session.add(account)
  312. db.session.commit()
  313. @staticmethod
  314. def login(account: Account, *, ip_address: Optional[str] = None) -> TokenPair:
  315. if ip_address:
  316. AccountService.update_login_info(account=account, ip_address=ip_address)
  317. if account.status == AccountStatus.PENDING.value:
  318. account.status = AccountStatus.ACTIVE.value
  319. db.session.commit()
  320. access_token = AccountService.get_account_jwt_token(account=account)
  321. refresh_token = _generate_refresh_token()
  322. AccountService._store_refresh_token(refresh_token, account.id)
  323. return TokenPair(access_token=access_token, refresh_token=refresh_token)
  324. @staticmethod
  325. def logout(*, account: Account) -> None:
  326. refresh_token = redis_client.get(AccountService._get_account_refresh_token_key(account.id))
  327. if refresh_token:
  328. AccountService._delete_refresh_token(refresh_token.decode("utf-8"), account.id)
  329. @staticmethod
  330. def refresh_token(refresh_token: str) -> TokenPair:
  331. # Verify the refresh token
  332. account_id = redis_client.get(AccountService._get_refresh_token_key(refresh_token))
  333. if not account_id:
  334. raise ValueError("Invalid refresh token")
  335. account = AccountService.load_user(account_id.decode("utf-8"))
  336. if not account:
  337. raise ValueError("Invalid account")
  338. # Generate new access token and refresh token
  339. new_access_token = AccountService.get_account_jwt_token(account)
  340. new_refresh_token = _generate_refresh_token()
  341. AccountService._delete_refresh_token(refresh_token, account.id)
  342. AccountService._store_refresh_token(new_refresh_token, account.id)
  343. return TokenPair(access_token=new_access_token, refresh_token=new_refresh_token)
  344. @staticmethod
  345. def load_logged_in_account(*, account_id: str):
  346. return AccountService.load_user(account_id)
  347. @classmethod
  348. def send_reset_password_email(
  349. cls,
  350. account: Optional[Account] = None,
  351. email: Optional[str] = None,
  352. language: Optional[str] = "en-US",
  353. ):
  354. account_email = account.email if account else email
  355. if account_email is None:
  356. raise ValueError("Email must be provided.")
  357. if cls.reset_password_rate_limiter.is_rate_limited(account_email):
  358. from controllers.console.auth.error import PasswordResetRateLimitExceededError
  359. raise PasswordResetRateLimitExceededError()
  360. code, token = cls.generate_reset_password_token(account_email, account)
  361. send_reset_password_mail_task.delay(
  362. language=language,
  363. to=account_email,
  364. code=code,
  365. )
  366. cls.reset_password_rate_limiter.increment_rate_limit(account_email)
  367. return token
  368. @classmethod
  369. def send_change_email_email(
  370. cls,
  371. account: Optional[Account] = None,
  372. email: Optional[str] = None,
  373. old_email: Optional[str] = None,
  374. language: Optional[str] = "en-US",
  375. phase: Optional[str] = None,
  376. ):
  377. account_email = account.email if account else email
  378. if account_email is None:
  379. raise ValueError("Email must be provided.")
  380. if cls.change_email_rate_limiter.is_rate_limited(account_email):
  381. from controllers.console.auth.error import EmailChangeRateLimitExceededError
  382. raise EmailChangeRateLimitExceededError()
  383. code, token = cls.generate_change_email_token(account_email, account, old_email=old_email)
  384. send_change_mail_task.delay(
  385. language=language,
  386. to=account_email,
  387. code=code,
  388. phase=phase,
  389. )
  390. cls.change_email_rate_limiter.increment_rate_limit(account_email)
  391. return token
  392. @classmethod
  393. def send_change_email_completed_notify_email(
  394. cls,
  395. account: Optional[Account] = None,
  396. email: Optional[str] = None,
  397. language: Optional[str] = "en-US",
  398. ):
  399. account_email = account.email if account else email
  400. if account_email is None:
  401. raise ValueError("Email must be provided.")
  402. send_change_mail_completed_notification_task.delay(
  403. language=language,
  404. to=account_email,
  405. )
  406. @classmethod
  407. def send_owner_transfer_email(
  408. cls,
  409. account: Optional[Account] = None,
  410. email: Optional[str] = None,
  411. language: Optional[str] = "en-US",
  412. workspace_name: Optional[str] = "",
  413. ):
  414. account_email = account.email if account else email
  415. if account_email is None:
  416. raise ValueError("Email must be provided.")
  417. if cls.owner_transfer_rate_limiter.is_rate_limited(account_email):
  418. from controllers.console.auth.error import OwnerTransferRateLimitExceededError
  419. raise OwnerTransferRateLimitExceededError()
  420. code, token = cls.generate_owner_transfer_token(account_email, account)
  421. send_owner_transfer_confirm_task.delay(
  422. language=language,
  423. to=account_email,
  424. code=code,
  425. workspace=workspace_name,
  426. )
  427. cls.owner_transfer_rate_limiter.increment_rate_limit(account_email)
  428. return token
  429. @classmethod
  430. def send_old_owner_transfer_notify_email(
  431. cls,
  432. account: Optional[Account] = None,
  433. email: Optional[str] = None,
  434. language: Optional[str] = "en-US",
  435. workspace_name: Optional[str] = "",
  436. new_owner_email: Optional[str] = "",
  437. ):
  438. account_email = account.email if account else email
  439. if account_email is None:
  440. raise ValueError("Email must be provided.")
  441. send_old_owner_transfer_notify_email_task.delay(
  442. language=language,
  443. to=account_email,
  444. workspace=workspace_name,
  445. new_owner_email=new_owner_email,
  446. )
  447. @classmethod
  448. def send_new_owner_transfer_notify_email(
  449. cls,
  450. account: Optional[Account] = None,
  451. email: Optional[str] = None,
  452. language: Optional[str] = "en-US",
  453. workspace_name: Optional[str] = "",
  454. ):
  455. account_email = account.email if account else email
  456. if account_email is None:
  457. raise ValueError("Email must be provided.")
  458. send_new_owner_transfer_notify_email_task.delay(
  459. language=language,
  460. to=account_email,
  461. workspace=workspace_name,
  462. )
  463. @classmethod
  464. def generate_reset_password_token(
  465. cls,
  466. email: str,
  467. account: Optional[Account] = None,
  468. code: Optional[str] = None,
  469. additional_data: dict[str, Any] = {},
  470. ):
  471. if not code:
  472. code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])
  473. additional_data["code"] = code
  474. token = TokenManager.generate_token(
  475. account=account, email=email, token_type="reset_password", additional_data=additional_data
  476. )
  477. return code, token
  478. @classmethod
  479. def generate_change_email_token(
  480. cls,
  481. email: str,
  482. account: Optional[Account] = None,
  483. code: Optional[str] = None,
  484. old_email: Optional[str] = None,
  485. additional_data: dict[str, Any] = {},
  486. ):
  487. if not code:
  488. code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])
  489. additional_data["code"] = code
  490. additional_data["old_email"] = old_email
  491. token = TokenManager.generate_token(
  492. account=account, email=email, token_type="change_email", additional_data=additional_data
  493. )
  494. return code, token
  495. @classmethod
  496. def generate_owner_transfer_token(
  497. cls,
  498. email: str,
  499. account: Optional[Account] = None,
  500. code: Optional[str] = None,
  501. additional_data: dict[str, Any] = {},
  502. ):
  503. if not code:
  504. code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])
  505. additional_data["code"] = code
  506. token = TokenManager.generate_token(
  507. account=account, email=email, token_type="owner_transfer", additional_data=additional_data
  508. )
  509. return code, token
  510. @classmethod
  511. def revoke_reset_password_token(cls, token: str):
  512. TokenManager.revoke_token(token, "reset_password")
  513. @classmethod
  514. def revoke_change_email_token(cls, token: str):
  515. TokenManager.revoke_token(token, "change_email")
  516. @classmethod
  517. def revoke_owner_transfer_token(cls, token: str):
  518. TokenManager.revoke_token(token, "owner_transfer")
  519. @classmethod
  520. def get_reset_password_data(cls, token: str) -> Optional[dict[str, Any]]:
  521. return TokenManager.get_token_data(token, "reset_password")
  522. @classmethod
  523. def get_change_email_data(cls, token: str) -> Optional[dict[str, Any]]:
  524. return TokenManager.get_token_data(token, "change_email")
  525. @classmethod
  526. def get_owner_transfer_data(cls, token: str) -> Optional[dict[str, Any]]:
  527. return TokenManager.get_token_data(token, "owner_transfer")
  528. @classmethod
  529. def send_email_code_login_email(
  530. cls, account: Optional[Account] = None, email: Optional[str] = None, language: Optional[str] = "en-US"
  531. ):
  532. email = account.email if account else email
  533. if email is None:
  534. raise ValueError("Email must be provided.")
  535. if cls.email_code_login_rate_limiter.is_rate_limited(email):
  536. from controllers.console.auth.error import EmailCodeLoginRateLimitExceededError
  537. raise EmailCodeLoginRateLimitExceededError()
  538. code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])
  539. token = TokenManager.generate_token(
  540. account=account, email=email, token_type="email_code_login", additional_data={"code": code}
  541. )
  542. send_email_code_login_mail_task.delay(
  543. language=language,
  544. to=account.email if account else email,
  545. code=code,
  546. )
  547. cls.email_code_login_rate_limiter.increment_rate_limit(email)
  548. return token
  549. @classmethod
  550. def get_email_code_login_data(cls, token: str) -> Optional[dict[str, Any]]:
  551. return TokenManager.get_token_data(token, "email_code_login")
  552. @classmethod
  553. def revoke_email_code_login_token(cls, token: str):
  554. TokenManager.revoke_token(token, "email_code_login")
  555. @classmethod
  556. def get_user_through_email(cls, email: str):
  557. if dify_config.BILLING_ENABLED and BillingService.is_email_in_freeze(email):
  558. raise AccountRegisterError(
  559. description=(
  560. "This email account has been deleted within the past "
  561. "30 days and is temporarily unavailable for new account registration"
  562. )
  563. )
  564. account = db.session.query(Account).where(Account.email == email).first()
  565. if not account:
  566. return None
  567. if account.status == AccountStatus.BANNED.value:
  568. raise Unauthorized("Account is banned.")
  569. return account
  570. @classmethod
  571. def is_account_in_freeze(cls, email: str) -> bool:
  572. if dify_config.BILLING_ENABLED and BillingService.is_email_in_freeze(email):
  573. return True
  574. return False
  575. @staticmethod
  576. @redis_fallback(default_return=None)
  577. def add_login_error_rate_limit(email: str) -> None:
  578. key = f"login_error_rate_limit:{email}"
  579. count = redis_client.get(key)
  580. if count is None:
  581. count = 0
  582. count = int(count) + 1
  583. redis_client.setex(key, dify_config.LOGIN_LOCKOUT_DURATION, count)
  584. @staticmethod
  585. @redis_fallback(default_return=False)
  586. def is_login_error_rate_limit(email: str) -> bool:
  587. key = f"login_error_rate_limit:{email}"
  588. count = redis_client.get(key)
  589. if count is None:
  590. return False
  591. count = int(count)
  592. if count > AccountService.LOGIN_MAX_ERROR_LIMITS:
  593. return True
  594. return False
  595. @staticmethod
  596. @redis_fallback(default_return=None)
  597. def reset_login_error_rate_limit(email: str):
  598. key = f"login_error_rate_limit:{email}"
  599. redis_client.delete(key)
  600. @staticmethod
  601. @redis_fallback(default_return=None)
  602. def add_forgot_password_error_rate_limit(email: str) -> None:
  603. key = f"forgot_password_error_rate_limit:{email}"
  604. count = redis_client.get(key)
  605. if count is None:
  606. count = 0
  607. count = int(count) + 1
  608. redis_client.setex(key, dify_config.FORGOT_PASSWORD_LOCKOUT_DURATION, count)
  609. @staticmethod
  610. @redis_fallback(default_return=False)
  611. def is_forgot_password_error_rate_limit(email: str) -> bool:
  612. key = f"forgot_password_error_rate_limit:{email}"
  613. count = redis_client.get(key)
  614. if count is None:
  615. return False
  616. count = int(count)
  617. if count > AccountService.FORGOT_PASSWORD_MAX_ERROR_LIMITS:
  618. return True
  619. return False
  620. @staticmethod
  621. @redis_fallback(default_return=None)
  622. def reset_forgot_password_error_rate_limit(email: str):
  623. key = f"forgot_password_error_rate_limit:{email}"
  624. redis_client.delete(key)
  625. @staticmethod
  626. @redis_fallback(default_return=None)
  627. def add_change_email_error_rate_limit(email: str) -> None:
  628. key = f"change_email_error_rate_limit:{email}"
  629. count = redis_client.get(key)
  630. if count is None:
  631. count = 0
  632. count = int(count) + 1
  633. redis_client.setex(key, dify_config.CHANGE_EMAIL_LOCKOUT_DURATION, count)
  634. @staticmethod
  635. @redis_fallback(default_return=False)
  636. def is_change_email_error_rate_limit(email: str) -> bool:
  637. key = f"change_email_error_rate_limit:{email}"
  638. count = redis_client.get(key)
  639. if count is None:
  640. return False
  641. count = int(count)
  642. if count > AccountService.CHANGE_EMAIL_MAX_ERROR_LIMITS:
  643. return True
  644. return False
  645. @staticmethod
  646. @redis_fallback(default_return=None)
  647. def reset_change_email_error_rate_limit(email: str):
  648. key = f"change_email_error_rate_limit:{email}"
  649. redis_client.delete(key)
  650. @staticmethod
  651. @redis_fallback(default_return=None)
  652. def add_owner_transfer_error_rate_limit(email: str) -> None:
  653. key = f"owner_transfer_error_rate_limit:{email}"
  654. count = redis_client.get(key)
  655. if count is None:
  656. count = 0
  657. count = int(count) + 1
  658. redis_client.setex(key, dify_config.OWNER_TRANSFER_LOCKOUT_DURATION, count)
  659. @staticmethod
  660. @redis_fallback(default_return=False)
  661. def is_owner_transfer_error_rate_limit(email: str) -> bool:
  662. key = f"owner_transfer_error_rate_limit:{email}"
  663. count = redis_client.get(key)
  664. if count is None:
  665. return False
  666. count = int(count)
  667. if count > AccountService.OWNER_TRANSFER_MAX_ERROR_LIMITS:
  668. return True
  669. return False
  670. @staticmethod
  671. @redis_fallback(default_return=None)
  672. def reset_owner_transfer_error_rate_limit(email: str):
  673. key = f"owner_transfer_error_rate_limit:{email}"
  674. redis_client.delete(key)
  675. @staticmethod
  676. @redis_fallback(default_return=False)
  677. def is_email_send_ip_limit(ip_address: str):
  678. minute_key = f"email_send_ip_limit_minute:{ip_address}"
  679. freeze_key = f"email_send_ip_limit_freeze:{ip_address}"
  680. hour_limit_key = f"email_send_ip_limit_hour:{ip_address}"
  681. # check ip is frozen
  682. if redis_client.get(freeze_key):
  683. return True
  684. # check current minute count
  685. current_minute_count = redis_client.get(minute_key)
  686. if current_minute_count is None:
  687. current_minute_count = 0
  688. current_minute_count = int(current_minute_count)
  689. # check current hour count
  690. if current_minute_count > dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE:
  691. hour_limit_count = redis_client.get(hour_limit_key)
  692. if hour_limit_count is None:
  693. hour_limit_count = 0
  694. hour_limit_count = int(hour_limit_count)
  695. if hour_limit_count >= 1:
  696. redis_client.setex(freeze_key, 60 * 60, 1)
  697. return True
  698. else:
  699. redis_client.setex(hour_limit_key, 60 * 10, hour_limit_count + 1) # first time limit 10 minutes
  700. # add hour limit count
  701. redis_client.incr(hour_limit_key)
  702. redis_client.expire(hour_limit_key, 60 * 60)
  703. return True
  704. redis_client.setex(minute_key, 60, current_minute_count + 1)
  705. redis_client.expire(minute_key, 60)
  706. return False
  707. @staticmethod
  708. def check_email_unique(email: str) -> bool:
  709. return db.session.query(Account).filter_by(email=email).first() is None
  710. class TenantService:
  711. @staticmethod
  712. def create_tenant(name: str, is_setup: Optional[bool] = False, is_from_dashboard: Optional[bool] = False) -> Tenant:
  713. """Create tenant"""
  714. if (
  715. not FeatureService.get_system_features().is_allow_create_workspace
  716. and not is_setup
  717. and not is_from_dashboard
  718. ):
  719. from controllers.console.error import NotAllowedCreateWorkspace
  720. raise NotAllowedCreateWorkspace()
  721. tenant = Tenant(name=name)
  722. db.session.add(tenant)
  723. db.session.commit()
  724. plugin_upgrade_strategy = TenantPluginAutoUpgradeStrategy(
  725. tenant_id=tenant.id,
  726. strategy_setting=TenantPluginAutoUpgradeStrategy.StrategySetting.FIX_ONLY,
  727. upgrade_time_of_day=0,
  728. upgrade_mode=TenantPluginAutoUpgradeStrategy.UpgradeMode.EXCLUDE,
  729. exclude_plugins=[],
  730. include_plugins=[],
  731. )
  732. db.session.add(plugin_upgrade_strategy)
  733. db.session.commit()
  734. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  735. db.session.commit()
  736. return tenant
  737. @staticmethod
  738. def create_owner_tenant_if_not_exist(
  739. account: Account, name: Optional[str] = None, is_setup: Optional[bool] = False
  740. ):
  741. """Check if user have a workspace or not"""
  742. available_ta = (
  743. db.session.query(TenantAccountJoin)
  744. .filter_by(account_id=account.id)
  745. .order_by(TenantAccountJoin.id.asc())
  746. .first()
  747. )
  748. if available_ta:
  749. return
  750. """Create owner tenant if not exist"""
  751. if not FeatureService.get_system_features().is_allow_create_workspace and not is_setup:
  752. raise WorkSpaceNotAllowedCreateError()
  753. workspaces = FeatureService.get_system_features().license.workspaces
  754. if not workspaces.is_available():
  755. raise WorkspacesLimitExceededError()
  756. if name:
  757. tenant = TenantService.create_tenant(name=name, is_setup=is_setup)
  758. else:
  759. tenant = TenantService.create_tenant(name=f"{account.name}'s Workspace", is_setup=is_setup)
  760. TenantService.create_tenant_member(tenant, account, role="owner")
  761. account.current_tenant = tenant
  762. db.session.commit()
  763. tenant_was_created.send(tenant)
  764. @staticmethod
  765. def create_tenant_member(tenant: Tenant, account: Account, role: str = "normal") -> TenantAccountJoin:
  766. """Create tenant member"""
  767. if role == TenantAccountRole.OWNER.value:
  768. if TenantService.has_roles(tenant, [TenantAccountRole.OWNER]):
  769. logging.error("Tenant %s has already an owner.", tenant.id)
  770. raise Exception("Tenant already has an owner.")
  771. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  772. if ta:
  773. ta.role = role
  774. else:
  775. ta = TenantAccountJoin(tenant_id=tenant.id, account_id=account.id, role=role)
  776. db.session.add(ta)
  777. db.session.commit()
  778. return ta
  779. @staticmethod
  780. def get_join_tenants(account: Account) -> list[Tenant]:
  781. """Get account join tenants"""
  782. return (
  783. db.session.query(Tenant)
  784. .join(TenantAccountJoin, Tenant.id == TenantAccountJoin.tenant_id)
  785. .where(TenantAccountJoin.account_id == account.id, Tenant.status == TenantStatus.NORMAL)
  786. .all()
  787. )
  788. @staticmethod
  789. def get_current_tenant_by_account(account: Account):
  790. """Get tenant by account and add the role"""
  791. tenant = account.current_tenant
  792. if not tenant:
  793. raise TenantNotFoundError("Tenant not found.")
  794. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  795. if ta:
  796. tenant.role = ta.role
  797. else:
  798. raise TenantNotFoundError("Tenant not found for the account.")
  799. return tenant
  800. @staticmethod
  801. def switch_tenant(account: Account, tenant_id: Optional[str] = None) -> None:
  802. """Switch the current workspace for the account"""
  803. # Ensure tenant_id is provided
  804. if tenant_id is None:
  805. raise ValueError("Tenant ID must be provided.")
  806. tenant_account_join = (
  807. db.session.query(TenantAccountJoin)
  808. .join(Tenant, TenantAccountJoin.tenant_id == Tenant.id)
  809. .where(
  810. TenantAccountJoin.account_id == account.id,
  811. TenantAccountJoin.tenant_id == tenant_id,
  812. Tenant.status == TenantStatus.NORMAL,
  813. )
  814. .first()
  815. )
  816. if not tenant_account_join:
  817. raise AccountNotLinkTenantError("Tenant not found or account is not a member of the tenant.")
  818. else:
  819. db.session.query(TenantAccountJoin).where(
  820. TenantAccountJoin.account_id == account.id, TenantAccountJoin.tenant_id != tenant_id
  821. ).update({"current": False})
  822. tenant_account_join.current = True
  823. # Set the current tenant for the account
  824. account.set_tenant_id(tenant_account_join.tenant_id)
  825. db.session.commit()
  826. @staticmethod
  827. def get_tenant_members(tenant: Tenant) -> list[Account]:
  828. """Get tenant 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. )
  835. # Initialize an empty list to store the updated accounts
  836. updated_accounts = []
  837. for account, role in query:
  838. account.role = role
  839. updated_accounts.append(account)
  840. return updated_accounts
  841. @staticmethod
  842. def get_dataset_operator_members(tenant: Tenant) -> list[Account]:
  843. """Get dataset admin members"""
  844. query = (
  845. db.session.query(Account, TenantAccountJoin.role)
  846. .select_from(Account)
  847. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  848. .where(TenantAccountJoin.tenant_id == tenant.id)
  849. .where(TenantAccountJoin.role == "dataset_operator")
  850. )
  851. # Initialize an empty list to store the updated accounts
  852. updated_accounts = []
  853. for account, role in query:
  854. account.role = role
  855. updated_accounts.append(account)
  856. return updated_accounts
  857. @staticmethod
  858. def has_roles(tenant: Tenant, roles: list[TenantAccountRole]) -> bool:
  859. """Check if user has any of the given roles for a tenant"""
  860. if not all(isinstance(role, TenantAccountRole) for role in roles):
  861. raise ValueError("all roles must be TenantAccountRole")
  862. return (
  863. db.session.query(TenantAccountJoin)
  864. .where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.role.in_([role.value for role in roles]))
  865. .first()
  866. is not None
  867. )
  868. @staticmethod
  869. def get_user_role(account: Account, tenant: Tenant) -> Optional[TenantAccountRole]:
  870. """Get the role of the current account for a given tenant"""
  871. join = (
  872. db.session.query(TenantAccountJoin)
  873. .where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == account.id)
  874. .first()
  875. )
  876. return TenantAccountRole(join.role) if join else None
  877. @staticmethod
  878. def get_tenant_count() -> int:
  879. """Get tenant count"""
  880. return cast(int, db.session.query(func.count(Tenant.id)).scalar())
  881. @staticmethod
  882. def check_member_permission(tenant: Tenant, operator: Account, member: Account | None, action: str) -> None:
  883. """Check member permission"""
  884. perms = {
  885. "add": [TenantAccountRole.OWNER, TenantAccountRole.ADMIN],
  886. "remove": [TenantAccountRole.OWNER],
  887. "update": [TenantAccountRole.OWNER],
  888. }
  889. if action not in {"add", "remove", "update"}:
  890. raise InvalidActionError("Invalid action.")
  891. if member:
  892. if operator.id == member.id:
  893. raise CannotOperateSelfError("Cannot operate self.")
  894. ta_operator = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=operator.id).first()
  895. if not ta_operator or ta_operator.role not in perms[action]:
  896. raise NoPermissionError(f"No permission to {action} member.")
  897. @staticmethod
  898. def remove_member_from_tenant(tenant: Tenant, account: Account, operator: Account) -> None:
  899. """Remove member from tenant"""
  900. if operator.id == account.id:
  901. raise CannotOperateSelfError("Cannot operate self.")
  902. TenantService.check_member_permission(tenant, operator, account, "remove")
  903. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  904. if not ta:
  905. raise MemberNotInTenantError("Member not in tenant.")
  906. db.session.delete(ta)
  907. db.session.commit()
  908. @staticmethod
  909. def update_member_role(tenant: Tenant, member: Account, new_role: str, operator: Account) -> None:
  910. """Update member role"""
  911. TenantService.check_member_permission(tenant, operator, member, "update")
  912. target_member_join = (
  913. db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=member.id).first()
  914. )
  915. if not target_member_join:
  916. raise MemberNotInTenantError("Member not in tenant.")
  917. if target_member_join.role == new_role:
  918. raise RoleAlreadyAssignedError("The provided role is already assigned to the member.")
  919. if new_role == "owner":
  920. # Find the current owner and change their role to 'admin'
  921. current_owner_join = (
  922. db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, role="owner").first()
  923. )
  924. if current_owner_join:
  925. current_owner_join.role = "admin"
  926. # Update the role of the target member
  927. target_member_join.role = new_role
  928. db.session.commit()
  929. @staticmethod
  930. def get_custom_config(tenant_id: str) -> dict:
  931. tenant = db.get_or_404(Tenant, tenant_id)
  932. return cast(dict, tenant.custom_config_dict)
  933. @staticmethod
  934. def is_owner(account: Account, tenant: Tenant) -> bool:
  935. return TenantService.get_user_role(account, tenant) == TenantAccountRole.OWNER
  936. @staticmethod
  937. def is_member(account: Account, tenant: Tenant) -> bool:
  938. """Check if the account is a member of the tenant"""
  939. return TenantService.get_user_role(account, tenant) is not None
  940. class RegisterService:
  941. @classmethod
  942. def _get_invitation_token_key(cls, token: str) -> str:
  943. return f"member_invite:token:{token}"
  944. @classmethod
  945. def setup(cls, email: str, name: str, password: str, ip_address: str) -> None:
  946. """
  947. Setup dify
  948. :param email: email
  949. :param name: username
  950. :param password: password
  951. :param ip_address: ip address
  952. """
  953. try:
  954. # Register
  955. account = AccountService.create_account(
  956. email=email,
  957. name=name,
  958. interface_language=languages[0],
  959. password=password,
  960. is_setup=True,
  961. )
  962. account.last_login_ip = ip_address
  963. account.initialized_at = naive_utc_now()
  964. TenantService.create_owner_tenant_if_not_exist(account=account, is_setup=True)
  965. dify_setup = DifySetup(version=dify_config.project.version)
  966. db.session.add(dify_setup)
  967. db.session.commit()
  968. except Exception as e:
  969. db.session.query(DifySetup).delete()
  970. db.session.query(TenantAccountJoin).delete()
  971. db.session.query(Account).delete()
  972. db.session.query(Tenant).delete()
  973. db.session.commit()
  974. logging.exception("Setup account failed, email: %s, name: %s", email, name)
  975. raise ValueError(f"Setup failed: {e}")
  976. @classmethod
  977. def register(
  978. cls,
  979. email,
  980. name,
  981. password: Optional[str] = None,
  982. open_id: Optional[str] = None,
  983. provider: Optional[str] = None,
  984. language: Optional[str] = None,
  985. status: Optional[AccountStatus] = None,
  986. is_setup: Optional[bool] = False,
  987. create_workspace_required: Optional[bool] = True,
  988. ) -> Account:
  989. db.session.begin_nested()
  990. """Register account"""
  991. try:
  992. account = AccountService.create_account(
  993. email=email,
  994. name=name,
  995. interface_language=language or languages[0],
  996. password=password,
  997. is_setup=is_setup,
  998. )
  999. account.status = AccountStatus.ACTIVE.value if not status else status.value
  1000. account.initialized_at = naive_utc_now()
  1001. if open_id is not None and provider is not None:
  1002. AccountService.link_account_integrate(provider, open_id, account)
  1003. if (
  1004. FeatureService.get_system_features().is_allow_create_workspace
  1005. and create_workspace_required
  1006. and FeatureService.get_system_features().license.workspaces.is_available()
  1007. ):
  1008. tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  1009. TenantService.create_tenant_member(tenant, account, role="owner")
  1010. account.current_tenant = tenant
  1011. tenant_was_created.send(tenant)
  1012. db.session.commit()
  1013. except WorkSpaceNotAllowedCreateError:
  1014. db.session.rollback()
  1015. logging.exception("Register failed")
  1016. raise AccountRegisterError("Workspace is not allowed to create.")
  1017. except AccountRegisterError as are:
  1018. db.session.rollback()
  1019. logging.exception("Register failed")
  1020. raise are
  1021. except Exception as e:
  1022. db.session.rollback()
  1023. logging.exception("Register failed")
  1024. raise AccountRegisterError(f"Registration failed: {e}") from e
  1025. return account
  1026. @classmethod
  1027. def invite_new_member(
  1028. cls, tenant: Tenant, email: str, language: str, role: str = "normal", inviter: Account | None = None
  1029. ) -> str:
  1030. if not inviter:
  1031. raise ValueError("Inviter is required")
  1032. """Invite new member"""
  1033. with Session(db.engine) as session:
  1034. account = session.query(Account).filter_by(email=email).first()
  1035. if not account:
  1036. TenantService.check_member_permission(tenant, inviter, None, "add")
  1037. name = email.split("@")[0]
  1038. account = cls.register(
  1039. email=email, name=name, language=language, status=AccountStatus.PENDING, is_setup=True
  1040. )
  1041. # Create new tenant member for invited tenant
  1042. TenantService.create_tenant_member(tenant, account, role)
  1043. TenantService.switch_tenant(account, tenant.id)
  1044. else:
  1045. TenantService.check_member_permission(tenant, inviter, account, "add")
  1046. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  1047. if not ta:
  1048. TenantService.create_tenant_member(tenant, account, role)
  1049. # Support resend invitation email when the account is pending status
  1050. if account.status != AccountStatus.PENDING.value:
  1051. raise AccountAlreadyInTenantError("Account already in tenant.")
  1052. token = cls.generate_invite_token(tenant, account)
  1053. # send email
  1054. send_invite_member_mail_task.delay(
  1055. language=account.interface_language,
  1056. to=email,
  1057. token=token,
  1058. inviter_name=inviter.name if inviter else "Dify",
  1059. workspace_name=tenant.name,
  1060. )
  1061. return token
  1062. @classmethod
  1063. def generate_invite_token(cls, tenant: Tenant, account: Account) -> str:
  1064. token = str(uuid.uuid4())
  1065. invitation_data = {
  1066. "account_id": account.id,
  1067. "email": account.email,
  1068. "workspace_id": tenant.id,
  1069. }
  1070. expiry_hours = dify_config.INVITE_EXPIRY_HOURS
  1071. redis_client.setex(cls._get_invitation_token_key(token), expiry_hours * 60 * 60, json.dumps(invitation_data))
  1072. return token
  1073. @classmethod
  1074. def is_valid_invite_token(cls, token: str) -> bool:
  1075. data = redis_client.get(cls._get_invitation_token_key(token))
  1076. return data is not None
  1077. @classmethod
  1078. def revoke_token(cls, workspace_id: str, email: str, token: str):
  1079. if workspace_id and email:
  1080. email_hash = sha256(email.encode()).hexdigest()
  1081. cache_key = f"member_invite_token:{workspace_id}, {email_hash}:{token}"
  1082. redis_client.delete(cache_key)
  1083. else:
  1084. redis_client.delete(cls._get_invitation_token_key(token))
  1085. @classmethod
  1086. def get_invitation_if_token_valid(
  1087. cls, workspace_id: Optional[str], email: str, token: str
  1088. ) -> Optional[dict[str, Any]]:
  1089. invitation_data = cls._get_invitation_by_token(token, workspace_id, email)
  1090. if not invitation_data:
  1091. return None
  1092. tenant = (
  1093. db.session.query(Tenant)
  1094. .where(Tenant.id == invitation_data["workspace_id"], Tenant.status == "normal")
  1095. .first()
  1096. )
  1097. if not tenant:
  1098. return None
  1099. tenant_account = (
  1100. db.session.query(Account, TenantAccountJoin.role)
  1101. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  1102. .where(Account.email == invitation_data["email"], TenantAccountJoin.tenant_id == tenant.id)
  1103. .first()
  1104. )
  1105. if not tenant_account:
  1106. return None
  1107. account = tenant_account[0]
  1108. if not account:
  1109. return None
  1110. if invitation_data["account_id"] != str(account.id):
  1111. return None
  1112. return {
  1113. "account": account,
  1114. "data": invitation_data,
  1115. "tenant": tenant,
  1116. }
  1117. @classmethod
  1118. def _get_invitation_by_token(
  1119. cls, token: str, workspace_id: Optional[str] = None, email: Optional[str] = None
  1120. ) -> Optional[dict[str, str]]:
  1121. if workspace_id is not None and email is not None:
  1122. email_hash = sha256(email.encode()).hexdigest()
  1123. cache_key = f"member_invite_token:{workspace_id}, {email_hash}:{token}"
  1124. account_id = redis_client.get(cache_key)
  1125. if not account_id:
  1126. return None
  1127. return {
  1128. "account_id": account_id.decode("utf-8"),
  1129. "email": email,
  1130. "workspace_id": workspace_id,
  1131. }
  1132. else:
  1133. data = redis_client.get(cls._get_invitation_token_key(token))
  1134. if not data:
  1135. return None
  1136. invitation: dict = json.loads(data)
  1137. return invitation
  1138. def _generate_refresh_token(length: int = 64):
  1139. token = secrets.token_hex(length)
  1140. return token