account_service.py 35 KB

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