account_service.py 40 KB

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