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 49KB

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