Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

account_service.py 40KB

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