Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

account_service.py 50KB

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