Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

account_service.py 50KB

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