account_service.py 38 KB

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