選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

account_service.py 40KB

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