您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

account_service.py 54KB

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