account_service.py 39 KB

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