account_service.py 39 KB

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