account_service.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  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.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(UTC).replace(tzinfo=None) - account.last_active_at > timedelta(minutes=10):
  102. account.last_active_at = datetime.now(UTC).replace(tzinfo=None)
  103. db.session.commit()
  104. return cast(Account, account)
  105. @staticmethod
  106. def get_account_jwt_token(account: Account) -> str:
  107. exp_dt = datetime.now(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: str = 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(UTC).replace(tzinfo=None)
  138. db.session.commit()
  139. return cast(Account, 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 AccountNotFound
  169. raise AccountNotFound()
  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(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(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 account_email is None:
  288. raise ValueError("Email must be provided.")
  289. if cls.reset_password_rate_limiter.is_rate_limited(account_email):
  290. from controllers.console.auth.error import PasswordResetRateLimitExceededError
  291. raise PasswordResetRateLimitExceededError()
  292. code = "".join([str(random.randint(0, 9)) for _ in range(6)])
  293. token = TokenManager.generate_token(
  294. account=account, email=email, token_type="reset_password", additional_data={"code": code}
  295. )
  296. send_reset_password_mail_task.delay(
  297. language=language,
  298. to=account_email,
  299. code=code,
  300. )
  301. cls.reset_password_rate_limiter.increment_rate_limit(account_email)
  302. return token
  303. @classmethod
  304. def revoke_reset_password_token(cls, token: str):
  305. TokenManager.revoke_token(token, "reset_password")
  306. @classmethod
  307. def get_reset_password_data(cls, token: str) -> Optional[dict[str, Any]]:
  308. return TokenManager.get_token_data(token, "reset_password")
  309. @classmethod
  310. def send_email_code_login_email(
  311. cls, account: Optional[Account] = None, email: Optional[str] = None, language: Optional[str] = "en-US"
  312. ):
  313. if email is None:
  314. raise ValueError("Email must be provided.")
  315. if cls.email_code_login_rate_limiter.is_rate_limited(email):
  316. from controllers.console.auth.error import EmailCodeLoginRateLimitExceededError
  317. raise EmailCodeLoginRateLimitExceededError()
  318. code = "".join([str(random.randint(0, 9)) for _ in range(6)])
  319. token = TokenManager.generate_token(
  320. account=account, email=email, token_type="email_code_login", additional_data={"code": code}
  321. )
  322. send_email_code_login_mail_task.delay(
  323. language=language,
  324. to=account.email if account else email,
  325. code=code,
  326. )
  327. cls.email_code_login_rate_limiter.increment_rate_limit(email)
  328. return token
  329. @classmethod
  330. def get_email_code_login_data(cls, token: str) -> Optional[dict[str, Any]]:
  331. return TokenManager.get_token_data(token, "email_code_login")
  332. @classmethod
  333. def revoke_email_code_login_token(cls, token: str):
  334. TokenManager.revoke_token(token, "email_code_login")
  335. @classmethod
  336. def get_user_through_email(cls, email: str):
  337. account = db.session.query(Account).filter(Account.email == email).first()
  338. if not account:
  339. return None
  340. if account.status == AccountStatus.BANNED.value:
  341. raise Unauthorized("Account is banned.")
  342. return account
  343. @staticmethod
  344. def add_login_error_rate_limit(email: str) -> None:
  345. key = f"login_error_rate_limit:{email}"
  346. count = redis_client.get(key)
  347. if count is None:
  348. count = 0
  349. count = int(count) + 1
  350. redis_client.setex(key, dify_config.LOGIN_LOCKOUT_DURATION, count)
  351. @staticmethod
  352. def is_login_error_rate_limit(email: str) -> bool:
  353. key = f"login_error_rate_limit:{email}"
  354. count = redis_client.get(key)
  355. if count is None:
  356. return False
  357. count = int(count)
  358. if count > AccountService.LOGIN_MAX_ERROR_LIMITS:
  359. return True
  360. return False
  361. @staticmethod
  362. def reset_login_error_rate_limit(email: str):
  363. key = f"login_error_rate_limit:{email}"
  364. redis_client.delete(key)
  365. @staticmethod
  366. def is_email_send_ip_limit(ip_address: str):
  367. minute_key = f"email_send_ip_limit_minute:{ip_address}"
  368. freeze_key = f"email_send_ip_limit_freeze:{ip_address}"
  369. hour_limit_key = f"email_send_ip_limit_hour:{ip_address}"
  370. # check ip is frozen
  371. if redis_client.get(freeze_key):
  372. return True
  373. # check current minute count
  374. current_minute_count = redis_client.get(minute_key)
  375. if current_minute_count is None:
  376. current_minute_count = 0
  377. current_minute_count = int(current_minute_count)
  378. # check current hour count
  379. if current_minute_count > dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE:
  380. hour_limit_count = redis_client.get(hour_limit_key)
  381. if hour_limit_count is None:
  382. hour_limit_count = 0
  383. hour_limit_count = int(hour_limit_count)
  384. if hour_limit_count >= 1:
  385. redis_client.setex(freeze_key, 60 * 60, 1)
  386. return True
  387. else:
  388. redis_client.setex(hour_limit_key, 60 * 10, hour_limit_count + 1) # first time limit 10 minutes
  389. # add hour limit count
  390. redis_client.incr(hour_limit_key)
  391. redis_client.expire(hour_limit_key, 60 * 60)
  392. return True
  393. redis_client.setex(minute_key, 60, current_minute_count + 1)
  394. redis_client.expire(minute_key, 60)
  395. return False
  396. def _get_login_cache_key(*, account_id: str, token: str):
  397. return f"account_login:{account_id}:{token}"
  398. class TenantService:
  399. @staticmethod
  400. def create_tenant(name: str, is_setup: Optional[bool] = False, is_from_dashboard: Optional[bool] = False) -> Tenant:
  401. """Create tenant"""
  402. if (
  403. not FeatureService.get_system_features().is_allow_create_workspace
  404. and not is_setup
  405. and not is_from_dashboard
  406. ):
  407. from controllers.console.error import NotAllowedCreateWorkspace
  408. raise NotAllowedCreateWorkspace()
  409. tenant = Tenant(name=name)
  410. db.session.add(tenant)
  411. db.session.commit()
  412. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  413. db.session.commit()
  414. return tenant
  415. @staticmethod
  416. def create_owner_tenant_if_not_exist(
  417. account: Account, name: Optional[str] = None, is_setup: Optional[bool] = False
  418. ):
  419. """Check if user have a workspace or not"""
  420. available_ta = (
  421. TenantAccountJoin.query.filter_by(account_id=account.id).order_by(TenantAccountJoin.id.asc()).first()
  422. )
  423. if available_ta:
  424. return
  425. """Create owner tenant if not exist"""
  426. if not FeatureService.get_system_features().is_allow_create_workspace and not is_setup:
  427. raise WorkSpaceNotAllowedCreateError()
  428. if name:
  429. tenant = TenantService.create_tenant(name=name, is_setup=is_setup)
  430. else:
  431. tenant = TenantService.create_tenant(name=f"{account.name}'s Workspace", is_setup=is_setup)
  432. TenantService.create_tenant_member(tenant, account, role="owner")
  433. account.current_tenant = tenant
  434. db.session.commit()
  435. tenant_was_created.send(tenant)
  436. @staticmethod
  437. def create_tenant_member(tenant: Tenant, account: Account, role: str = "normal") -> TenantAccountJoin:
  438. """Create tenant member"""
  439. if role == TenantAccountJoinRole.OWNER.value:
  440. if TenantService.has_roles(tenant, [TenantAccountJoinRole.OWNER]):
  441. logging.error(f"Tenant {tenant.id} has already an owner.")
  442. raise Exception("Tenant already has an owner.")
  443. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  444. if ta:
  445. ta.role = role
  446. else:
  447. ta = TenantAccountJoin(tenant_id=tenant.id, account_id=account.id, role=role)
  448. db.session.add(ta)
  449. db.session.commit()
  450. return ta
  451. @staticmethod
  452. def get_join_tenants(account: Account) -> list[Tenant]:
  453. """Get account join tenants"""
  454. return (
  455. db.session.query(Tenant)
  456. .join(TenantAccountJoin, Tenant.id == TenantAccountJoin.tenant_id)
  457. .filter(TenantAccountJoin.account_id == account.id, Tenant.status == TenantStatus.NORMAL)
  458. .all()
  459. )
  460. @staticmethod
  461. def get_current_tenant_by_account(account: Account):
  462. """Get tenant by account and add the role"""
  463. tenant = account.current_tenant
  464. if not tenant:
  465. raise TenantNotFoundError("Tenant not found.")
  466. ta = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=account.id).first()
  467. if ta:
  468. tenant.role = ta.role
  469. else:
  470. raise TenantNotFoundError("Tenant not found for the account.")
  471. return tenant
  472. @staticmethod
  473. def switch_tenant(account: Account, tenant_id: Optional[str] = None) -> None:
  474. """Switch the current workspace for the account"""
  475. # Ensure tenant_id is provided
  476. if tenant_id is None:
  477. raise ValueError("Tenant ID must be provided.")
  478. tenant_account_join = (
  479. db.session.query(TenantAccountJoin)
  480. .join(Tenant, TenantAccountJoin.tenant_id == Tenant.id)
  481. .filter(
  482. TenantAccountJoin.account_id == account.id,
  483. TenantAccountJoin.tenant_id == tenant_id,
  484. Tenant.status == TenantStatus.NORMAL,
  485. )
  486. .first()
  487. )
  488. if not tenant_account_join:
  489. raise AccountNotLinkTenantError("Tenant not found or account is not a member of the tenant.")
  490. else:
  491. TenantAccountJoin.query.filter(
  492. TenantAccountJoin.account_id == account.id, TenantAccountJoin.tenant_id != tenant_id
  493. ).update({"current": False})
  494. tenant_account_join.current = True
  495. # Set the current tenant for the account
  496. account.current_tenant_id = tenant_account_join.tenant_id
  497. db.session.commit()
  498. @staticmethod
  499. def get_tenant_members(tenant: Tenant) -> list[Account]:
  500. """Get tenant members"""
  501. query = (
  502. db.session.query(Account, TenantAccountJoin.role)
  503. .select_from(Account)
  504. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  505. .filter(TenantAccountJoin.tenant_id == tenant.id)
  506. )
  507. # Initialize an empty list to store the updated accounts
  508. updated_accounts = []
  509. for account, role in query:
  510. account.role = role
  511. updated_accounts.append(account)
  512. return updated_accounts
  513. @staticmethod
  514. def get_dataset_operator_members(tenant: Tenant) -> list[Account]:
  515. """Get dataset admin members"""
  516. query = (
  517. db.session.query(Account, TenantAccountJoin.role)
  518. .select_from(Account)
  519. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  520. .filter(TenantAccountJoin.tenant_id == tenant.id)
  521. .filter(TenantAccountJoin.role == "dataset_operator")
  522. )
  523. # Initialize an empty list to store the updated accounts
  524. updated_accounts = []
  525. for account, role in query:
  526. account.role = role
  527. updated_accounts.append(account)
  528. return updated_accounts
  529. @staticmethod
  530. def has_roles(tenant: Tenant, roles: list[TenantAccountJoinRole]) -> bool:
  531. """Check if user has any of the given roles for a tenant"""
  532. if not all(isinstance(role, TenantAccountJoinRole) for role in roles):
  533. raise ValueError("all roles must be TenantAccountJoinRole")
  534. return (
  535. db.session.query(TenantAccountJoin)
  536. .filter(
  537. TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.role.in_([role.value for role in roles])
  538. )
  539. .first()
  540. is not None
  541. )
  542. @staticmethod
  543. def get_user_role(account: Account, tenant: Tenant) -> Optional[TenantAccountJoinRole]:
  544. """Get the role of the current account for a given tenant"""
  545. join = (
  546. db.session.query(TenantAccountJoin)
  547. .filter(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == account.id)
  548. .first()
  549. )
  550. return join.role if join else None
  551. @staticmethod
  552. def get_tenant_count() -> int:
  553. """Get tenant count"""
  554. return cast(int, db.session.query(func.count(Tenant.id)).scalar())
  555. @staticmethod
  556. def check_member_permission(tenant: Tenant, operator: Account, member: Account | None, action: str) -> None:
  557. """Check member permission"""
  558. perms = {
  559. "add": [TenantAccountRole.OWNER, TenantAccountRole.ADMIN],
  560. "remove": [TenantAccountRole.OWNER],
  561. "update": [TenantAccountRole.OWNER],
  562. }
  563. if action not in {"add", "remove", "update"}:
  564. raise InvalidActionError("Invalid action.")
  565. if member:
  566. if operator.id == member.id:
  567. raise CannotOperateSelfError("Cannot operate self.")
  568. ta_operator = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=operator.id).first()
  569. if not ta_operator or ta_operator.role not in perms[action]:
  570. raise NoPermissionError(f"No permission to {action} member.")
  571. @staticmethod
  572. def remove_member_from_tenant(tenant: Tenant, account: Account, operator: Account) -> None:
  573. """Remove member from tenant"""
  574. if operator.id == account.id and TenantService.check_member_permission(tenant, operator, account, "remove"):
  575. raise CannotOperateSelfError("Cannot operate self.")
  576. ta = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=account.id).first()
  577. if not ta:
  578. raise MemberNotInTenantError("Member not in tenant.")
  579. db.session.delete(ta)
  580. db.session.commit()
  581. @staticmethod
  582. def update_member_role(tenant: Tenant, member: Account, new_role: str, operator: Account) -> None:
  583. """Update member role"""
  584. TenantService.check_member_permission(tenant, operator, member, "update")
  585. target_member_join = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=member.id).first()
  586. if target_member_join.role == new_role:
  587. raise RoleAlreadyAssignedError("The provided role is already assigned to the member.")
  588. if new_role == "owner":
  589. # Find the current owner and change their role to 'admin'
  590. current_owner_join = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, role="owner").first()
  591. current_owner_join.role = "admin"
  592. # Update the role of the target member
  593. target_member_join.role = new_role
  594. db.session.commit()
  595. @staticmethod
  596. def dissolve_tenant(tenant: Tenant, operator: Account) -> None:
  597. """Dissolve tenant"""
  598. if not TenantService.check_member_permission(tenant, operator, operator, "remove"):
  599. raise NoPermissionError("No permission to dissolve tenant.")
  600. db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id).delete()
  601. db.session.delete(tenant)
  602. db.session.commit()
  603. @staticmethod
  604. def get_custom_config(tenant_id: str) -> dict:
  605. tenant = Tenant.query.filter(Tenant.id == tenant_id).one_or_404()
  606. return cast(dict, tenant.custom_config_dict)
  607. class RegisterService:
  608. @classmethod
  609. def _get_invitation_token_key(cls, token: str) -> str:
  610. return f"member_invite:token:{token}"
  611. @classmethod
  612. def setup(cls, email: str, name: str, password: str, ip_address: str) -> None:
  613. """
  614. Setup dify
  615. :param email: email
  616. :param name: username
  617. :param password: password
  618. :param ip_address: ip address
  619. """
  620. try:
  621. # Register
  622. account = AccountService.create_account(
  623. email=email,
  624. name=name,
  625. interface_language=languages[0],
  626. password=password,
  627. is_setup=True,
  628. )
  629. account.last_login_ip = ip_address
  630. account.initialized_at = datetime.now(UTC).replace(tzinfo=None)
  631. TenantService.create_owner_tenant_if_not_exist(account=account, is_setup=True)
  632. dify_setup = DifySetup(version=dify_config.CURRENT_VERSION)
  633. db.session.add(dify_setup)
  634. db.session.commit()
  635. except Exception as e:
  636. db.session.query(DifySetup).delete()
  637. db.session.query(TenantAccountJoin).delete()
  638. db.session.query(Account).delete()
  639. db.session.query(Tenant).delete()
  640. db.session.commit()
  641. logging.exception(f"Setup account failed, email: {email}, name: {name}")
  642. raise ValueError(f"Setup failed: {e}")
  643. @classmethod
  644. def register(
  645. cls,
  646. email,
  647. name,
  648. password: Optional[str] = None,
  649. open_id: Optional[str] = None,
  650. provider: Optional[str] = None,
  651. language: Optional[str] = None,
  652. status: Optional[AccountStatus] = None,
  653. is_setup: Optional[bool] = False,
  654. create_workspace_required: Optional[bool] = True,
  655. ) -> Account:
  656. db.session.begin_nested()
  657. """Register account"""
  658. try:
  659. account = AccountService.create_account(
  660. email=email,
  661. name=name,
  662. interface_language=language or languages[0],
  663. password=password,
  664. is_setup=is_setup,
  665. )
  666. account.status = AccountStatus.ACTIVE.value if not status else status.value
  667. account.initialized_at = datetime.now(UTC).replace(tzinfo=None)
  668. if open_id is not None and provider is not None:
  669. AccountService.link_account_integrate(provider, open_id, account)
  670. if FeatureService.get_system_features().is_allow_create_workspace and create_workspace_required:
  671. tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  672. TenantService.create_tenant_member(tenant, account, role="owner")
  673. account.current_tenant = tenant
  674. tenant_was_created.send(tenant)
  675. db.session.commit()
  676. except WorkSpaceNotAllowedCreateError:
  677. db.session.rollback()
  678. except Exception as e:
  679. db.session.rollback()
  680. logging.exception("Register failed")
  681. raise AccountRegisterError(f"Registration failed: {e}") from e
  682. return account
  683. @classmethod
  684. def invite_new_member(
  685. cls, tenant: Tenant, email: str, language: str, role: str = "normal", inviter: Optional[Account] = None
  686. ) -> str:
  687. """Invite new member"""
  688. account = Account.query.filter_by(email=email).first()
  689. assert inviter is not None, "Inviter must be provided."
  690. if not account:
  691. TenantService.check_member_permission(tenant, inviter, None, "add")
  692. name = email.split("@")[0]
  693. account = cls.register(
  694. email=email, name=name, language=language, status=AccountStatus.PENDING, is_setup=True
  695. )
  696. # Create new tenant member for invited tenant
  697. TenantService.create_tenant_member(tenant, account, role)
  698. TenantService.switch_tenant(account, tenant.id)
  699. else:
  700. TenantService.check_member_permission(tenant, inviter, account, "add")
  701. ta = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=account.id).first()
  702. if not ta:
  703. TenantService.create_tenant_member(tenant, account, role)
  704. # Support resend invitation email when the account is pending status
  705. if account.status != AccountStatus.PENDING.value:
  706. raise AccountAlreadyInTenantError("Account already in tenant.")
  707. token = cls.generate_invite_token(tenant, account)
  708. # send email
  709. send_invite_member_mail_task.delay(
  710. language=account.interface_language,
  711. to=email,
  712. token=token,
  713. inviter_name=inviter.name if inviter else "Dify",
  714. workspace_name=tenant.name,
  715. )
  716. return token
  717. @classmethod
  718. def generate_invite_token(cls, tenant: Tenant, account: Account) -> str:
  719. token = str(uuid.uuid4())
  720. invitation_data = {
  721. "account_id": account.id,
  722. "email": account.email,
  723. "workspace_id": tenant.id,
  724. }
  725. expiry_hours = dify_config.INVITE_EXPIRY_HOURS
  726. redis_client.setex(cls._get_invitation_token_key(token), expiry_hours * 60 * 60, json.dumps(invitation_data))
  727. return token
  728. @classmethod
  729. def is_valid_invite_token(cls, token: str) -> bool:
  730. data = redis_client.get(cls._get_invitation_token_key(token))
  731. return data is not None
  732. @classmethod
  733. def revoke_token(cls, workspace_id: str, email: str, token: str):
  734. if workspace_id and email:
  735. email_hash = sha256(email.encode()).hexdigest()
  736. cache_key = "member_invite_token:{}, {}:{}".format(workspace_id, email_hash, token)
  737. redis_client.delete(cache_key)
  738. else:
  739. redis_client.delete(cls._get_invitation_token_key(token))
  740. @classmethod
  741. def get_invitation_if_token_valid(
  742. cls, workspace_id: Optional[str], email: str, token: str
  743. ) -> Optional[dict[str, Any]]:
  744. invitation_data = cls._get_invitation_by_token(token, workspace_id, email)
  745. if not invitation_data:
  746. return None
  747. tenant = (
  748. db.session.query(Tenant)
  749. .filter(Tenant.id == invitation_data["workspace_id"], Tenant.status == "normal")
  750. .first()
  751. )
  752. if not tenant:
  753. return None
  754. tenant_account = (
  755. db.session.query(Account, TenantAccountJoin.role)
  756. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  757. .filter(Account.email == invitation_data["email"], TenantAccountJoin.tenant_id == tenant.id)
  758. .first()
  759. )
  760. if not tenant_account:
  761. return None
  762. account = tenant_account[0]
  763. if not account:
  764. return None
  765. if invitation_data["account_id"] != str(account.id):
  766. return None
  767. return {
  768. "account": account,
  769. "data": invitation_data,
  770. "tenant": tenant,
  771. }
  772. @classmethod
  773. def _get_invitation_by_token(
  774. cls, token: str, workspace_id: Optional[str] = None, email: Optional[str] = None
  775. ) -> Optional[dict[str, str]]:
  776. if workspace_id is not None and email is not None:
  777. email_hash = sha256(email.encode()).hexdigest()
  778. cache_key = f"member_invite_token:{workspace_id}, {email_hash}:{token}"
  779. account_id = redis_client.get(cache_key)
  780. if not account_id:
  781. return None
  782. return {
  783. "account_id": account_id.decode("utf-8"),
  784. "email": email,
  785. "workspace_id": workspace_id,
  786. }
  787. else:
  788. data = redis_client.get(cls._get_invitation_token_key(token))
  789. if not data:
  790. return None
  791. invitation: dict = json.loads(data)
  792. return invitation
  793. def _generate_refresh_token(length: int = 64):
  794. token = secrets.token_hex(length)
  795. return token