account_service.py 35 KB

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