account_service.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. import base64
  2. import logging
  3. import secrets
  4. import uuid
  5. from datetime import datetime, timedelta
  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 Forbidden
  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.helper import get_remote_ip
  15. from libs.passport import PassportService
  16. from libs.password import compare_password, hash_password, valid_password
  17. from libs.rsa import generate_key_pair
  18. from models.account import *
  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 Forbidden('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.utcnow() - account.last_active_at > timedelta(minutes=10):
  54. account.last_active_at = datetime.utcnow()
  55. db.session.commit()
  56. return account
  57. @staticmethod
  58. def get_account_jwt_token(account):
  59. payload = {
  60. "user_id": account.id,
  61. "exp": datetime.utcnow() + timedelta(days=30),
  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.utcnow()
  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, name: str, interface_language: str,
  101. password: str = None,
  102. interface_theme: str = 'light',
  103. timezone: str = 'America/New_York', ) -> Account:
  104. """create account"""
  105. account = Account()
  106. account.email = email
  107. account.name = name
  108. if password:
  109. # generate password salt
  110. salt = secrets.token_bytes(16)
  111. base64_salt = base64.b64encode(salt).decode()
  112. # encrypt password with salt
  113. password_hashed = hash_password(password, salt)
  114. base64_password_hashed = base64.b64encode(password_hashed).decode()
  115. account.password = base64_password_hashed
  116. account.password_salt = base64_salt
  117. account.interface_language = interface_language
  118. account.interface_theme = interface_theme
  119. # Set timezone based on language
  120. account.timezone = language_timezone_mapping.get(interface_language, 'UTC')
  121. db.session.add(account)
  122. db.session.commit()
  123. return account
  124. @staticmethod
  125. def link_account_integrate(provider: str, open_id: str, account: Account) -> None:
  126. """Link account integrate"""
  127. try:
  128. # Query whether there is an existing binding record for the same provider
  129. account_integrate: Optional[AccountIntegrate] = AccountIntegrate.query.filter_by(account_id=account.id,
  130. provider=provider).first()
  131. if account_integrate:
  132. # If it exists, update the record
  133. account_integrate.open_id = open_id
  134. account_integrate.encrypted_token = "" # todo
  135. account_integrate.updated_at = datetime.utcnow()
  136. else:
  137. # If it does not exist, create a new record
  138. account_integrate = AccountIntegrate(account_id=account.id, provider=provider, open_id=open_id,
  139. encrypted_token="")
  140. db.session.add(account_integrate)
  141. db.session.commit()
  142. logging.info(f'Account {account.id} linked {provider} account {open_id}.')
  143. except Exception as e:
  144. logging.exception(f'Failed to link {provider} account {open_id} to Account {account.id}')
  145. raise LinkAccountIntegrateError('Failed to link account.') from e
  146. @staticmethod
  147. def close_account(account: Account) -> None:
  148. """todo: Close account"""
  149. account.status = AccountStatus.CLOSED.value
  150. db.session.commit()
  151. @staticmethod
  152. def update_account(account, **kwargs):
  153. """Update account fields"""
  154. for field, value in kwargs.items():
  155. if hasattr(account, field):
  156. setattr(account, field, value)
  157. else:
  158. raise AttributeError(f"Invalid field: {field}")
  159. db.session.commit()
  160. return account
  161. @staticmethod
  162. def update_last_login(account: Account, request) -> None:
  163. """Update last login time and ip"""
  164. account.last_login_at = datetime.utcnow()
  165. account.last_login_ip = get_remote_ip(request)
  166. db.session.add(account)
  167. db.session.commit()
  168. logging.info(f'Account {account.id} logged in successfully.')
  169. class TenantService:
  170. @staticmethod
  171. def create_tenant(name: str) -> Tenant:
  172. """Create tenant"""
  173. tenant = Tenant(name=name)
  174. db.session.add(tenant)
  175. db.session.commit()
  176. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  177. db.session.commit()
  178. return tenant
  179. @staticmethod
  180. def create_owner_tenant_if_not_exist(account: Account):
  181. """Create owner tenant if not exist"""
  182. available_ta = TenantAccountJoin.query.filter_by(account_id=account.id) \
  183. .order_by(TenantAccountJoin.id.asc()).first()
  184. if available_ta:
  185. return
  186. tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  187. TenantService.create_tenant_member(tenant, account, role='owner')
  188. account.current_tenant = tenant
  189. db.session.commit()
  190. tenant_was_created.send(tenant)
  191. @staticmethod
  192. def create_tenant_member(tenant: Tenant, account: Account, role: str = 'normal') -> TenantAccountJoin:
  193. """Create tenant member"""
  194. if role == TenantAccountJoinRole.OWNER.value:
  195. if TenantService.has_roles(tenant, [TenantAccountJoinRole.OWNER]):
  196. logging.error(f'Tenant {tenant.id} has already an owner.')
  197. raise Exception('Tenant already has an owner.')
  198. ta = TenantAccountJoin(
  199. tenant_id=tenant.id,
  200. account_id=account.id,
  201. role=role
  202. )
  203. db.session.add(ta)
  204. db.session.commit()
  205. return ta
  206. @staticmethod
  207. def get_join_tenants(account: Account) -> list[Tenant]:
  208. """Get account join tenants"""
  209. return db.session.query(Tenant).join(
  210. TenantAccountJoin, Tenant.id == TenantAccountJoin.tenant_id
  211. ).filter(TenantAccountJoin.account_id == account.id).all()
  212. @staticmethod
  213. def get_current_tenant_by_account(account: Account):
  214. """Get tenant by account and add the role"""
  215. tenant = account.current_tenant
  216. if not tenant:
  217. raise TenantNotFound("Tenant not found.")
  218. ta = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=account.id).first()
  219. if ta:
  220. tenant.role = ta.role
  221. else:
  222. raise TenantNotFound("Tenant not found for the account.")
  223. return tenant
  224. @staticmethod
  225. def switch_tenant(account: Account, tenant_id: int = None) -> None:
  226. """Switch the current workspace for the account"""
  227. # Ensure tenant_id is provided
  228. if tenant_id is None:
  229. raise ValueError("Tenant ID must be provided.")
  230. tenant_account_join = TenantAccountJoin.query.filter_by(account_id=account.id, tenant_id=tenant_id).first()
  231. if not tenant_account_join:
  232. raise AccountNotLinkTenantError("Tenant not found or account is not a member of the tenant.")
  233. else:
  234. TenantAccountJoin.query.filter(TenantAccountJoin.account_id == account.id, TenantAccountJoin.tenant_id != tenant_id).update({'current': False})
  235. tenant_account_join.current = True
  236. # Set the current tenant for the account
  237. account.current_tenant_id = tenant_account_join.tenant_id
  238. db.session.commit()
  239. @staticmethod
  240. def get_tenant_members(tenant: Tenant) -> list[Account]:
  241. """Get tenant members"""
  242. query = (
  243. db.session.query(Account, TenantAccountJoin.role)
  244. .select_from(Account)
  245. .join(
  246. TenantAccountJoin, Account.id == TenantAccountJoin.account_id
  247. )
  248. .filter(TenantAccountJoin.tenant_id == tenant.id)
  249. )
  250. # Initialize an empty list to store the updated accounts
  251. updated_accounts = []
  252. for account, role in query:
  253. account.role = role
  254. updated_accounts.append(account)
  255. return updated_accounts
  256. @staticmethod
  257. def has_roles(tenant: Tenant, roles: list[TenantAccountJoinRole]) -> bool:
  258. """Check if user has any of the given roles for a tenant"""
  259. if not all(isinstance(role, TenantAccountJoinRole) for role in roles):
  260. raise ValueError('all roles must be TenantAccountJoinRole')
  261. return db.session.query(TenantAccountJoin).filter(
  262. TenantAccountJoin.tenant_id == tenant.id,
  263. TenantAccountJoin.role.in_([role.value for role in roles])
  264. ).first() is not None
  265. @staticmethod
  266. def get_user_role(account: Account, tenant: Tenant) -> Optional[TenantAccountJoinRole]:
  267. """Get the role of the current account for a given tenant"""
  268. join = db.session.query(TenantAccountJoin).filter(
  269. TenantAccountJoin.tenant_id == tenant.id,
  270. TenantAccountJoin.account_id == account.id
  271. ).first()
  272. return join.role if join else None
  273. @staticmethod
  274. def get_tenant_count() -> int:
  275. """Get tenant count"""
  276. return db.session.query(func.count(Tenant.id)).scalar()
  277. @staticmethod
  278. def check_member_permission(tenant: Tenant, operator: Account, member: Account, action: str) -> None:
  279. """Check member permission"""
  280. perms = {
  281. 'add': ['owner', 'admin'],
  282. 'remove': ['owner'],
  283. 'update': ['owner']
  284. }
  285. if action not in ['add', 'remove', 'update']:
  286. raise InvalidActionError("Invalid action.")
  287. if member:
  288. if operator.id == member.id:
  289. raise CannotOperateSelfError("Cannot operate self.")
  290. ta_operator = TenantAccountJoin.query.filter_by(
  291. tenant_id=tenant.id,
  292. account_id=operator.id
  293. ).first()
  294. if not ta_operator or ta_operator.role not in perms[action]:
  295. raise NoPermissionError(f'No permission to {action} member.')
  296. @staticmethod
  297. def remove_member_from_tenant(tenant: Tenant, account: Account, operator: Account) -> None:
  298. """Remove member from tenant"""
  299. if operator.id == account.id and TenantService.check_member_permission(tenant, operator, account, 'remove'):
  300. raise CannotOperateSelfError("Cannot operate self.")
  301. ta = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=account.id).first()
  302. if not ta:
  303. raise MemberNotInTenantError("Member not in tenant.")
  304. db.session.delete(ta)
  305. db.session.commit()
  306. @staticmethod
  307. def update_member_role(tenant: Tenant, member: Account, new_role: str, operator: Account) -> None:
  308. """Update member role"""
  309. TenantService.check_member_permission(tenant, operator, member, 'update')
  310. target_member_join = TenantAccountJoin.query.filter_by(
  311. tenant_id=tenant.id,
  312. account_id=member.id
  313. ).first()
  314. if target_member_join.role == new_role:
  315. raise RoleAlreadyAssignedError("The provided role is already assigned to the member.")
  316. if new_role == 'owner':
  317. # Find the current owner and change their role to 'admin'
  318. current_owner_join = TenantAccountJoin.query.filter_by(
  319. tenant_id=tenant.id,
  320. role='owner'
  321. ).first()
  322. current_owner_join.role = 'admin'
  323. # Update the role of the target member
  324. target_member_join.role = new_role
  325. db.session.commit()
  326. @staticmethod
  327. def dissolve_tenant(tenant: Tenant, operator: Account) -> None:
  328. """Dissolve tenant"""
  329. if not TenantService.check_member_permission(tenant, operator, operator, 'remove'):
  330. raise NoPermissionError('No permission to dissolve tenant.')
  331. db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id).delete()
  332. db.session.delete(tenant)
  333. db.session.commit()
  334. @staticmethod
  335. def get_custom_config(tenant_id: str) -> None:
  336. tenant = db.session.query(Tenant).filter(Tenant.id == tenant_id).one_or_404()
  337. return tenant.custom_config_dict
  338. class RegisterService:
  339. @classmethod
  340. def _get_invitation_token_key(cls, token: str) -> str:
  341. return f'member_invite:token:{token}'
  342. @classmethod
  343. def register(cls, email, name, password: str = None, open_id: str = None, provider: str = None,
  344. language: str = None, status: AccountStatus = None) -> Account:
  345. db.session.begin_nested()
  346. """Register account"""
  347. try:
  348. account = AccountService.create_account(
  349. email=email,
  350. name=name,
  351. interface_language=language if language else languages[0],
  352. password=password
  353. )
  354. account.status = AccountStatus.ACTIVE.value if not status else status.value
  355. account.initialized_at = datetime.utcnow()
  356. if open_id is not None or provider is not None:
  357. AccountService.link_account_integrate(provider, open_id, account)
  358. if current_app.config['EDITION'] != 'SELF_HOSTED':
  359. tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  360. TenantService.create_tenant_member(tenant, account, role='owner')
  361. account.current_tenant = tenant
  362. tenant_was_created.send(tenant)
  363. db.session.commit()
  364. except Exception as e:
  365. db.session.rollback() # todo: do not work
  366. logging.error(f'Register failed: {e}')
  367. raise AccountRegisterError(f'Registration failed: {e}') from e
  368. return account
  369. @classmethod
  370. def invite_new_member(cls, tenant: Tenant, email: str, language: str, role: str = 'normal', inviter: Account = None) -> str:
  371. """Invite new member"""
  372. account = Account.query.filter_by(email=email).first()
  373. if not account:
  374. TenantService.check_member_permission(tenant, inviter, None, 'add')
  375. name = email.split('@')[0]
  376. account = cls.register(email=email, name=name, language=language, status=AccountStatus.PENDING)
  377. # Create new tenant member for invited tenant
  378. TenantService.create_tenant_member(tenant, account, role)
  379. TenantService.switch_tenant(account, tenant.id)
  380. else:
  381. TenantService.check_member_permission(tenant, inviter, account, 'add')
  382. ta = TenantAccountJoin.query.filter_by(
  383. tenant_id=tenant.id,
  384. account_id=account.id
  385. ).first()
  386. if not ta:
  387. TenantService.create_tenant_member(tenant, account, role)
  388. # Support resend invitation email when the account is pending status
  389. if account.status != AccountStatus.PENDING.value:
  390. raise AccountAlreadyInTenantError("Account already in tenant.")
  391. token = cls.generate_invite_token(tenant, account)
  392. # send email
  393. send_invite_member_mail_task.delay(
  394. language=account.interface_language,
  395. to=email,
  396. token=token,
  397. inviter_name=inviter.name if inviter else 'Dify',
  398. workspace_name=tenant.name,
  399. )
  400. return token
  401. @classmethod
  402. def generate_invite_token(cls, tenant: Tenant, account: Account) -> str:
  403. token = str(uuid.uuid4())
  404. invitation_data = {
  405. 'account_id': account.id,
  406. 'email': account.email,
  407. 'workspace_id': tenant.id,
  408. }
  409. expiryHours = current_app.config['INVITE_EXPIRY_HOURS']
  410. redis_client.setex(
  411. cls._get_invitation_token_key(token),
  412. expiryHours * 60 * 60,
  413. json.dumps(invitation_data)
  414. )
  415. return token
  416. @classmethod
  417. def revoke_token(cls, workspace_id: str, email: str, token: str):
  418. if workspace_id and email:
  419. email_hash = sha256(email.encode()).hexdigest()
  420. cache_key = 'member_invite_token:{}, {}:{}'.format(workspace_id, email_hash, token)
  421. redis_client.delete(cache_key)
  422. else:
  423. redis_client.delete(cls._get_invitation_token_key(token))
  424. @classmethod
  425. def get_invitation_if_token_valid(cls, workspace_id: str, email: str, token: str) -> Optional[dict[str, Any]]:
  426. invitation_data = cls._get_invitation_by_token(token, workspace_id, email)
  427. if not invitation_data:
  428. return None
  429. tenant = db.session.query(Tenant).filter(
  430. Tenant.id == invitation_data['workspace_id'],
  431. Tenant.status == 'normal'
  432. ).first()
  433. if not tenant:
  434. return None
  435. tenant_account = db.session.query(Account, TenantAccountJoin.role).join(
  436. TenantAccountJoin, Account.id == TenantAccountJoin.account_id
  437. ).filter(Account.email == invitation_data['email'], TenantAccountJoin.tenant_id == tenant.id).first()
  438. if not tenant_account:
  439. return None
  440. account = tenant_account[0]
  441. if not account:
  442. return None
  443. if invitation_data['account_id'] != str(account.id):
  444. return None
  445. return {
  446. 'account': account,
  447. 'data': invitation_data,
  448. 'tenant': tenant,
  449. }
  450. @classmethod
  451. def _get_invitation_by_token(cls, token: str, workspace_id: str, email: str) -> Optional[dict[str, str]]:
  452. if workspace_id is not None and email is not None:
  453. email_hash = sha256(email.encode()).hexdigest()
  454. cache_key = f'member_invite_token:{workspace_id}, {email_hash}:{token}'
  455. account_id = redis_client.get(cache_key)
  456. if not account_id:
  457. return None
  458. return {
  459. 'account_id': account_id.decode('utf-8'),
  460. 'email': email,
  461. 'workspace_id': workspace_id,
  462. }
  463. else:
  464. data = redis_client.get(cls._get_invitation_token_key(token))
  465. if not data:
  466. return None
  467. invitation = json.loads(data)
  468. return invitation