account_service.py 40 KB

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