account_service.py 39 KB

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