Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

account_service.py 50KB

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