You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

account_service.py 53KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480
  1. import base64
  2. import json
  3. import logging
  4. import secrets
  5. import uuid
  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
  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, redis_fallback
  18. from libs.datetime_utils import naive_utc_now
  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. TenantPluginAutoUpgradeStrategy,
  31. TenantStatus,
  32. )
  33. from models.model import DifySetup
  34. from services.billing_service import BillingService
  35. from services.errors.account import (
  36. AccountAlreadyInTenantError,
  37. AccountLoginError,
  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, WorkspacesLimitExceededError
  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_change_mail_task import (
  55. send_change_mail_completed_notification_task,
  56. send_change_mail_task,
  57. )
  58. from tasks.mail_email_code_login import send_email_code_login_mail_task
  59. from tasks.mail_invite_member_task import send_invite_member_mail_task
  60. from tasks.mail_owner_transfer_task import (
  61. send_new_owner_transfer_notify_email_task,
  62. send_old_owner_transfer_notify_email_task,
  63. send_owner_transfer_confirm_task,
  64. )
  65. from tasks.mail_register_task import send_email_register_mail_task, send_email_register_mail_task_when_account_exist
  66. from tasks.mail_reset_password_task import (
  67. send_reset_password_mail_task,
  68. send_reset_password_mail_task_when_account_not_exist,
  69. )
  70. logger = logging.getLogger(__name__)
  71. class TokenPair(BaseModel):
  72. access_token: str
  73. refresh_token: str
  74. REFRESH_TOKEN_PREFIX = "refresh_token:"
  75. ACCOUNT_REFRESH_TOKEN_PREFIX = "account_refresh_token:"
  76. REFRESH_TOKEN_EXPIRY = timedelta(days=dify_config.REFRESH_TOKEN_EXPIRE_DAYS)
  77. class AccountService:
  78. reset_password_rate_limiter = RateLimiter(prefix="reset_password_rate_limit", max_attempts=1, time_window=60 * 1)
  79. email_register_rate_limiter = RateLimiter(prefix="email_register_rate_limit", max_attempts=1, time_window=60 * 1)
  80. email_code_login_rate_limiter = RateLimiter(
  81. prefix="email_code_login_rate_limit", max_attempts=1, time_window=60 * 1
  82. )
  83. email_code_account_deletion_rate_limiter = RateLimiter(
  84. prefix="email_code_account_deletion_rate_limit", max_attempts=1, time_window=60 * 1
  85. )
  86. change_email_rate_limiter = RateLimiter(prefix="change_email_rate_limit", max_attempts=1, time_window=60 * 1)
  87. owner_transfer_rate_limiter = RateLimiter(prefix="owner_transfer_rate_limit", max_attempts=1, time_window=60 * 1)
  88. LOGIN_MAX_ERROR_LIMITS = 5
  89. FORGOT_PASSWORD_MAX_ERROR_LIMITS = 5
  90. CHANGE_EMAIL_MAX_ERROR_LIMITS = 5
  91. OWNER_TRANSFER_MAX_ERROR_LIMITS = 5
  92. EMAIL_REGISTER_MAX_ERROR_LIMITS = 5
  93. @staticmethod
  94. def _get_refresh_token_key(refresh_token: str) -> str:
  95. return f"{REFRESH_TOKEN_PREFIX}{refresh_token}"
  96. @staticmethod
  97. def _get_account_refresh_token_key(account_id: str) -> str:
  98. return f"{ACCOUNT_REFRESH_TOKEN_PREFIX}{account_id}"
  99. @staticmethod
  100. def _store_refresh_token(refresh_token: str, account_id: str):
  101. redis_client.setex(AccountService._get_refresh_token_key(refresh_token), REFRESH_TOKEN_EXPIRY, account_id)
  102. redis_client.setex(
  103. AccountService._get_account_refresh_token_key(account_id), REFRESH_TOKEN_EXPIRY, refresh_token
  104. )
  105. @staticmethod
  106. def _delete_refresh_token(refresh_token: str, account_id: str):
  107. redis_client.delete(AccountService._get_refresh_token_key(refresh_token))
  108. redis_client.delete(AccountService._get_account_refresh_token_key(account_id))
  109. @staticmethod
  110. def load_user(user_id: str) -> None | Account:
  111. account = db.session.query(Account).filter_by(id=user_id).first()
  112. if not account:
  113. return None
  114. if account.status == AccountStatus.BANNED.value:
  115. raise Unauthorized("Account is banned.")
  116. current_tenant = db.session.query(TenantAccountJoin).filter_by(account_id=account.id, current=True).first()
  117. if current_tenant:
  118. account.set_tenant_id(current_tenant.tenant_id)
  119. else:
  120. available_ta = (
  121. db.session.query(TenantAccountJoin)
  122. .filter_by(account_id=account.id)
  123. .order_by(TenantAccountJoin.id.asc())
  124. .first()
  125. )
  126. if not available_ta:
  127. return None
  128. account.set_tenant_id(available_ta.tenant_id)
  129. available_ta.current = True
  130. db.session.commit()
  131. if naive_utc_now() - account.last_active_at > timedelta(minutes=10):
  132. account.last_active_at = naive_utc_now()
  133. db.session.commit()
  134. # NOTE: make sure account is accessible outside of a db session
  135. # This ensures that it will work correctly after upgrading to Flask version 3.1.2
  136. db.session.refresh(account)
  137. db.session.close()
  138. return account
  139. @staticmethod
  140. def get_account_jwt_token(account: Account) -> str:
  141. exp_dt = datetime.now(UTC) + timedelta(minutes=dify_config.ACCESS_TOKEN_EXPIRE_MINUTES)
  142. exp = int(exp_dt.timestamp())
  143. payload = {
  144. "user_id": account.id,
  145. "exp": exp,
  146. "iss": dify_config.EDITION,
  147. "sub": "Console API Passport",
  148. }
  149. token: str = PassportService().issue(payload)
  150. return token
  151. @staticmethod
  152. def authenticate(email: str, password: str, invite_token: Optional[str] = None) -> Account:
  153. """authenticate account with email and password"""
  154. account = db.session.query(Account).filter_by(email=email).first()
  155. if not account:
  156. raise AccountPasswordError("Invalid email or password.")
  157. if account.status == AccountStatus.BANNED.value:
  158. raise AccountLoginError("Account is banned.")
  159. if password and invite_token and account.password is None:
  160. # if invite_token is valid, set password and password_salt
  161. salt = secrets.token_bytes(16)
  162. base64_salt = base64.b64encode(salt).decode()
  163. password_hashed = hash_password(password, salt)
  164. base64_password_hashed = base64.b64encode(password_hashed).decode()
  165. account.password = base64_password_hashed
  166. account.password_salt = base64_salt
  167. if account.password is None or not compare_password(password, account.password, account.password_salt):
  168. raise AccountPasswordError("Invalid email or password.")
  169. if account.status == AccountStatus.PENDING.value:
  170. account.status = AccountStatus.ACTIVE.value
  171. account.initialized_at = naive_utc_now()
  172. db.session.commit()
  173. return account
  174. @staticmethod
  175. def update_account_password(account, password, new_password):
  176. """update account password"""
  177. if account.password and not compare_password(password, account.password, account.password_salt):
  178. raise CurrentPasswordIncorrectError("Current password is incorrect.")
  179. # may be raised
  180. valid_password(new_password)
  181. # generate password salt
  182. salt = secrets.token_bytes(16)
  183. base64_salt = base64.b64encode(salt).decode()
  184. # encrypt password with salt
  185. password_hashed = hash_password(new_password, salt)
  186. base64_password_hashed = base64.b64encode(password_hashed).decode()
  187. account.password = base64_password_hashed
  188. account.password_salt = base64_salt
  189. db.session.add(account)
  190. db.session.commit()
  191. return account
  192. @staticmethod
  193. def create_account(
  194. email: str,
  195. name: str,
  196. interface_language: str,
  197. password: Optional[str] = None,
  198. interface_theme: str = "light",
  199. is_setup: Optional[bool] = False,
  200. ) -> Account:
  201. """create account"""
  202. if not FeatureService.get_system_features().is_allow_register and not is_setup:
  203. from controllers.console.error import AccountNotFound
  204. raise AccountNotFound()
  205. if dify_config.BILLING_ENABLED and BillingService.is_email_in_freeze(email):
  206. raise AccountRegisterError(
  207. description=(
  208. "This email account has been deleted within the past "
  209. "30 days and is temporarily unavailable for new account registration"
  210. )
  211. )
  212. account = Account()
  213. account.email = email
  214. account.name = name
  215. if password:
  216. # generate password salt
  217. salt = secrets.token_bytes(16)
  218. base64_salt = base64.b64encode(salt).decode()
  219. # encrypt password with salt
  220. password_hashed = hash_password(password, salt)
  221. base64_password_hashed = base64.b64encode(password_hashed).decode()
  222. account.password = base64_password_hashed
  223. account.password_salt = base64_salt
  224. account.interface_language = interface_language
  225. account.interface_theme = interface_theme
  226. # Set timezone based on language
  227. account.timezone = language_timezone_mapping.get(interface_language, "UTC")
  228. db.session.add(account)
  229. db.session.commit()
  230. return account
  231. @staticmethod
  232. def create_account_and_tenant(
  233. email: str, name: str, interface_language: str, password: Optional[str] = None
  234. ) -> Account:
  235. """create account"""
  236. account = AccountService.create_account(
  237. email=email, name=name, interface_language=interface_language, password=password
  238. )
  239. TenantService.create_owner_tenant_if_not_exist(account=account)
  240. return account
  241. @staticmethod
  242. def generate_account_deletion_verification_code(account: Account) -> tuple[str, str]:
  243. code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])
  244. token = TokenManager.generate_token(
  245. account=account, token_type="account_deletion", additional_data={"code": code}
  246. )
  247. return token, code
  248. @classmethod
  249. def send_account_deletion_verification_email(cls, account: Account, code: str):
  250. email = account.email
  251. if cls.email_code_account_deletion_rate_limiter.is_rate_limited(email):
  252. from controllers.console.auth.error import EmailCodeAccountDeletionRateLimitExceededError
  253. raise EmailCodeAccountDeletionRateLimitExceededError()
  254. send_account_deletion_verification_code.delay(to=email, code=code)
  255. cls.email_code_account_deletion_rate_limiter.increment_rate_limit(email)
  256. @staticmethod
  257. def verify_account_deletion_code(token: str, code: str) -> bool:
  258. token_data = TokenManager.get_token_data(token, "account_deletion")
  259. if token_data is None:
  260. return False
  261. if token_data["code"] != code:
  262. return False
  263. return True
  264. @staticmethod
  265. def delete_account(account: Account):
  266. """Delete account. This method only adds a task to the queue for deletion."""
  267. delete_account_task.delay(account.id)
  268. @staticmethod
  269. def link_account_integrate(provider: str, open_id: str, account: Account):
  270. """Link account integrate"""
  271. try:
  272. # Query whether there is an existing binding record for the same provider
  273. account_integrate: Optional[AccountIntegrate] = (
  274. db.session.query(AccountIntegrate).filter_by(account_id=account.id, provider=provider).first()
  275. )
  276. if account_integrate:
  277. # If it exists, update the record
  278. account_integrate.open_id = open_id
  279. account_integrate.encrypted_token = "" # todo
  280. account_integrate.updated_at = naive_utc_now()
  281. else:
  282. # If it does not exist, create a new record
  283. account_integrate = AccountIntegrate(
  284. account_id=account.id, provider=provider, open_id=open_id, encrypted_token=""
  285. )
  286. db.session.add(account_integrate)
  287. db.session.commit()
  288. logger.info("Account %s linked %s account %s.", account.id, provider, open_id)
  289. except Exception as e:
  290. logger.exception("Failed to link %s account %s to Account %s", provider, open_id, account.id)
  291. raise LinkAccountIntegrateError("Failed to link account.") from e
  292. @staticmethod
  293. def close_account(account: Account):
  294. """Close account"""
  295. account.status = AccountStatus.CLOSED.value
  296. db.session.commit()
  297. @staticmethod
  298. def update_account(account, **kwargs):
  299. """Update account fields"""
  300. account = db.session.merge(account)
  301. for field, value in kwargs.items():
  302. if hasattr(account, field):
  303. setattr(account, field, value)
  304. else:
  305. raise AttributeError(f"Invalid field: {field}")
  306. db.session.commit()
  307. return account
  308. @staticmethod
  309. def update_account_email(account: Account, email: str) -> Account:
  310. """Update account email"""
  311. account.email = email
  312. account_integrate = db.session.query(AccountIntegrate).filter_by(account_id=account.id).first()
  313. if account_integrate:
  314. db.session.delete(account_integrate)
  315. db.session.add(account)
  316. db.session.commit()
  317. return account
  318. @staticmethod
  319. def update_login_info(account: Account, *, ip_address: str):
  320. """Update last login time and ip"""
  321. account.last_login_at = naive_utc_now()
  322. account.last_login_ip = ip_address
  323. db.session.add(account)
  324. db.session.commit()
  325. @staticmethod
  326. def login(account: Account, *, ip_address: Optional[str] = None) -> TokenPair:
  327. if ip_address:
  328. AccountService.update_login_info(account=account, ip_address=ip_address)
  329. if account.status == AccountStatus.PENDING.value:
  330. account.status = AccountStatus.ACTIVE.value
  331. db.session.commit()
  332. access_token = AccountService.get_account_jwt_token(account=account)
  333. refresh_token = _generate_refresh_token()
  334. AccountService._store_refresh_token(refresh_token, account.id)
  335. return TokenPair(access_token=access_token, refresh_token=refresh_token)
  336. @staticmethod
  337. def logout(*, account: Account):
  338. refresh_token = redis_client.get(AccountService._get_account_refresh_token_key(account.id))
  339. if refresh_token:
  340. AccountService._delete_refresh_token(refresh_token.decode("utf-8"), account.id)
  341. @staticmethod
  342. def refresh_token(refresh_token: str) -> TokenPair:
  343. # Verify the refresh token
  344. account_id = redis_client.get(AccountService._get_refresh_token_key(refresh_token))
  345. if not account_id:
  346. raise ValueError("Invalid refresh token")
  347. account = AccountService.load_user(account_id.decode("utf-8"))
  348. if not account:
  349. raise ValueError("Invalid account")
  350. # Generate new access token and refresh token
  351. new_access_token = AccountService.get_account_jwt_token(account)
  352. new_refresh_token = _generate_refresh_token()
  353. AccountService._delete_refresh_token(refresh_token, account.id)
  354. AccountService._store_refresh_token(new_refresh_token, account.id)
  355. return TokenPair(access_token=new_access_token, refresh_token=new_refresh_token)
  356. @staticmethod
  357. def load_logged_in_account(*, account_id: str):
  358. return AccountService.load_user(account_id)
  359. @classmethod
  360. def send_reset_password_email(
  361. cls,
  362. account: Optional[Account] = None,
  363. email: Optional[str] = None,
  364. language: str = "en-US",
  365. is_allow_register: bool = False,
  366. ):
  367. account_email = account.email if account else email
  368. if account_email is None:
  369. raise ValueError("Email must be provided.")
  370. if cls.reset_password_rate_limiter.is_rate_limited(account_email):
  371. from controllers.console.auth.error import PasswordResetRateLimitExceededError
  372. raise PasswordResetRateLimitExceededError()
  373. code, token = cls.generate_reset_password_token(account_email, account)
  374. if account:
  375. send_reset_password_mail_task.delay(
  376. language=language,
  377. to=account_email,
  378. code=code,
  379. )
  380. else:
  381. send_reset_password_mail_task_when_account_not_exist.delay(
  382. language=language,
  383. to=account_email,
  384. is_allow_register=is_allow_register,
  385. )
  386. cls.reset_password_rate_limiter.increment_rate_limit(account_email)
  387. return token
  388. @classmethod
  389. def send_email_register_email(
  390. cls,
  391. account: Optional[Account] = None,
  392. email: Optional[str] = None,
  393. language: str = "en-US",
  394. ):
  395. account_email = account.email if account else email
  396. if account_email is None:
  397. raise ValueError("Email must be provided.")
  398. if cls.email_register_rate_limiter.is_rate_limited(account_email):
  399. from controllers.console.auth.error import EmailRegisterRateLimitExceededError
  400. raise EmailRegisterRateLimitExceededError()
  401. code, token = cls.generate_email_register_token(account_email)
  402. if account:
  403. send_email_register_mail_task_when_account_exist.delay(
  404. language=language,
  405. to=account_email,
  406. )
  407. else:
  408. send_email_register_mail_task.delay(
  409. language=language,
  410. to=account_email,
  411. code=code,
  412. )
  413. cls.email_register_rate_limiter.increment_rate_limit(account_email)
  414. return token
  415. @classmethod
  416. def send_change_email_email(
  417. cls,
  418. account: Optional[Account] = None,
  419. email: Optional[str] = None,
  420. old_email: Optional[str] = None,
  421. language: str = "en-US",
  422. phase: Optional[str] = None,
  423. ):
  424. account_email = account.email if account else email
  425. if account_email is None:
  426. raise ValueError("Email must be provided.")
  427. if not phase:
  428. raise ValueError("phase must be provided.")
  429. if cls.change_email_rate_limiter.is_rate_limited(account_email):
  430. from controllers.console.auth.error import EmailChangeRateLimitExceededError
  431. raise EmailChangeRateLimitExceededError()
  432. code, token = cls.generate_change_email_token(account_email, account, old_email=old_email)
  433. send_change_mail_task.delay(
  434. language=language,
  435. to=account_email,
  436. code=code,
  437. phase=phase,
  438. )
  439. cls.change_email_rate_limiter.increment_rate_limit(account_email)
  440. return token
  441. @classmethod
  442. def send_change_email_completed_notify_email(
  443. cls,
  444. account: Optional[Account] = None,
  445. email: Optional[str] = None,
  446. language: str = "en-US",
  447. ):
  448. account_email = account.email if account else email
  449. if account_email is None:
  450. raise ValueError("Email must be provided.")
  451. send_change_mail_completed_notification_task.delay(
  452. language=language,
  453. to=account_email,
  454. )
  455. @classmethod
  456. def send_owner_transfer_email(
  457. cls,
  458. account: Optional[Account] = None,
  459. email: Optional[str] = None,
  460. language: str = "en-US",
  461. workspace_name: Optional[str] = "",
  462. ):
  463. account_email = account.email if account else email
  464. if account_email is None:
  465. raise ValueError("Email must be provided.")
  466. if cls.owner_transfer_rate_limiter.is_rate_limited(account_email):
  467. from controllers.console.auth.error import OwnerTransferRateLimitExceededError
  468. raise OwnerTransferRateLimitExceededError()
  469. code, token = cls.generate_owner_transfer_token(account_email, account)
  470. workspace_name = workspace_name or ""
  471. send_owner_transfer_confirm_task.delay(
  472. language=language,
  473. to=account_email,
  474. code=code,
  475. workspace=workspace_name,
  476. )
  477. cls.owner_transfer_rate_limiter.increment_rate_limit(account_email)
  478. return token
  479. @classmethod
  480. def send_old_owner_transfer_notify_email(
  481. cls,
  482. account: Optional[Account] = None,
  483. email: Optional[str] = None,
  484. language: str = "en-US",
  485. workspace_name: Optional[str] = "",
  486. new_owner_email: str = "",
  487. ):
  488. account_email = account.email if account else email
  489. if account_email is None:
  490. raise ValueError("Email must be provided.")
  491. workspace_name = workspace_name or ""
  492. send_old_owner_transfer_notify_email_task.delay(
  493. language=language,
  494. to=account_email,
  495. workspace=workspace_name,
  496. new_owner_email=new_owner_email,
  497. )
  498. @classmethod
  499. def send_new_owner_transfer_notify_email(
  500. cls,
  501. account: Optional[Account] = None,
  502. email: Optional[str] = None,
  503. language: str = "en-US",
  504. workspace_name: Optional[str] = "",
  505. ):
  506. account_email = account.email if account else email
  507. if account_email is None:
  508. raise ValueError("Email must be provided.")
  509. workspace_name = workspace_name or ""
  510. send_new_owner_transfer_notify_email_task.delay(
  511. language=language,
  512. to=account_email,
  513. workspace=workspace_name,
  514. )
  515. @classmethod
  516. def generate_reset_password_token(
  517. cls,
  518. email: str,
  519. account: Optional[Account] = None,
  520. code: Optional[str] = None,
  521. additional_data: dict[str, Any] = {},
  522. ):
  523. if not code:
  524. code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])
  525. additional_data["code"] = code
  526. token = TokenManager.generate_token(
  527. account=account, email=email, token_type="reset_password", additional_data=additional_data
  528. )
  529. return code, token
  530. @classmethod
  531. def generate_email_register_token(
  532. cls,
  533. email: str,
  534. code: Optional[str] = None,
  535. additional_data: dict[str, Any] = {},
  536. ):
  537. if not code:
  538. code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])
  539. additional_data["code"] = code
  540. token = TokenManager.generate_token(email=email, token_type="email_register", additional_data=additional_data)
  541. return code, token
  542. @classmethod
  543. def generate_change_email_token(
  544. cls,
  545. email: str,
  546. account: Optional[Account] = None,
  547. code: Optional[str] = None,
  548. old_email: Optional[str] = None,
  549. additional_data: dict[str, Any] = {},
  550. ):
  551. if not code:
  552. code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])
  553. additional_data["code"] = code
  554. additional_data["old_email"] = old_email
  555. token = TokenManager.generate_token(
  556. account=account, email=email, token_type="change_email", additional_data=additional_data
  557. )
  558. return code, token
  559. @classmethod
  560. def generate_owner_transfer_token(
  561. cls,
  562. email: str,
  563. account: Optional[Account] = None,
  564. code: Optional[str] = None,
  565. additional_data: dict[str, Any] = {},
  566. ):
  567. if not code:
  568. code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])
  569. additional_data["code"] = code
  570. token = TokenManager.generate_token(
  571. account=account, email=email, token_type="owner_transfer", additional_data=additional_data
  572. )
  573. return code, token
  574. @classmethod
  575. def revoke_reset_password_token(cls, token: str):
  576. TokenManager.revoke_token(token, "reset_password")
  577. @classmethod
  578. def revoke_email_register_token(cls, token: str):
  579. TokenManager.revoke_token(token, "email_register")
  580. @classmethod
  581. def revoke_change_email_token(cls, token: str):
  582. TokenManager.revoke_token(token, "change_email")
  583. @classmethod
  584. def revoke_owner_transfer_token(cls, token: str):
  585. TokenManager.revoke_token(token, "owner_transfer")
  586. @classmethod
  587. def get_reset_password_data(cls, token: str) -> Optional[dict[str, Any]]:
  588. return TokenManager.get_token_data(token, "reset_password")
  589. @classmethod
  590. def get_email_register_data(cls, token: str) -> Optional[dict[str, Any]]:
  591. return TokenManager.get_token_data(token, "email_register")
  592. @classmethod
  593. def get_change_email_data(cls, token: str) -> Optional[dict[str, Any]]:
  594. return TokenManager.get_token_data(token, "change_email")
  595. @classmethod
  596. def get_owner_transfer_data(cls, token: str) -> Optional[dict[str, Any]]:
  597. return TokenManager.get_token_data(token, "owner_transfer")
  598. @classmethod
  599. def send_email_code_login_email(
  600. cls,
  601. account: Optional[Account] = None,
  602. email: Optional[str] = None,
  603. language: str = "en-US",
  604. ):
  605. email = account.email if account else email
  606. if email is None:
  607. raise ValueError("Email must be provided.")
  608. if cls.email_code_login_rate_limiter.is_rate_limited(email):
  609. from controllers.console.auth.error import EmailCodeLoginRateLimitExceededError
  610. raise EmailCodeLoginRateLimitExceededError()
  611. code = "".join([str(secrets.randbelow(exclusive_upper_bound=10)) for _ in range(6)])
  612. token = TokenManager.generate_token(
  613. account=account, email=email, token_type="email_code_login", additional_data={"code": code}
  614. )
  615. send_email_code_login_mail_task.delay(
  616. language=language,
  617. to=account.email if account else email,
  618. code=code,
  619. )
  620. cls.email_code_login_rate_limiter.increment_rate_limit(email)
  621. return token
  622. @classmethod
  623. def get_email_code_login_data(cls, token: str) -> Optional[dict[str, Any]]:
  624. return TokenManager.get_token_data(token, "email_code_login")
  625. @classmethod
  626. def revoke_email_code_login_token(cls, token: str):
  627. TokenManager.revoke_token(token, "email_code_login")
  628. @classmethod
  629. def get_user_through_email(cls, email: str):
  630. if dify_config.BILLING_ENABLED and BillingService.is_email_in_freeze(email):
  631. raise AccountRegisterError(
  632. description=(
  633. "This email account has been deleted within the past "
  634. "30 days and is temporarily unavailable for new account registration"
  635. )
  636. )
  637. account = db.session.query(Account).where(Account.email == email).first()
  638. if not account:
  639. return None
  640. if account.status == AccountStatus.BANNED.value:
  641. raise Unauthorized("Account is banned.")
  642. return account
  643. @classmethod
  644. def is_account_in_freeze(cls, email: str) -> bool:
  645. if dify_config.BILLING_ENABLED and BillingService.is_email_in_freeze(email):
  646. return True
  647. return False
  648. @staticmethod
  649. @redis_fallback(default_return=None)
  650. def add_login_error_rate_limit(email: str):
  651. key = f"login_error_rate_limit:{email}"
  652. count = redis_client.get(key)
  653. if count is None:
  654. count = 0
  655. count = int(count) + 1
  656. redis_client.setex(key, dify_config.LOGIN_LOCKOUT_DURATION, count)
  657. @staticmethod
  658. @redis_fallback(default_return=False)
  659. def is_login_error_rate_limit(email: str) -> bool:
  660. key = f"login_error_rate_limit:{email}"
  661. count = redis_client.get(key)
  662. if count is None:
  663. return False
  664. count = int(count)
  665. if count > AccountService.LOGIN_MAX_ERROR_LIMITS:
  666. return True
  667. return False
  668. @staticmethod
  669. @redis_fallback(default_return=None)
  670. def reset_login_error_rate_limit(email: str):
  671. key = f"login_error_rate_limit:{email}"
  672. redis_client.delete(key)
  673. @staticmethod
  674. @redis_fallback(default_return=None)
  675. def add_forgot_password_error_rate_limit(email: str):
  676. key = f"forgot_password_error_rate_limit:{email}"
  677. count = redis_client.get(key)
  678. if count is None:
  679. count = 0
  680. count = int(count) + 1
  681. redis_client.setex(key, dify_config.FORGOT_PASSWORD_LOCKOUT_DURATION, count)
  682. @staticmethod
  683. @redis_fallback(default_return=None)
  684. def add_email_register_error_rate_limit(email: str) -> None:
  685. key = f"email_register_error_rate_limit:{email}"
  686. count = redis_client.get(key)
  687. if count is None:
  688. count = 0
  689. count = int(count) + 1
  690. redis_client.setex(key, dify_config.EMAIL_REGISTER_LOCKOUT_DURATION, count)
  691. @staticmethod
  692. @redis_fallback(default_return=False)
  693. def is_forgot_password_error_rate_limit(email: str) -> bool:
  694. key = f"forgot_password_error_rate_limit:{email}"
  695. count = redis_client.get(key)
  696. if count is None:
  697. return False
  698. count = int(count)
  699. if count > AccountService.FORGOT_PASSWORD_MAX_ERROR_LIMITS:
  700. return True
  701. return False
  702. @staticmethod
  703. @redis_fallback(default_return=None)
  704. def reset_forgot_password_error_rate_limit(email: str):
  705. key = f"forgot_password_error_rate_limit:{email}"
  706. redis_client.delete(key)
  707. @staticmethod
  708. @redis_fallback(default_return=False)
  709. def is_email_register_error_rate_limit(email: str) -> bool:
  710. key = f"email_register_error_rate_limit:{email}"
  711. count = redis_client.get(key)
  712. if count is None:
  713. return False
  714. count = int(count)
  715. if count > AccountService.EMAIL_REGISTER_MAX_ERROR_LIMITS:
  716. return True
  717. return False
  718. @staticmethod
  719. @redis_fallback(default_return=None)
  720. def reset_email_register_error_rate_limit(email: str):
  721. key = f"email_register_error_rate_limit:{email}"
  722. redis_client.delete(key)
  723. @staticmethod
  724. @redis_fallback(default_return=None)
  725. def add_change_email_error_rate_limit(email: str):
  726. key = f"change_email_error_rate_limit:{email}"
  727. count = redis_client.get(key)
  728. if count is None:
  729. count = 0
  730. count = int(count) + 1
  731. redis_client.setex(key, dify_config.CHANGE_EMAIL_LOCKOUT_DURATION, count)
  732. @staticmethod
  733. @redis_fallback(default_return=False)
  734. def is_change_email_error_rate_limit(email: str) -> bool:
  735. key = f"change_email_error_rate_limit:{email}"
  736. count = redis_client.get(key)
  737. if count is None:
  738. return False
  739. count = int(count)
  740. if count > AccountService.CHANGE_EMAIL_MAX_ERROR_LIMITS:
  741. return True
  742. return False
  743. @staticmethod
  744. @redis_fallback(default_return=None)
  745. def reset_change_email_error_rate_limit(email: str):
  746. key = f"change_email_error_rate_limit:{email}"
  747. redis_client.delete(key)
  748. @staticmethod
  749. @redis_fallback(default_return=None)
  750. def add_owner_transfer_error_rate_limit(email: str):
  751. key = f"owner_transfer_error_rate_limit:{email}"
  752. count = redis_client.get(key)
  753. if count is None:
  754. count = 0
  755. count = int(count) + 1
  756. redis_client.setex(key, dify_config.OWNER_TRANSFER_LOCKOUT_DURATION, count)
  757. @staticmethod
  758. @redis_fallback(default_return=False)
  759. def is_owner_transfer_error_rate_limit(email: str) -> bool:
  760. key = f"owner_transfer_error_rate_limit:{email}"
  761. count = redis_client.get(key)
  762. if count is None:
  763. return False
  764. count = int(count)
  765. if count > AccountService.OWNER_TRANSFER_MAX_ERROR_LIMITS:
  766. return True
  767. return False
  768. @staticmethod
  769. @redis_fallback(default_return=None)
  770. def reset_owner_transfer_error_rate_limit(email: str):
  771. key = f"owner_transfer_error_rate_limit:{email}"
  772. redis_client.delete(key)
  773. @staticmethod
  774. @redis_fallback(default_return=False)
  775. def is_email_send_ip_limit(ip_address: str):
  776. minute_key = f"email_send_ip_limit_minute:{ip_address}"
  777. freeze_key = f"email_send_ip_limit_freeze:{ip_address}"
  778. hour_limit_key = f"email_send_ip_limit_hour:{ip_address}"
  779. # check ip is frozen
  780. if redis_client.get(freeze_key):
  781. return True
  782. # check current minute count
  783. current_minute_count = redis_client.get(minute_key)
  784. if current_minute_count is None:
  785. current_minute_count = 0
  786. current_minute_count = int(current_minute_count)
  787. # check current hour count
  788. if current_minute_count > dify_config.EMAIL_SEND_IP_LIMIT_PER_MINUTE:
  789. hour_limit_count = redis_client.get(hour_limit_key)
  790. if hour_limit_count is None:
  791. hour_limit_count = 0
  792. hour_limit_count = int(hour_limit_count)
  793. if hour_limit_count >= 1:
  794. redis_client.setex(freeze_key, 60 * 60, 1)
  795. return True
  796. else:
  797. redis_client.setex(hour_limit_key, 60 * 10, hour_limit_count + 1) # first time limit 10 minutes
  798. # add hour limit count
  799. redis_client.incr(hour_limit_key)
  800. redis_client.expire(hour_limit_key, 60 * 60)
  801. return True
  802. redis_client.setex(minute_key, 60, current_minute_count + 1)
  803. redis_client.expire(minute_key, 60)
  804. return False
  805. @staticmethod
  806. def check_email_unique(email: str) -> bool:
  807. return db.session.query(Account).filter_by(email=email).first() is None
  808. class TenantService:
  809. @staticmethod
  810. def create_tenant(name: str, is_setup: Optional[bool] = False, is_from_dashboard: Optional[bool] = False) -> Tenant:
  811. """Create tenant"""
  812. if (
  813. not FeatureService.get_system_features().is_allow_create_workspace
  814. and not is_setup
  815. and not is_from_dashboard
  816. ):
  817. from controllers.console.error import NotAllowedCreateWorkspace
  818. raise NotAllowedCreateWorkspace()
  819. tenant = Tenant(name=name)
  820. db.session.add(tenant)
  821. db.session.commit()
  822. plugin_upgrade_strategy = TenantPluginAutoUpgradeStrategy(
  823. tenant_id=tenant.id,
  824. strategy_setting=TenantPluginAutoUpgradeStrategy.StrategySetting.FIX_ONLY,
  825. upgrade_time_of_day=0,
  826. upgrade_mode=TenantPluginAutoUpgradeStrategy.UpgradeMode.EXCLUDE,
  827. exclude_plugins=[],
  828. include_plugins=[],
  829. )
  830. db.session.add(plugin_upgrade_strategy)
  831. db.session.commit()
  832. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  833. db.session.commit()
  834. return tenant
  835. @staticmethod
  836. def create_owner_tenant_if_not_exist(
  837. account: Account, name: Optional[str] = None, is_setup: Optional[bool] = False
  838. ):
  839. """Check if user have a workspace or not"""
  840. available_ta = (
  841. db.session.query(TenantAccountJoin)
  842. .filter_by(account_id=account.id)
  843. .order_by(TenantAccountJoin.id.asc())
  844. .first()
  845. )
  846. if available_ta:
  847. return
  848. """Create owner tenant if not exist"""
  849. if not FeatureService.get_system_features().is_allow_create_workspace and not is_setup:
  850. raise WorkSpaceNotAllowedCreateError()
  851. workspaces = FeatureService.get_system_features().license.workspaces
  852. if not workspaces.is_available():
  853. raise WorkspacesLimitExceededError()
  854. if name:
  855. tenant = TenantService.create_tenant(name=name, is_setup=is_setup)
  856. else:
  857. tenant = TenantService.create_tenant(name=f"{account.name}'s Workspace", is_setup=is_setup)
  858. TenantService.create_tenant_member(tenant, account, role="owner")
  859. account.current_tenant = tenant
  860. db.session.commit()
  861. tenant_was_created.send(tenant)
  862. @staticmethod
  863. def create_tenant_member(tenant: Tenant, account: Account, role: str = "normal") -> TenantAccountJoin:
  864. """Create tenant member"""
  865. if role == TenantAccountRole.OWNER.value:
  866. if TenantService.has_roles(tenant, [TenantAccountRole.OWNER]):
  867. logger.error("Tenant %s has already an owner.", tenant.id)
  868. raise Exception("Tenant already has an owner.")
  869. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  870. if ta:
  871. ta.role = role
  872. else:
  873. ta = TenantAccountJoin(tenant_id=tenant.id, account_id=account.id, role=role)
  874. db.session.add(ta)
  875. db.session.commit()
  876. return ta
  877. @staticmethod
  878. def get_join_tenants(account: Account) -> list[Tenant]:
  879. """Get account join tenants"""
  880. return (
  881. db.session.query(Tenant)
  882. .join(TenantAccountJoin, Tenant.id == TenantAccountJoin.tenant_id)
  883. .where(TenantAccountJoin.account_id == account.id, Tenant.status == TenantStatus.NORMAL)
  884. .all()
  885. )
  886. @staticmethod
  887. def get_current_tenant_by_account(account: Account):
  888. """Get tenant by account and add the role"""
  889. tenant = account.current_tenant
  890. if not tenant:
  891. raise TenantNotFoundError("Tenant not found.")
  892. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  893. if ta:
  894. tenant.role = ta.role
  895. else:
  896. raise TenantNotFoundError("Tenant not found for the account.")
  897. return tenant
  898. @staticmethod
  899. def switch_tenant(account: Account, tenant_id: Optional[str] = None):
  900. """Switch the current workspace for the account"""
  901. # Ensure tenant_id is provided
  902. if tenant_id is None:
  903. raise ValueError("Tenant ID must be provided.")
  904. tenant_account_join = (
  905. db.session.query(TenantAccountJoin)
  906. .join(Tenant, TenantAccountJoin.tenant_id == Tenant.id)
  907. .where(
  908. TenantAccountJoin.account_id == account.id,
  909. TenantAccountJoin.tenant_id == tenant_id,
  910. Tenant.status == TenantStatus.NORMAL,
  911. )
  912. .first()
  913. )
  914. if not tenant_account_join:
  915. raise AccountNotLinkTenantError("Tenant not found or account is not a member of the tenant.")
  916. else:
  917. db.session.query(TenantAccountJoin).where(
  918. TenantAccountJoin.account_id == account.id, TenantAccountJoin.tenant_id != tenant_id
  919. ).update({"current": False})
  920. tenant_account_join.current = True
  921. # Set the current tenant for the account
  922. account.set_tenant_id(tenant_account_join.tenant_id)
  923. db.session.commit()
  924. @staticmethod
  925. def get_tenant_members(tenant: Tenant) -> list[Account]:
  926. """Get tenant members"""
  927. query = (
  928. db.session.query(Account, TenantAccountJoin.role)
  929. .select_from(Account)
  930. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  931. .where(TenantAccountJoin.tenant_id == tenant.id)
  932. )
  933. # Initialize an empty list to store the updated accounts
  934. updated_accounts = []
  935. for account, role in query:
  936. account.role = role
  937. updated_accounts.append(account)
  938. return updated_accounts
  939. @staticmethod
  940. def get_dataset_operator_members(tenant: Tenant) -> list[Account]:
  941. """Get dataset admin members"""
  942. query = (
  943. db.session.query(Account, TenantAccountJoin.role)
  944. .select_from(Account)
  945. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  946. .where(TenantAccountJoin.tenant_id == tenant.id)
  947. .where(TenantAccountJoin.role == "dataset_operator")
  948. )
  949. # Initialize an empty list to store the updated accounts
  950. updated_accounts = []
  951. for account, role in query:
  952. account.role = role
  953. updated_accounts.append(account)
  954. return updated_accounts
  955. @staticmethod
  956. def has_roles(tenant: Tenant, roles: list[TenantAccountRole]) -> bool:
  957. """Check if user has any of the given roles for a tenant"""
  958. if not all(isinstance(role, TenantAccountRole) for role in roles):
  959. raise ValueError("all roles must be TenantAccountRole")
  960. return (
  961. db.session.query(TenantAccountJoin)
  962. .where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.role.in_([role.value for role in roles]))
  963. .first()
  964. is not None
  965. )
  966. @staticmethod
  967. def get_user_role(account: Account, tenant: Tenant) -> Optional[TenantAccountRole]:
  968. """Get the role of the current account for a given tenant"""
  969. join = (
  970. db.session.query(TenantAccountJoin)
  971. .where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == account.id)
  972. .first()
  973. )
  974. return TenantAccountRole(join.role) if join else None
  975. @staticmethod
  976. def get_tenant_count() -> int:
  977. """Get tenant count"""
  978. return cast(int, db.session.query(func.count(Tenant.id)).scalar())
  979. @staticmethod
  980. def check_member_permission(tenant: Tenant, operator: Account, member: Account | None, action: str):
  981. """Check member permission"""
  982. perms = {
  983. "add": [TenantAccountRole.OWNER, TenantAccountRole.ADMIN],
  984. "remove": [TenantAccountRole.OWNER],
  985. "update": [TenantAccountRole.OWNER],
  986. }
  987. if action not in {"add", "remove", "update"}:
  988. raise InvalidActionError("Invalid action.")
  989. if member:
  990. if operator.id == member.id:
  991. raise CannotOperateSelfError("Cannot operate self.")
  992. ta_operator = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=operator.id).first()
  993. if not ta_operator or ta_operator.role not in perms[action]:
  994. raise NoPermissionError(f"No permission to {action} member.")
  995. @staticmethod
  996. def remove_member_from_tenant(tenant: Tenant, account: Account, operator: Account):
  997. """Remove member from tenant"""
  998. if operator.id == account.id:
  999. raise CannotOperateSelfError("Cannot operate self.")
  1000. TenantService.check_member_permission(tenant, operator, account, "remove")
  1001. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  1002. if not ta:
  1003. raise MemberNotInTenantError("Member not in tenant.")
  1004. db.session.delete(ta)
  1005. db.session.commit()
  1006. @staticmethod
  1007. def update_member_role(tenant: Tenant, member: Account, new_role: str, operator: Account):
  1008. """Update member role"""
  1009. TenantService.check_member_permission(tenant, operator, member, "update")
  1010. target_member_join = (
  1011. db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=member.id).first()
  1012. )
  1013. if not target_member_join:
  1014. raise MemberNotInTenantError("Member not in tenant.")
  1015. if target_member_join.role == new_role:
  1016. raise RoleAlreadyAssignedError("The provided role is already assigned to the member.")
  1017. if new_role == "owner":
  1018. # Find the current owner and change their role to 'admin'
  1019. current_owner_join = (
  1020. db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, role="owner").first()
  1021. )
  1022. if current_owner_join:
  1023. current_owner_join.role = "admin"
  1024. # Update the role of the target member
  1025. target_member_join.role = new_role
  1026. db.session.commit()
  1027. @staticmethod
  1028. def get_custom_config(tenant_id: str):
  1029. tenant = db.get_or_404(Tenant, tenant_id)
  1030. return tenant.custom_config_dict
  1031. @staticmethod
  1032. def is_owner(account: Account, tenant: Tenant) -> bool:
  1033. return TenantService.get_user_role(account, tenant) == TenantAccountRole.OWNER
  1034. @staticmethod
  1035. def is_member(account: Account, tenant: Tenant) -> bool:
  1036. """Check if the account is a member of the tenant"""
  1037. return TenantService.get_user_role(account, tenant) is not None
  1038. class RegisterService:
  1039. @classmethod
  1040. def _get_invitation_token_key(cls, token: str) -> str:
  1041. return f"member_invite:token:{token}"
  1042. @classmethod
  1043. def setup(cls, email: str, name: str, password: str, ip_address: str):
  1044. """
  1045. Setup dify
  1046. :param email: email
  1047. :param name: username
  1048. :param password: password
  1049. :param ip_address: ip address
  1050. """
  1051. try:
  1052. # Register
  1053. account = AccountService.create_account(
  1054. email=email,
  1055. name=name,
  1056. interface_language=languages[0],
  1057. password=password,
  1058. is_setup=True,
  1059. )
  1060. account.last_login_ip = ip_address
  1061. account.initialized_at = naive_utc_now()
  1062. TenantService.create_owner_tenant_if_not_exist(account=account, is_setup=True)
  1063. dify_setup = DifySetup(version=dify_config.project.version)
  1064. db.session.add(dify_setup)
  1065. db.session.commit()
  1066. except Exception as e:
  1067. db.session.query(DifySetup).delete()
  1068. db.session.query(TenantAccountJoin).delete()
  1069. db.session.query(Account).delete()
  1070. db.session.query(Tenant).delete()
  1071. db.session.commit()
  1072. logger.exception("Setup account failed, email: %s, name: %s", email, name)
  1073. raise ValueError(f"Setup failed: {e}")
  1074. @classmethod
  1075. def register(
  1076. cls,
  1077. email,
  1078. name,
  1079. password: Optional[str] = None,
  1080. open_id: Optional[str] = None,
  1081. provider: Optional[str] = None,
  1082. language: Optional[str] = None,
  1083. status: Optional[AccountStatus] = None,
  1084. is_setup: Optional[bool] = False,
  1085. create_workspace_required: Optional[bool] = True,
  1086. ) -> Account:
  1087. db.session.begin_nested()
  1088. """Register account"""
  1089. try:
  1090. account = AccountService.create_account(
  1091. email=email,
  1092. name=name,
  1093. interface_language=language or languages[0],
  1094. password=password,
  1095. is_setup=is_setup,
  1096. )
  1097. account.status = AccountStatus.ACTIVE.value if not status else status.value
  1098. account.initialized_at = naive_utc_now()
  1099. if open_id is not None and provider is not None:
  1100. AccountService.link_account_integrate(provider, open_id, account)
  1101. if (
  1102. FeatureService.get_system_features().is_allow_create_workspace
  1103. and create_workspace_required
  1104. and FeatureService.get_system_features().license.workspaces.is_available()
  1105. ):
  1106. tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  1107. TenantService.create_tenant_member(tenant, account, role="owner")
  1108. account.current_tenant = tenant
  1109. tenant_was_created.send(tenant)
  1110. db.session.commit()
  1111. except WorkSpaceNotAllowedCreateError:
  1112. db.session.rollback()
  1113. logger.exception("Register failed")
  1114. raise AccountRegisterError("Workspace is not allowed to create.")
  1115. except AccountRegisterError as are:
  1116. db.session.rollback()
  1117. logger.exception("Register failed")
  1118. raise are
  1119. except Exception as e:
  1120. db.session.rollback()
  1121. logger.exception("Register failed")
  1122. raise AccountRegisterError(f"Registration failed: {e}") from e
  1123. return account
  1124. @classmethod
  1125. def invite_new_member(
  1126. cls, tenant: Tenant, email: str, language: str, role: str = "normal", inviter: Account | None = None
  1127. ) -> str:
  1128. if not inviter:
  1129. raise ValueError("Inviter is required")
  1130. """Invite new member"""
  1131. with Session(db.engine) as session:
  1132. account = session.query(Account).filter_by(email=email).first()
  1133. if not account:
  1134. TenantService.check_member_permission(tenant, inviter, None, "add")
  1135. name = email.split("@")[0]
  1136. account = cls.register(
  1137. email=email, name=name, language=language, status=AccountStatus.PENDING, is_setup=True
  1138. )
  1139. # Create new tenant member for invited tenant
  1140. TenantService.create_tenant_member(tenant, account, role)
  1141. TenantService.switch_tenant(account, tenant.id)
  1142. else:
  1143. TenantService.check_member_permission(tenant, inviter, account, "add")
  1144. ta = db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id, account_id=account.id).first()
  1145. if not ta:
  1146. TenantService.create_tenant_member(tenant, account, role)
  1147. # Support resend invitation email when the account is pending status
  1148. if account.status != AccountStatus.PENDING.value:
  1149. raise AccountAlreadyInTenantError("Account already in tenant.")
  1150. token = cls.generate_invite_token(tenant, account)
  1151. language = account.interface_language or "en-US"
  1152. # send email
  1153. send_invite_member_mail_task.delay(
  1154. language=language,
  1155. to=email,
  1156. token=token,
  1157. inviter_name=inviter.name if inviter else "Dify",
  1158. workspace_name=tenant.name,
  1159. )
  1160. return token
  1161. @classmethod
  1162. def generate_invite_token(cls, tenant: Tenant, account: Account) -> str:
  1163. token = str(uuid.uuid4())
  1164. invitation_data = {
  1165. "account_id": account.id,
  1166. "email": account.email,
  1167. "workspace_id": tenant.id,
  1168. }
  1169. expiry_hours = dify_config.INVITE_EXPIRY_HOURS
  1170. redis_client.setex(cls._get_invitation_token_key(token), expiry_hours * 60 * 60, json.dumps(invitation_data))
  1171. return token
  1172. @classmethod
  1173. def is_valid_invite_token(cls, token: str) -> bool:
  1174. data = redis_client.get(cls._get_invitation_token_key(token))
  1175. return data is not None
  1176. @classmethod
  1177. def revoke_token(cls, workspace_id: str, email: str, token: str):
  1178. if workspace_id and email:
  1179. email_hash = sha256(email.encode()).hexdigest()
  1180. cache_key = f"member_invite_token:{workspace_id}, {email_hash}:{token}"
  1181. redis_client.delete(cache_key)
  1182. else:
  1183. redis_client.delete(cls._get_invitation_token_key(token))
  1184. @classmethod
  1185. def get_invitation_if_token_valid(
  1186. cls, workspace_id: Optional[str], email: str, token: str
  1187. ) -> Optional[dict[str, Any]]:
  1188. invitation_data = cls._get_invitation_by_token(token, workspace_id, email)
  1189. if not invitation_data:
  1190. return None
  1191. tenant = (
  1192. db.session.query(Tenant)
  1193. .where(Tenant.id == invitation_data["workspace_id"], Tenant.status == "normal")
  1194. .first()
  1195. )
  1196. if not tenant:
  1197. return None
  1198. tenant_account = (
  1199. db.session.query(Account, TenantAccountJoin.role)
  1200. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  1201. .where(Account.email == invitation_data["email"], TenantAccountJoin.tenant_id == tenant.id)
  1202. .first()
  1203. )
  1204. if not tenant_account:
  1205. return None
  1206. account = tenant_account[0]
  1207. if not account:
  1208. return None
  1209. if invitation_data["account_id"] != str(account.id):
  1210. return None
  1211. return {
  1212. "account": account,
  1213. "data": invitation_data,
  1214. "tenant": tenant,
  1215. }
  1216. @classmethod
  1217. def _get_invitation_by_token(
  1218. cls, token: str, workspace_id: Optional[str] = None, email: Optional[str] = None
  1219. ) -> Optional[dict[str, str]]:
  1220. if workspace_id is not None and email is not None:
  1221. email_hash = sha256(email.encode()).hexdigest()
  1222. cache_key = f"member_invite_token:{workspace_id}, {email_hash}:{token}"
  1223. account_id = redis_client.get(cache_key)
  1224. if not account_id:
  1225. return None
  1226. return {
  1227. "account_id": account_id.decode("utf-8"),
  1228. "email": email,
  1229. "workspace_id": workspace_id,
  1230. }
  1231. else:
  1232. data = redis_client.get(cls._get_invitation_token_key(token))
  1233. if not data:
  1234. return None
  1235. invitation: dict = json.loads(data)
  1236. return invitation
  1237. def _generate_refresh_token(length: int = 64):
  1238. token = secrets.token_hex(length)
  1239. return token