account_service.py 53 KB

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