account_service.py 21 KB

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