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

account_service.py 40KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  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
  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. def add_login_error_rate_limit(email: str) -> None:
  408. key = f"login_error_rate_limit:{email}"
  409. count = redis_client.get(key)
  410. if count is None:
  411. count = 0
  412. count = int(count) + 1
  413. redis_client.setex(key, dify_config.LOGIN_LOCKOUT_DURATION, count)
  414. @staticmethod
  415. def is_login_error_rate_limit(email: str) -> bool:
  416. key = f"login_error_rate_limit:{email}"
  417. count = redis_client.get(key)
  418. if count is None:
  419. return False
  420. count = int(count)
  421. if count > AccountService.LOGIN_MAX_ERROR_LIMITS:
  422. return True
  423. return False
  424. @staticmethod
  425. def reset_login_error_rate_limit(email: str):
  426. key = f"login_error_rate_limit:{email}"
  427. redis_client.delete(key)
  428. @staticmethod
  429. def add_forgot_password_error_rate_limit(email: str) -> None:
  430. key = f"forgot_password_error_rate_limit:{email}"
  431. count = redis_client.get(key)
  432. if count is None:
  433. count = 0
  434. count = int(count) + 1
  435. redis_client.setex(key, dify_config.FORGOT_PASSWORD_LOCKOUT_DURATION, count)
  436. @staticmethod
  437. def is_forgot_password_error_rate_limit(email: str) -> bool:
  438. key = f"forgot_password_error_rate_limit:{email}"
  439. count = redis_client.get(key)
  440. if count is None:
  441. return False
  442. count = int(count)
  443. if count > AccountService.FORGOT_PASSWORD_MAX_ERROR_LIMITS:
  444. return True
  445. return False
  446. @staticmethod
  447. def reset_forgot_password_error_rate_limit(email: str):
  448. key = f"forgot_password_error_rate_limit:{email}"
  449. redis_client.delete(key)
  450. @staticmethod
  451. def is_email_send_ip_limit(ip_address: str):
  452. minute_key = f"email_send_ip_limit_minute:{ip_address}"
  453. freeze_key = f"email_send_ip_limit_freeze:{ip_address}"
  454. hour_limit_key = f"email_send_ip_limit_hour:{ip_address}"
  455. # check ip is frozen
  456. if redis_client.get(freeze_key):
  457. return True
  458. # check current minute count
  459. current_minute_count = redis_client.get(minute_key)
  460. if current_minute_count is None:
  461. current_minute_count = 0
  462. current_minute_count = int(current_minute_count)
  463. # check current hour count
  464. if current_minute_count > dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE:
  465. hour_limit_count = redis_client.get(hour_limit_key)
  466. if hour_limit_count is None:
  467. hour_limit_count = 0
  468. hour_limit_count = int(hour_limit_count)
  469. if hour_limit_count >= 1:
  470. redis_client.setex(freeze_key, 60 * 60, 1)
  471. return True
  472. else:
  473. redis_client.setex(hour_limit_key, 60 * 10, hour_limit_count + 1) # first time limit 10 minutes
  474. # add hour limit count
  475. redis_client.incr(hour_limit_key)
  476. redis_client.expire(hour_limit_key, 60 * 60)
  477. return True
  478. redis_client.setex(minute_key, 60, current_minute_count + 1)
  479. redis_client.expire(minute_key, 60)
  480. return False
  481. class TenantService:
  482. @staticmethod
  483. def create_tenant(name: str, is_setup: Optional[bool] = False, is_from_dashboard: Optional[bool] = False) -> Tenant:
  484. """Create tenant"""
  485. if (
  486. not FeatureService.get_system_features().is_allow_create_workspace
  487. and not is_setup
  488. and not is_from_dashboard
  489. ):
  490. from controllers.console.error import NotAllowedCreateWorkspace
  491. raise NotAllowedCreateWorkspace()
  492. tenant = Tenant(name=name)
  493. db.session.add(tenant)
  494. db.session.commit()
  495. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  496. db.session.commit()
  497. return tenant
  498. @staticmethod
  499. def create_owner_tenant_if_not_exist(
  500. account: Account, name: Optional[str] = None, is_setup: Optional[bool] = False
  501. ):
  502. """Check if user have a workspace or not"""
  503. available_ta = (
  504. db.session.query(TenantAccountJoin)
  505. .filter_by(account_id=account.id)
  506. .order_by(TenantAccountJoin.id.asc())
  507. .first()
  508. )
  509. if available_ta:
  510. return
  511. """Create owner tenant if not exist"""
  512. if not FeatureService.get_system_features().is_allow_create_workspace and not is_setup:
  513. raise WorkSpaceNotAllowedCreateError()
  514. workspaces = FeatureService.get_system_features().license.workspaces
  515. if not workspaces.is_available():
  516. raise WorkspacesLimitExceededError()
  517. if name:
  518. tenant = TenantService.create_tenant(name=name, is_setup=is_setup)
  519. else:
  520. tenant = TenantService.create_tenant(name=f"{account.name}'s Workspace", is_setup=is_setup)
  521. TenantService.create_tenant_member(tenant, account, role="owner")
  522. account.current_tenant = tenant
  523. db.session.commit()
  524. tenant_was_created.send(tenant)
  525. @staticmethod
  526. def create_tenant_member(tenant: Tenant, account: Account, role: str = "normal") -> TenantAccountJoin:
  527. """Create tenant member"""
  528. if role == TenantAccountRole.OWNER.value:
  529. if TenantService.has_roles(tenant, [TenantAccountRole.OWNER]):
  530. logging.error(f"Tenant {tenant.id} has already an owner.")
  531. raise Exception("Tenant already has an owner.")
  532. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  533. if ta:
  534. ta.role = role
  535. else:
  536. ta = TenantAccountJoin(tenant_id=tenant.id, account_id=account.id, role=role)
  537. db.session.add(ta)
  538. db.session.commit()
  539. return ta
  540. @staticmethod
  541. def get_join_tenants(account: Account) -> list[Tenant]:
  542. """Get account join tenants"""
  543. return (
  544. db.session.query(Tenant)
  545. .join(TenantAccountJoin, Tenant.id == TenantAccountJoin.tenant_id)
  546. .filter(TenantAccountJoin.account_id == account.id, Tenant.status == TenantStatus.NORMAL)
  547. .all()
  548. )
  549. @staticmethod
  550. def get_current_tenant_by_account(account: Account):
  551. """Get tenant by account and add the role"""
  552. tenant = account.current_tenant
  553. if not tenant:
  554. raise TenantNotFoundError("Tenant not found.")
  555. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  556. if ta:
  557. tenant.role = ta.role
  558. else:
  559. raise TenantNotFoundError("Tenant not found for the account.")
  560. return tenant
  561. @staticmethod
  562. def switch_tenant(account: Account, tenant_id: Optional[str] = None) -> None:
  563. """Switch the current workspace for the account"""
  564. # Ensure tenant_id is provided
  565. if tenant_id is None:
  566. raise ValueError("Tenant ID must be provided.")
  567. tenant_account_join = (
  568. db.session.query(TenantAccountJoin)
  569. .join(Tenant, TenantAccountJoin.tenant_id == Tenant.id)
  570. .filter(
  571. TenantAccountJoin.account_id == account.id,
  572. TenantAccountJoin.tenant_id == tenant_id,
  573. Tenant.status == TenantStatus.NORMAL,
  574. )
  575. .first()
  576. )
  577. if not tenant_account_join:
  578. raise AccountNotLinkTenantError("Tenant not found or account is not a member of the tenant.")
  579. else:
  580. db.session.query(TenantAccountJoin).filter(
  581. TenantAccountJoin.account_id == account.id, TenantAccountJoin.tenant_id != tenant_id
  582. ).update({"current": False})
  583. tenant_account_join.current = True
  584. # Set the current tenant for the account
  585. account.set_tenant_id(tenant_account_join.tenant_id)
  586. db.session.commit()
  587. @staticmethod
  588. def get_tenant_members(tenant: Tenant) -> list[Account]:
  589. """Get tenant members"""
  590. query = (
  591. db.session.query(Account, TenantAccountJoin.role)
  592. .select_from(Account)
  593. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  594. .filter(TenantAccountJoin.tenant_id == tenant.id)
  595. )
  596. # Initialize an empty list to store the updated accounts
  597. updated_accounts = []
  598. for account, role in query:
  599. account.role = role
  600. updated_accounts.append(account)
  601. return updated_accounts
  602. @staticmethod
  603. def get_dataset_operator_members(tenant: Tenant) -> list[Account]:
  604. """Get dataset admin members"""
  605. query = (
  606. db.session.query(Account, TenantAccountJoin.role)
  607. .select_from(Account)
  608. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  609. .filter(TenantAccountJoin.tenant_id == tenant.id)
  610. .filter(TenantAccountJoin.role == "dataset_operator")
  611. )
  612. # Initialize an empty list to store the updated accounts
  613. updated_accounts = []
  614. for account, role in query:
  615. account.role = role
  616. updated_accounts.append(account)
  617. return updated_accounts
  618. @staticmethod
  619. def has_roles(tenant: Tenant, roles: list[TenantAccountRole]) -> bool:
  620. """Check if user has any of the given roles for a tenant"""
  621. if not all(isinstance(role, TenantAccountRole) for role in roles):
  622. raise ValueError("all roles must be TenantAccountRole")
  623. return (
  624. db.session.query(TenantAccountJoin)
  625. .filter(
  626. TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.role.in_([role.value for role in roles])
  627. )
  628. .first()
  629. is not None
  630. )
  631. @staticmethod
  632. def get_user_role(account: Account, tenant: Tenant) -> Optional[TenantAccountRole]:
  633. """Get the role of the current account for a given tenant"""
  634. join = (
  635. db.session.query(TenantAccountJoin)
  636. .filter(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == account.id)
  637. .first()
  638. )
  639. return join.role if join else None
  640. @staticmethod
  641. def get_tenant_count() -> int:
  642. """Get tenant count"""
  643. return cast(int, db.session.query(func.count(Tenant.id)).scalar())
  644. @staticmethod
  645. def check_member_permission(tenant: Tenant, operator: Account, member: Account | None, action: str) -> None:
  646. """Check member permission"""
  647. perms = {
  648. "add": [TenantAccountRole.OWNER, TenantAccountRole.ADMIN],
  649. "remove": [TenantAccountRole.OWNER],
  650. "update": [TenantAccountRole.OWNER],
  651. }
  652. if action not in {"add", "remove", "update"}:
  653. raise InvalidActionError("Invalid action.")
  654. if member:
  655. if operator.id == member.id:
  656. raise CannotOperateSelfError("Cannot operate self.")
  657. ta_operator = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=operator.id).first()
  658. if not ta_operator or ta_operator.role not in perms[action]:
  659. raise NoPermissionError(f"No permission to {action} member.")
  660. @staticmethod
  661. def remove_member_from_tenant(tenant: Tenant, account: Account, operator: Account) -> None:
  662. """Remove member from tenant"""
  663. if operator.id == account.id:
  664. raise CannotOperateSelfError("Cannot operate self.")
  665. TenantService.check_member_permission(tenant, operator, account, "remove")
  666. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  667. if not ta:
  668. raise MemberNotInTenantError("Member not in tenant.")
  669. db.session.delete(ta)
  670. db.session.commit()
  671. @staticmethod
  672. def update_member_role(tenant: Tenant, member: Account, new_role: str, operator: Account) -> None:
  673. """Update member role"""
  674. TenantService.check_member_permission(tenant, operator, member, "update")
  675. target_member_join = (
  676. db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=member.id).first()
  677. )
  678. if not target_member_join:
  679. raise MemberNotInTenantError("Member not in tenant.")
  680. if target_member_join.role == new_role:
  681. raise RoleAlreadyAssignedError("The provided role is already assigned to the member.")
  682. if new_role == "owner":
  683. # Find the current owner and change their role to 'admin'
  684. current_owner_join = (
  685. db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, role="owner").first()
  686. )
  687. if current_owner_join:
  688. current_owner_join.role = "admin"
  689. # Update the role of the target member
  690. target_member_join.role = new_role
  691. db.session.commit()
  692. @staticmethod
  693. def dissolve_tenant(tenant: Tenant, operator: Account) -> None:
  694. """Dissolve tenant"""
  695. if not TenantService.check_member_permission(tenant, operator, operator, "remove"):
  696. raise NoPermissionError("No permission to dissolve tenant.")
  697. db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id).delete()
  698. db.session.delete(tenant)
  699. db.session.commit()
  700. @staticmethod
  701. def get_custom_config(tenant_id: str) -> dict:
  702. tenant = db.get_or_404(Tenant, tenant_id)
  703. return cast(dict, tenant.custom_config_dict)
  704. class RegisterService:
  705. @classmethod
  706. def _get_invitation_token_key(cls, token: str) -> str:
  707. return f"member_invite:token:{token}"
  708. @classmethod
  709. def setup(cls, email: str, name: str, password: str, ip_address: str) -> None:
  710. """
  711. Setup dify
  712. :param email: email
  713. :param name: username
  714. :param password: password
  715. :param ip_address: ip address
  716. """
  717. try:
  718. # Register
  719. account = AccountService.create_account(
  720. email=email,
  721. name=name,
  722. interface_language=languages[0],
  723. password=password,
  724. is_setup=True,
  725. )
  726. account.last_login_ip = ip_address
  727. account.initialized_at = datetime.now(UTC).replace(tzinfo=None)
  728. TenantService.create_owner_tenant_if_not_exist(account=account, is_setup=True)
  729. dify_setup = DifySetup(version=dify_config.project.version)
  730. db.session.add(dify_setup)
  731. db.session.commit()
  732. except Exception as e:
  733. db.session.query(DifySetup).delete()
  734. db.session.query(TenantAccountJoin).delete()
  735. db.session.query(Account).delete()
  736. db.session.query(Tenant).delete()
  737. db.session.commit()
  738. logging.exception(f"Setup account failed, email: {email}, name: {name}")
  739. raise ValueError(f"Setup failed: {e}")
  740. @classmethod
  741. def register(
  742. cls,
  743. email,
  744. name,
  745. password: Optional[str] = None,
  746. open_id: Optional[str] = None,
  747. provider: Optional[str] = None,
  748. language: Optional[str] = None,
  749. status: Optional[AccountStatus] = None,
  750. is_setup: Optional[bool] = False,
  751. create_workspace_required: Optional[bool] = True,
  752. ) -> Account:
  753. db.session.begin_nested()
  754. """Register account"""
  755. try:
  756. account = AccountService.create_account(
  757. email=email,
  758. name=name,
  759. interface_language=language or languages[0],
  760. password=password,
  761. is_setup=is_setup,
  762. )
  763. account.status = AccountStatus.ACTIVE.value if not status else status.value
  764. account.initialized_at = datetime.now(UTC).replace(tzinfo=None)
  765. if open_id is not None and provider is not None:
  766. AccountService.link_account_integrate(provider, open_id, account)
  767. if (
  768. FeatureService.get_system_features().is_allow_create_workspace
  769. and create_workspace_required
  770. and FeatureService.get_system_features().license.workspaces.is_available()
  771. ):
  772. tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  773. TenantService.create_tenant_member(tenant, account, role="owner")
  774. account.current_tenant = tenant
  775. tenant_was_created.send(tenant)
  776. db.session.commit()
  777. except WorkSpaceNotAllowedCreateError:
  778. db.session.rollback()
  779. logging.exception("Register failed")
  780. raise AccountRegisterError("Workspace is not allowed to create.")
  781. except AccountRegisterError as are:
  782. db.session.rollback()
  783. logging.exception("Register failed")
  784. raise are
  785. except Exception as e:
  786. db.session.rollback()
  787. logging.exception("Register failed")
  788. raise AccountRegisterError(f"Registration failed: {e}") from e
  789. return account
  790. @classmethod
  791. def invite_new_member(
  792. cls, tenant: Tenant, email: str, language: str, role: str = "normal", inviter: Account | None = None
  793. ) -> str:
  794. if not inviter:
  795. raise ValueError("Inviter is required")
  796. """Invite new member"""
  797. with Session(db.engine) as session:
  798. account = session.query(Account).filter_by(email=email).first()
  799. if not account:
  800. TenantService.check_member_permission(tenant, inviter, None, "add")
  801. name = email.split("@")[0]
  802. account = cls.register(
  803. email=email, name=name, language=language, status=AccountStatus.PENDING, is_setup=True
  804. )
  805. # Create new tenant member for invited tenant
  806. TenantService.create_tenant_member(tenant, account, role)
  807. TenantService.switch_tenant(account, tenant.id)
  808. else:
  809. TenantService.check_member_permission(tenant, inviter, account, "add")
  810. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  811. if not ta:
  812. TenantService.create_tenant_member(tenant, account, role)
  813. # Support resend invitation email when the account is pending status
  814. if account.status != AccountStatus.PENDING.value:
  815. raise AccountAlreadyInTenantError("Account already in tenant.")
  816. token = cls.generate_invite_token(tenant, account)
  817. # send email
  818. send_invite_member_mail_task.delay(
  819. language=account.interface_language,
  820. to=email,
  821. token=token,
  822. inviter_name=inviter.name if inviter else "Dify",
  823. workspace_name=tenant.name,
  824. )
  825. return token
  826. @classmethod
  827. def generate_invite_token(cls, tenant: Tenant, account: Account) -> str:
  828. token = str(uuid.uuid4())
  829. invitation_data = {
  830. "account_id": account.id,
  831. "email": account.email,
  832. "workspace_id": tenant.id,
  833. }
  834. expiry_hours = dify_config.INVITE_EXPIRY_HOURS
  835. redis_client.setex(cls._get_invitation_token_key(token), expiry_hours * 60 * 60, json.dumps(invitation_data))
  836. return token
  837. @classmethod
  838. def is_valid_invite_token(cls, token: str) -> bool:
  839. data = redis_client.get(cls._get_invitation_token_key(token))
  840. return data is not None
  841. @classmethod
  842. def revoke_token(cls, workspace_id: str, email: str, token: str):
  843. if workspace_id and email:
  844. email_hash = sha256(email.encode()).hexdigest()
  845. cache_key = "member_invite_token:{}, {}:{}".format(workspace_id, email_hash, token)
  846. redis_client.delete(cache_key)
  847. else:
  848. redis_client.delete(cls._get_invitation_token_key(token))
  849. @classmethod
  850. def get_invitation_if_token_valid(
  851. cls, workspace_id: Optional[str], email: str, token: str
  852. ) -> Optional[dict[str, Any]]:
  853. invitation_data = cls._get_invitation_by_token(token, workspace_id, email)
  854. if not invitation_data:
  855. return None
  856. tenant = (
  857. db.session.query(Tenant)
  858. .filter(Tenant.id == invitation_data["workspace_id"], Tenant.status == "normal")
  859. .first()
  860. )
  861. if not tenant:
  862. return None
  863. tenant_account = (
  864. db.session.query(Account, TenantAccountJoin.role)
  865. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  866. .filter(Account.email == invitation_data["email"], TenantAccountJoin.tenant_id == tenant.id)
  867. .first()
  868. )
  869. if not tenant_account:
  870. return None
  871. account = tenant_account[0]
  872. if not account:
  873. return None
  874. if invitation_data["account_id"] != str(account.id):
  875. return None
  876. return {
  877. "account": account,
  878. "data": invitation_data,
  879. "tenant": tenant,
  880. }
  881. @classmethod
  882. def _get_invitation_by_token(
  883. cls, token: str, workspace_id: Optional[str] = None, email: Optional[str] = None
  884. ) -> Optional[dict[str, str]]:
  885. if workspace_id is not None and email is not None:
  886. email_hash = sha256(email.encode()).hexdigest()
  887. cache_key = f"member_invite_token:{workspace_id}, {email_hash}:{token}"
  888. account_id = redis_client.get(cache_key)
  889. if not account_id:
  890. return None
  891. return {
  892. "account_id": account_id.decode("utf-8"),
  893. "email": email,
  894. "workspace_id": workspace_id,
  895. }
  896. else:
  897. data = redis_client.get(cls._get_invitation_token_key(token))
  898. if not data:
  899. return None
  900. invitation: dict = json.loads(data)
  901. return invitation
  902. def _generate_refresh_token(length: int = 64):
  903. token = secrets.token_hex(length)
  904. return token