account_service.py 24 KB

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