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

account_service.py 50KB

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