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

account_service.py 50KB

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