account_service.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. import base64
  2. import json
  3. import logging
  4. import secrets
  5. import uuid
  6. from datetime import datetime, timedelta, timezone
  7. from hashlib import sha256
  8. from typing import Any, Optional
  9. from pydantic import BaseModel
  10. from sqlalchemy import func
  11. from werkzeug.exceptions import Unauthorized
  12. from configs import dify_config
  13. from constants.languages import language_timezone_mapping, languages
  14. from events.tenant_event import tenant_was_created
  15. from extensions.ext_database import db
  16. from extensions.ext_redis import redis_client
  17. from libs.helper import RateLimiter, TokenManager
  18. from libs.passport import PassportService
  19. from libs.password import compare_password, hash_password, valid_password
  20. from libs.rsa import generate_key_pair
  21. from models.account import (
  22. Account,
  23. AccountIntegrate,
  24. AccountStatus,
  25. Tenant,
  26. TenantAccountJoin,
  27. TenantAccountJoinRole,
  28. TenantAccountRole,
  29. TenantStatus,
  30. )
  31. from models.model import DifySetup
  32. from services.errors.account import (
  33. AccountAlreadyInTenantError,
  34. AccountLoginError,
  35. AccountNotLinkTenantError,
  36. AccountRegisterError,
  37. CannotOperateSelfError,
  38. CurrentPasswordIncorrectError,
  39. InvalidActionError,
  40. LinkAccountIntegrateError,
  41. MemberNotInTenantError,
  42. NoPermissionError,
  43. RateLimitExceededError,
  44. RoleAlreadyAssignedError,
  45. TenantNotFoundError,
  46. )
  47. from tasks.mail_invite_member_task import send_invite_member_mail_task
  48. from tasks.mail_reset_password_task import send_reset_password_mail_task
  49. class TokenPair(BaseModel):
  50. access_token: str
  51. refresh_token: str
  52. REFRESH_TOKEN_PREFIX = "refresh_token:"
  53. ACCOUNT_REFRESH_TOKEN_PREFIX = "account_refresh_token:"
  54. REFRESH_TOKEN_EXPIRY = timedelta(days=30)
  55. class AccountService:
  56. reset_password_rate_limiter = RateLimiter(prefix="reset_password_rate_limit", max_attempts=5, time_window=60 * 60)
  57. @staticmethod
  58. def _get_refresh_token_key(refresh_token: str) -> str:
  59. return f"{REFRESH_TOKEN_PREFIX}{refresh_token}"
  60. @staticmethod
  61. def _get_account_refresh_token_key(account_id: str) -> str:
  62. return f"{ACCOUNT_REFRESH_TOKEN_PREFIX}{account_id}"
  63. @staticmethod
  64. def _store_refresh_token(refresh_token: str, account_id: str) -> None:
  65. redis_client.setex(AccountService._get_refresh_token_key(refresh_token), REFRESH_TOKEN_EXPIRY, account_id)
  66. redis_client.setex(
  67. AccountService._get_account_refresh_token_key(account_id), REFRESH_TOKEN_EXPIRY, refresh_token
  68. )
  69. @staticmethod
  70. def _delete_refresh_token(refresh_token: str, account_id: str) -> None:
  71. redis_client.delete(AccountService._get_refresh_token_key(refresh_token))
  72. redis_client.delete(AccountService._get_account_refresh_token_key(account_id))
  73. @staticmethod
  74. def load_user(user_id: str) -> None | Account:
  75. account = Account.query.filter_by(id=user_id).first()
  76. if not account:
  77. return None
  78. if account.status in {AccountStatus.BANNED.value, AccountStatus.CLOSED.value}:
  79. raise Unauthorized("Account is banned or closed.")
  80. current_tenant = TenantAccountJoin.query.filter_by(account_id=account.id, current=True).first()
  81. if current_tenant:
  82. account.current_tenant_id = current_tenant.tenant_id
  83. else:
  84. available_ta = (
  85. TenantAccountJoin.query.filter_by(account_id=account.id).order_by(TenantAccountJoin.id.asc()).first()
  86. )
  87. if not available_ta:
  88. return None
  89. account.current_tenant_id = available_ta.tenant_id
  90. available_ta.current = True
  91. db.session.commit()
  92. if datetime.now(timezone.utc).replace(tzinfo=None) - account.last_active_at > timedelta(minutes=10):
  93. account.last_active_at = datetime.now(timezone.utc).replace(tzinfo=None)
  94. db.session.commit()
  95. return account
  96. @staticmethod
  97. def get_account_jwt_token(account: Account) -> str:
  98. exp_dt = datetime.now(timezone.utc) + timedelta(minutes=dify_config.ACCESS_TOKEN_EXPIRE_MINUTES)
  99. exp = int(exp_dt.timestamp())
  100. payload = {
  101. "user_id": account.id,
  102. "exp": exp,
  103. "iss": dify_config.EDITION,
  104. "sub": "Console API Passport",
  105. }
  106. token = PassportService().issue(payload)
  107. return token
  108. @staticmethod
  109. def authenticate(email: str, password: str) -> Account:
  110. """authenticate account with email and password"""
  111. account = Account.query.filter_by(email=email).first()
  112. if not account:
  113. raise AccountLoginError("Invalid email or password.")
  114. if account.status in {AccountStatus.BANNED.value, AccountStatus.CLOSED.value}:
  115. raise AccountLoginError("Account is banned or closed.")
  116. if account.status == AccountStatus.PENDING.value:
  117. account.status = AccountStatus.ACTIVE.value
  118. account.initialized_at = datetime.now(timezone.utc).replace(tzinfo=None)
  119. db.session.commit()
  120. if account.password is None or not compare_password(password, account.password, account.password_salt):
  121. raise AccountLoginError("Invalid email or password.")
  122. return account
  123. @staticmethod
  124. def update_account_password(account, password, new_password):
  125. """update account password"""
  126. if account.password and not compare_password(password, account.password, account.password_salt):
  127. raise CurrentPasswordIncorrectError("Current password is incorrect.")
  128. # may be raised
  129. valid_password(new_password)
  130. # generate password salt
  131. salt = secrets.token_bytes(16)
  132. base64_salt = base64.b64encode(salt).decode()
  133. # encrypt password with salt
  134. password_hashed = hash_password(new_password, salt)
  135. base64_password_hashed = base64.b64encode(password_hashed).decode()
  136. account.password = base64_password_hashed
  137. account.password_salt = base64_salt
  138. db.session.commit()
  139. return account
  140. @staticmethod
  141. def create_account(
  142. email: str, name: str, interface_language: str, password: Optional[str] = None, interface_theme: str = "light"
  143. ) -> Account:
  144. """create account"""
  145. account = Account()
  146. account.email = email
  147. account.name = name
  148. if password:
  149. # generate password salt
  150. salt = secrets.token_bytes(16)
  151. base64_salt = base64.b64encode(salt).decode()
  152. # encrypt password with salt
  153. password_hashed = hash_password(password, salt)
  154. base64_password_hashed = base64.b64encode(password_hashed).decode()
  155. account.password = base64_password_hashed
  156. account.password_salt = base64_salt
  157. account.interface_language = interface_language
  158. account.interface_theme = interface_theme
  159. # Set timezone based on language
  160. account.timezone = language_timezone_mapping.get(interface_language, "UTC")
  161. db.session.add(account)
  162. db.session.commit()
  163. return account
  164. @staticmethod
  165. def link_account_integrate(provider: str, open_id: str, account: Account) -> None:
  166. """Link account integrate"""
  167. try:
  168. # Query whether there is an existing binding record for the same provider
  169. account_integrate: Optional[AccountIntegrate] = AccountIntegrate.query.filter_by(
  170. account_id=account.id, provider=provider
  171. ).first()
  172. if account_integrate:
  173. # If it exists, update the record
  174. account_integrate.open_id = open_id
  175. account_integrate.encrypted_token = "" # todo
  176. account_integrate.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
  177. else:
  178. # If it does not exist, create a new record
  179. account_integrate = AccountIntegrate(
  180. account_id=account.id, provider=provider, open_id=open_id, encrypted_token=""
  181. )
  182. db.session.add(account_integrate)
  183. db.session.commit()
  184. logging.info(f"Account {account.id} linked {provider} account {open_id}.")
  185. except Exception as e:
  186. logging.exception(f"Failed to link {provider} account {open_id} to Account {account.id}")
  187. raise LinkAccountIntegrateError("Failed to link account.") from e
  188. @staticmethod
  189. def close_account(account: Account) -> None:
  190. """Close account"""
  191. account.status = AccountStatus.CLOSED.value
  192. db.session.commit()
  193. @staticmethod
  194. def update_account(account, **kwargs):
  195. """Update account fields"""
  196. for field, value in kwargs.items():
  197. if hasattr(account, field):
  198. setattr(account, field, value)
  199. else:
  200. raise AttributeError(f"Invalid field: {field}")
  201. db.session.commit()
  202. return account
  203. @staticmethod
  204. def update_login_info(account: Account, *, ip_address: str) -> None:
  205. """Update last login time and ip"""
  206. account.last_login_at = datetime.now(timezone.utc).replace(tzinfo=None)
  207. account.last_login_ip = ip_address
  208. db.session.add(account)
  209. db.session.commit()
  210. @staticmethod
  211. def login(account: Account, *, ip_address: Optional[str] = None) -> TokenPair:
  212. if ip_address:
  213. AccountService.update_login_info(account=account, ip_address=ip_address)
  214. access_token = AccountService.get_account_jwt_token(account=account)
  215. refresh_token = _generate_refresh_token()
  216. AccountService._store_refresh_token(refresh_token, account.id)
  217. return TokenPair(access_token=access_token, refresh_token=refresh_token)
  218. @staticmethod
  219. def logout(*, account: Account) -> None:
  220. refresh_token = redis_client.get(AccountService._get_account_refresh_token_key(account.id))
  221. if refresh_token:
  222. AccountService._delete_refresh_token(refresh_token.decode("utf-8"), account.id)
  223. @staticmethod
  224. def refresh_token(refresh_token: str) -> TokenPair:
  225. # Verify the refresh token
  226. account_id = redis_client.get(AccountService._get_refresh_token_key(refresh_token))
  227. if not account_id:
  228. raise ValueError("Invalid refresh token")
  229. account = AccountService.load_user(account_id.decode("utf-8"))
  230. if not account:
  231. raise ValueError("Invalid account")
  232. # Generate new access token and refresh token
  233. new_access_token = AccountService.get_account_jwt_token(account)
  234. new_refresh_token = _generate_refresh_token()
  235. AccountService._delete_refresh_token(refresh_token, account.id)
  236. AccountService._store_refresh_token(new_refresh_token, account.id)
  237. return TokenPair(access_token=new_access_token, refresh_token=new_refresh_token)
  238. @staticmethod
  239. def load_logged_in_account(*, account_id: str):
  240. return AccountService.load_user(account_id)
  241. @classmethod
  242. def send_reset_password_email(cls, account):
  243. if cls.reset_password_rate_limiter.is_rate_limited(account.email):
  244. raise RateLimitExceededError(f"Rate limit exceeded for email: {account.email}. Please try again later.")
  245. token = TokenManager.generate_token(account, "reset_password")
  246. send_reset_password_mail_task.delay(language=account.interface_language, to=account.email, token=token)
  247. cls.reset_password_rate_limiter.increment_rate_limit(account.email)
  248. return token
  249. @classmethod
  250. def revoke_reset_password_token(cls, token: str):
  251. TokenManager.revoke_token(token, "reset_password")
  252. @classmethod
  253. def get_reset_password_data(cls, token: str) -> Optional[dict[str, Any]]:
  254. return TokenManager.get_token_data(token, "reset_password")
  255. class TenantService:
  256. @staticmethod
  257. def create_tenant(name: str) -> Tenant:
  258. """Create tenant"""
  259. tenant = Tenant(name=name)
  260. db.session.add(tenant)
  261. db.session.commit()
  262. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  263. db.session.commit()
  264. return tenant
  265. @staticmethod
  266. def create_owner_tenant_if_not_exist(account: Account, name: Optional[str] = None):
  267. """Create owner tenant if not exist"""
  268. available_ta = (
  269. TenantAccountJoin.query.filter_by(account_id=account.id).order_by(TenantAccountJoin.id.asc()).first()
  270. )
  271. if available_ta:
  272. return
  273. if name:
  274. tenant = TenantService.create_tenant(name)
  275. else:
  276. tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  277. TenantService.create_tenant_member(tenant, account, role="owner")
  278. account.current_tenant = tenant
  279. db.session.commit()
  280. tenant_was_created.send(tenant)
  281. @staticmethod
  282. def create_tenant_member(tenant: Tenant, account: Account, role: str = "normal") -> TenantAccountJoin:
  283. """Create tenant member"""
  284. if role == TenantAccountJoinRole.OWNER.value:
  285. if TenantService.has_roles(tenant, [TenantAccountJoinRole.OWNER]):
  286. logging.error(f"Tenant {tenant.id} has already an owner.")
  287. raise Exception("Tenant already has an owner.")
  288. ta = TenantAccountJoin(tenant_id=tenant.id, account_id=account.id, role=role)
  289. db.session.add(ta)
  290. db.session.commit()
  291. return ta
  292. @staticmethod
  293. def get_join_tenants(account: Account) -> list[Tenant]:
  294. """Get account join tenants"""
  295. return (
  296. db.session.query(Tenant)
  297. .join(TenantAccountJoin, Tenant.id == TenantAccountJoin.tenant_id)
  298. .filter(TenantAccountJoin.account_id == account.id, Tenant.status == TenantStatus.NORMAL)
  299. .all()
  300. )
  301. @staticmethod
  302. def get_current_tenant_by_account(account: Account):
  303. """Get tenant by account and add the role"""
  304. tenant = account.current_tenant
  305. if not tenant:
  306. raise TenantNotFoundError("Tenant not found.")
  307. ta = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=account.id).first()
  308. if ta:
  309. tenant.role = ta.role
  310. else:
  311. raise TenantNotFoundError("Tenant not found for the account.")
  312. return tenant
  313. @staticmethod
  314. def switch_tenant(account: Account, tenant_id: Optional[int] = None) -> None:
  315. """Switch the current workspace for the account"""
  316. # Ensure tenant_id is provided
  317. if tenant_id is None:
  318. raise ValueError("Tenant ID must be provided.")
  319. tenant_account_join = (
  320. db.session.query(TenantAccountJoin)
  321. .join(Tenant, TenantAccountJoin.tenant_id == Tenant.id)
  322. .filter(
  323. TenantAccountJoin.account_id == account.id,
  324. TenantAccountJoin.tenant_id == tenant_id,
  325. Tenant.status == TenantStatus.NORMAL,
  326. )
  327. .first()
  328. )
  329. if not tenant_account_join:
  330. raise AccountNotLinkTenantError("Tenant not found or account is not a member of the tenant.")
  331. else:
  332. TenantAccountJoin.query.filter(
  333. TenantAccountJoin.account_id == account.id, TenantAccountJoin.tenant_id != tenant_id
  334. ).update({"current": False})
  335. tenant_account_join.current = True
  336. # Set the current tenant for the account
  337. account.current_tenant_id = tenant_account_join.tenant_id
  338. db.session.commit()
  339. @staticmethod
  340. def get_tenant_members(tenant: Tenant) -> list[Account]:
  341. """Get tenant members"""
  342. query = (
  343. db.session.query(Account, TenantAccountJoin.role)
  344. .select_from(Account)
  345. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  346. .filter(TenantAccountJoin.tenant_id == tenant.id)
  347. )
  348. # Initialize an empty list to store the updated accounts
  349. updated_accounts = []
  350. for account, role in query:
  351. account.role = role
  352. updated_accounts.append(account)
  353. return updated_accounts
  354. @staticmethod
  355. def get_dataset_operator_members(tenant: Tenant) -> list[Account]:
  356. """Get dataset admin members"""
  357. query = (
  358. db.session.query(Account, TenantAccountJoin.role)
  359. .select_from(Account)
  360. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  361. .filter(TenantAccountJoin.tenant_id == tenant.id)
  362. .filter(TenantAccountJoin.role == "dataset_operator")
  363. )
  364. # Initialize an empty list to store the updated accounts
  365. updated_accounts = []
  366. for account, role in query:
  367. account.role = role
  368. updated_accounts.append(account)
  369. return updated_accounts
  370. @staticmethod
  371. def has_roles(tenant: Tenant, roles: list[TenantAccountJoinRole]) -> bool:
  372. """Check if user has any of the given roles for a tenant"""
  373. if not all(isinstance(role, TenantAccountJoinRole) for role in roles):
  374. raise ValueError("all roles must be TenantAccountJoinRole")
  375. return (
  376. db.session.query(TenantAccountJoin)
  377. .filter(
  378. TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.role.in_([role.value for role in roles])
  379. )
  380. .first()
  381. is not None
  382. )
  383. @staticmethod
  384. def get_user_role(account: Account, tenant: Tenant) -> Optional[TenantAccountJoinRole]:
  385. """Get the role of the current account for a given tenant"""
  386. join = (
  387. db.session.query(TenantAccountJoin)
  388. .filter(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == account.id)
  389. .first()
  390. )
  391. return join.role if join else None
  392. @staticmethod
  393. def get_tenant_count() -> int:
  394. """Get tenant count"""
  395. return db.session.query(func.count(Tenant.id)).scalar()
  396. @staticmethod
  397. def check_member_permission(tenant: Tenant, operator: Account, member: Account, action: str) -> None:
  398. """Check member permission"""
  399. perms = {
  400. "add": [TenantAccountRole.OWNER, TenantAccountRole.ADMIN],
  401. "remove": [TenantAccountRole.OWNER],
  402. "update": [TenantAccountRole.OWNER],
  403. }
  404. if action not in {"add", "remove", "update"}:
  405. raise InvalidActionError("Invalid action.")
  406. if member:
  407. if operator.id == member.id:
  408. raise CannotOperateSelfError("Cannot operate self.")
  409. ta_operator = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=operator.id).first()
  410. if not ta_operator or ta_operator.role not in perms[action]:
  411. raise NoPermissionError(f"No permission to {action} member.")
  412. @staticmethod
  413. def remove_member_from_tenant(tenant: Tenant, account: Account, operator: Account) -> None:
  414. """Remove member from tenant"""
  415. if operator.id == account.id and TenantService.check_member_permission(tenant, operator, account, "remove"):
  416. raise CannotOperateSelfError("Cannot operate self.")
  417. ta = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=account.id).first()
  418. if not ta:
  419. raise MemberNotInTenantError("Member not in tenant.")
  420. db.session.delete(ta)
  421. db.session.commit()
  422. @staticmethod
  423. def update_member_role(tenant: Tenant, member: Account, new_role: str, operator: Account) -> None:
  424. """Update member role"""
  425. TenantService.check_member_permission(tenant, operator, member, "update")
  426. target_member_join = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=member.id).first()
  427. if target_member_join.role == new_role:
  428. raise RoleAlreadyAssignedError("The provided role is already assigned to the member.")
  429. if new_role == "owner":
  430. # Find the current owner and change their role to 'admin'
  431. current_owner_join = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, role="owner").first()
  432. current_owner_join.role = "admin"
  433. # Update the role of the target member
  434. target_member_join.role = new_role
  435. db.session.commit()
  436. @staticmethod
  437. def dissolve_tenant(tenant: Tenant, operator: Account) -> None:
  438. """Dissolve tenant"""
  439. if not TenantService.check_member_permission(tenant, operator, operator, "remove"):
  440. raise NoPermissionError("No permission to dissolve tenant.")
  441. db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id).delete()
  442. db.session.delete(tenant)
  443. db.session.commit()
  444. @staticmethod
  445. def get_custom_config(tenant_id: str) -> None:
  446. tenant = db.session.query(Tenant).filter(Tenant.id == tenant_id).one_or_404()
  447. return tenant.custom_config_dict
  448. class RegisterService:
  449. @classmethod
  450. def _get_invitation_token_key(cls, token: str) -> str:
  451. return f"member_invite:token:{token}"
  452. @classmethod
  453. def setup(cls, email: str, name: str, password: str, ip_address: str) -> None:
  454. """
  455. Setup dify
  456. :param email: email
  457. :param name: username
  458. :param password: password
  459. :param ip_address: ip address
  460. """
  461. try:
  462. # Register
  463. account = AccountService.create_account(
  464. email=email,
  465. name=name,
  466. interface_language=languages[0],
  467. password=password,
  468. )
  469. account.last_login_ip = ip_address
  470. account.initialized_at = datetime.now(timezone.utc).replace(tzinfo=None)
  471. TenantService.create_owner_tenant_if_not_exist(account)
  472. dify_setup = DifySetup(version=dify_config.CURRENT_VERSION)
  473. db.session.add(dify_setup)
  474. db.session.commit()
  475. except Exception as e:
  476. db.session.query(DifySetup).delete()
  477. db.session.query(TenantAccountJoin).delete()
  478. db.session.query(Account).delete()
  479. db.session.query(Tenant).delete()
  480. db.session.commit()
  481. logging.exception(f"Setup failed: {e}")
  482. raise ValueError(f"Setup failed: {e}")
  483. @classmethod
  484. def register(
  485. cls,
  486. email,
  487. name,
  488. password: Optional[str] = None,
  489. open_id: Optional[str] = None,
  490. provider: Optional[str] = None,
  491. language: Optional[str] = None,
  492. status: Optional[AccountStatus] = None,
  493. ) -> Account:
  494. db.session.begin_nested()
  495. """Register account"""
  496. try:
  497. account = AccountService.create_account(
  498. email=email, name=name, interface_language=language or languages[0], password=password
  499. )
  500. account.status = AccountStatus.ACTIVE.value if not status else status.value
  501. account.initialized_at = datetime.now(timezone.utc).replace(tzinfo=None)
  502. if open_id is not None or provider is not None:
  503. AccountService.link_account_integrate(provider, open_id, account)
  504. if dify_config.EDITION != "SELF_HOSTED":
  505. tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  506. TenantService.create_tenant_member(tenant, account, role="owner")
  507. account.current_tenant = tenant
  508. tenant_was_created.send(tenant)
  509. db.session.commit()
  510. except Exception as e:
  511. db.session.rollback()
  512. logging.error(f"Register failed: {e}")
  513. raise AccountRegisterError(f"Registration failed: {e}") from e
  514. return account
  515. @classmethod
  516. def invite_new_member(
  517. cls, tenant: Tenant, email: str, language: str, role: str = "normal", inviter: Account = None
  518. ) -> str:
  519. """Invite new member"""
  520. account = Account.query.filter_by(email=email).first()
  521. if not account:
  522. TenantService.check_member_permission(tenant, inviter, None, "add")
  523. name = email.split("@")[0]
  524. account = cls.register(email=email, name=name, language=language, status=AccountStatus.PENDING)
  525. # Create new tenant member for invited tenant
  526. TenantService.create_tenant_member(tenant, account, role)
  527. TenantService.switch_tenant(account, tenant.id)
  528. else:
  529. TenantService.check_member_permission(tenant, inviter, account, "add")
  530. ta = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=account.id).first()
  531. if not ta:
  532. TenantService.create_tenant_member(tenant, account, role)
  533. # Support resend invitation email when the account is pending status
  534. if account.status != AccountStatus.PENDING.value:
  535. raise AccountAlreadyInTenantError("Account already in tenant.")
  536. token = cls.generate_invite_token(tenant, account)
  537. # send email
  538. send_invite_member_mail_task.delay(
  539. language=account.interface_language,
  540. to=email,
  541. token=token,
  542. inviter_name=inviter.name if inviter else "Dify",
  543. workspace_name=tenant.name,
  544. )
  545. return token
  546. @classmethod
  547. def generate_invite_token(cls, tenant: Tenant, account: Account) -> str:
  548. token = str(uuid.uuid4())
  549. invitation_data = {
  550. "account_id": account.id,
  551. "email": account.email,
  552. "workspace_id": tenant.id,
  553. }
  554. expiry_hours = dify_config.INVITE_EXPIRY_HOURS
  555. redis_client.setex(cls._get_invitation_token_key(token), expiry_hours * 60 * 60, json.dumps(invitation_data))
  556. return token
  557. @classmethod
  558. def revoke_token(cls, workspace_id: str, email: str, token: str):
  559. if workspace_id and email:
  560. email_hash = sha256(email.encode()).hexdigest()
  561. cache_key = "member_invite_token:{}, {}:{}".format(workspace_id, email_hash, token)
  562. redis_client.delete(cache_key)
  563. else:
  564. redis_client.delete(cls._get_invitation_token_key(token))
  565. @classmethod
  566. def get_invitation_if_token_valid(cls, workspace_id: str, email: str, token: str) -> Optional[dict[str, Any]]:
  567. invitation_data = cls._get_invitation_by_token(token, workspace_id, email)
  568. if not invitation_data:
  569. return None
  570. tenant = (
  571. db.session.query(Tenant)
  572. .filter(Tenant.id == invitation_data["workspace_id"], Tenant.status == "normal")
  573. .first()
  574. )
  575. if not tenant:
  576. return None
  577. tenant_account = (
  578. db.session.query(Account, TenantAccountJoin.role)
  579. .join(TenantAccountJoin, Account.id == TenantAccountJoin.account_id)
  580. .filter(Account.email == invitation_data["email"], TenantAccountJoin.tenant_id == tenant.id)
  581. .first()
  582. )
  583. if not tenant_account:
  584. return None
  585. account = tenant_account[0]
  586. if not account:
  587. return None
  588. if invitation_data["account_id"] != str(account.id):
  589. return None
  590. return {
  591. "account": account,
  592. "data": invitation_data,
  593. "tenant": tenant,
  594. }
  595. @classmethod
  596. def _get_invitation_by_token(cls, token: str, workspace_id: str, email: str) -> Optional[dict[str, str]]:
  597. if workspace_id is not None and email is not None:
  598. email_hash = sha256(email.encode()).hexdigest()
  599. cache_key = f"member_invite_token:{workspace_id}, {email_hash}:{token}"
  600. account_id = redis_client.get(cache_key)
  601. if not account_id:
  602. return None
  603. return {
  604. "account_id": account_id.decode("utf-8"),
  605. "email": email,
  606. "workspace_id": workspace_id,
  607. }
  608. else:
  609. data = redis_client.get(cls._get_invitation_token_key(token))
  610. if not data:
  611. return None
  612. invitation = json.loads(data)
  613. return invitation
  614. def _generate_refresh_token(length: int = 64):
  615. token = secrets.token_hex(length)
  616. return token