account_service.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. # -*- coding:utf-8 -*-
  2. import base64
  3. import json
  4. import logging
  5. import secrets
  6. import uuid
  7. from datetime import datetime, timedelta
  8. from hashlib import sha256
  9. from typing import Any, Dict, Optional
  10. from events.tenant_event import tenant_was_created
  11. from extensions.ext_redis import redis_client
  12. from flask import current_app, session
  13. from libs.helper import get_remote_ip
  14. from libs.passport import PassportService
  15. from libs.password import compare_password, hash_password
  16. from libs.rsa import generate_key_pair
  17. from models.account import *
  18. from services.errors.account import (AccountAlreadyInTenantError, AccountLoginError, AccountNotLinkTenantError,
  19. AccountRegisterError, CannotOperateSelfError, CurrentPasswordIncorrectError,
  20. InvalidActionError, LinkAccountIntegrateError, MemberNotInTenantError,
  21. NoPermissionError, RoleAlreadyAssignedError, TenantNotFound)
  22. from sqlalchemy import func
  23. from tasks.mail_invite_member_task import send_invite_member_mail_task
  24. from werkzeug.exceptions import Forbidden, Unauthorized
  25. def _create_tenant_for_account(account) -> Tenant:
  26. tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  27. TenantService.create_tenant_member(tenant, account, role='owner')
  28. account.current_tenant = tenant
  29. return tenant
  30. class AccountService:
  31. @staticmethod
  32. def load_user(user_id: str) -> Account:
  33. # todo: used by flask_login
  34. if '.' in user_id:
  35. tenant_id, account_id = user_id.split('.')
  36. else:
  37. account_id = user_id
  38. account = db.session.query(Account).filter(Account.id == account_id).first()
  39. if account:
  40. if account.status == AccountStatus.BANNED.value or account.status == AccountStatus.CLOSED.value:
  41. raise Forbidden('Account is banned or closed.')
  42. workspace_id = session.get('workspace_id')
  43. if workspace_id:
  44. tenant_account_join = db.session.query(TenantAccountJoin).filter(
  45. TenantAccountJoin.account_id == account.id,
  46. TenantAccountJoin.tenant_id == workspace_id
  47. ).first()
  48. if not tenant_account_join:
  49. tenant_account_join = db.session.query(TenantAccountJoin).filter(
  50. TenantAccountJoin.account_id == account.id).first()
  51. if tenant_account_join:
  52. account.current_tenant_id = tenant_account_join.tenant_id
  53. else:
  54. _create_tenant_for_account(account)
  55. session['workspace_id'] = account.current_tenant_id
  56. else:
  57. account.current_tenant_id = workspace_id
  58. else:
  59. tenant_account_join = db.session.query(TenantAccountJoin).filter(
  60. TenantAccountJoin.account_id == account.id).first()
  61. if tenant_account_join:
  62. account.current_tenant_id = tenant_account_join.tenant_id
  63. else:
  64. _create_tenant_for_account(account)
  65. session['workspace_id'] = account.current_tenant_id
  66. current_time = datetime.utcnow()
  67. # update last_active_at when last_active_at is more than 10 minutes ago
  68. if current_time - account.last_active_at > timedelta(minutes=10):
  69. account.last_active_at = current_time
  70. db.session.commit()
  71. return account
  72. @staticmethod
  73. def get_account_jwt_token(account):
  74. payload = {
  75. "user_id": account.id,
  76. "exp": datetime.utcnow() + timedelta(days=30),
  77. "iss": current_app.config['EDITION'],
  78. "sub": 'Console API Passport',
  79. }
  80. token = PassportService().issue(payload)
  81. return token
  82. @staticmethod
  83. def authenticate(email: str, password: str) -> Account:
  84. """authenticate account with email and password"""
  85. account = Account.query.filter_by(email=email).first()
  86. if not account:
  87. raise AccountLoginError('Invalid email or password.')
  88. if account.status == AccountStatus.BANNED.value or account.status == AccountStatus.CLOSED.value:
  89. raise AccountLoginError('Account is banned or closed.')
  90. if account.status == AccountStatus.PENDING.value:
  91. account.status = AccountStatus.ACTIVE.value
  92. account.initialized_at = datetime.utcnow()
  93. db.session.commit()
  94. if account.password is None or not compare_password(password, account.password, account.password_salt):
  95. raise AccountLoginError('Invalid email or password.')
  96. return account
  97. @staticmethod
  98. def update_account_password(account, password, new_password):
  99. """update account password"""
  100. if account.password and not compare_password(password, account.password, account.password_salt):
  101. raise CurrentPasswordIncorrectError("Current password is incorrect.")
  102. # generate password salt
  103. salt = secrets.token_bytes(16)
  104. base64_salt = base64.b64encode(salt).decode()
  105. # encrypt password with salt
  106. password_hashed = hash_password(new_password, salt)
  107. base64_password_hashed = base64.b64encode(password_hashed).decode()
  108. account.password = base64_password_hashed
  109. account.password_salt = base64_salt
  110. db.session.commit()
  111. return account
  112. @staticmethod
  113. def create_account(email: str, name: str, password: str = None,
  114. interface_language: str = 'en-US', interface_theme: str = 'light',
  115. timezone: str = 'America/New_York', ) -> Account:
  116. """create account"""
  117. account = Account()
  118. account.email = email
  119. account.name = name
  120. if password:
  121. # generate password salt
  122. salt = secrets.token_bytes(16)
  123. base64_salt = base64.b64encode(salt).decode()
  124. # encrypt password with salt
  125. password_hashed = hash_password(password, salt)
  126. base64_password_hashed = base64.b64encode(password_hashed).decode()
  127. account.password = base64_password_hashed
  128. account.password_salt = base64_salt
  129. account.interface_language = interface_language
  130. account.interface_theme = interface_theme
  131. if interface_language == 'zh-Hans':
  132. account.timezone = 'Asia/Shanghai'
  133. else:
  134. account.timezone = timezone
  135. db.session.add(account)
  136. db.session.commit()
  137. return account
  138. @staticmethod
  139. def link_account_integrate(provider: str, open_id: str, account: Account) -> None:
  140. """Link account integrate"""
  141. try:
  142. # Query whether there is an existing binding record for the same provider
  143. account_integrate: Optional[AccountIntegrate] = AccountIntegrate.query.filter_by(account_id=account.id,
  144. provider=provider).first()
  145. if account_integrate:
  146. # If it exists, update the record
  147. account_integrate.open_id = open_id
  148. account_integrate.encrypted_token = "" # todo
  149. account_integrate.updated_at = datetime.utcnow()
  150. else:
  151. # If it does not exist, create a new record
  152. account_integrate = AccountIntegrate(account_id=account.id, provider=provider, open_id=open_id,
  153. encrypted_token="")
  154. db.session.add(account_integrate)
  155. db.session.commit()
  156. logging.info(f'Account {account.id} linked {provider} account {open_id}.')
  157. except Exception as e:
  158. logging.exception(f'Failed to link {provider} account {open_id} to Account {account.id}')
  159. raise LinkAccountIntegrateError('Failed to link account.') from e
  160. @staticmethod
  161. def close_account(account: Account) -> None:
  162. """todo: Close account"""
  163. account.status = AccountStatus.CLOSED.value
  164. db.session.commit()
  165. @staticmethod
  166. def update_account(account, **kwargs):
  167. """Update account fields"""
  168. for field, value in kwargs.items():
  169. if hasattr(account, field):
  170. setattr(account, field, value)
  171. else:
  172. raise AttributeError(f"Invalid field: {field}")
  173. db.session.commit()
  174. return account
  175. @staticmethod
  176. def update_last_login(account: Account, request) -> None:
  177. """Update last login time and ip"""
  178. account.last_login_at = datetime.utcnow()
  179. account.last_login_ip = get_remote_ip(request)
  180. db.session.add(account)
  181. db.session.commit()
  182. logging.info(f'Account {account.id} logged in successfully.')
  183. class TenantService:
  184. @staticmethod
  185. def create_tenant(name: str) -> Tenant:
  186. """Create tenant"""
  187. tenant = Tenant(name=name)
  188. db.session.add(tenant)
  189. db.session.commit()
  190. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  191. db.session.commit()
  192. return tenant
  193. @staticmethod
  194. def create_tenant_member(tenant: Tenant, account: Account, role: str = 'normal') -> TenantAccountJoin:
  195. """Create tenant member"""
  196. if role == TenantAccountJoinRole.OWNER.value:
  197. if TenantService.has_roles(tenant, [TenantAccountJoinRole.OWNER]):
  198. logging.error(f'Tenant {tenant.id} has already an owner.')
  199. raise Exception('Tenant already has an owner.')
  200. ta = TenantAccountJoin(
  201. tenant_id=tenant.id,
  202. account_id=account.id,
  203. role=role
  204. )
  205. db.session.add(ta)
  206. db.session.commit()
  207. return ta
  208. @staticmethod
  209. def get_join_tenants(account: Account) -> List[Tenant]:
  210. """Get account join tenants"""
  211. return db.session.query(Tenant).join(
  212. TenantAccountJoin, Tenant.id == TenantAccountJoin.tenant_id
  213. ).filter(TenantAccountJoin.account_id == account.id).all()
  214. @staticmethod
  215. def get_current_tenant_by_account(account: Account):
  216. """Get tenant by account and add the role"""
  217. tenant = account.current_tenant
  218. if not tenant:
  219. raise TenantNotFound("Tenant not found.")
  220. ta = TenantAccountJoin.query.filter_by(tenant_id=tenant.id, account_id=account.id).first()
  221. if ta:
  222. tenant.role = ta.role
  223. else:
  224. raise TenantNotFound("Tenant not found for the account.")
  225. return tenant
  226. @staticmethod
  227. def switch_tenant(account: Account, tenant_id: int = None) -> None:
  228. """Switch the current workspace for the account"""
  229. if not tenant_id:
  230. tenant_account_join = TenantAccountJoin.query.filter_by(account_id=account.id).first()
  231. else:
  232. tenant_account_join = TenantAccountJoin.query.filter_by(account_id=account.id, tenant_id=tenant_id).first()
  233. # Check if the tenant exists and the account is a member of the tenant
  234. if not tenant_account_join:
  235. raise AccountNotLinkTenantError("Tenant not found or account is not a member of the tenant.")
  236. # Set the current tenant for the account
  237. account.current_tenant_id = tenant_account_join.tenant_id
  238. session['workspace_id'] = account.current_tenant.id
  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. account.initialized_at = None
  306. account.status = AccountStatus.PENDING.value
  307. account.password = None
  308. account.password_salt = None
  309. db.session.commit()
  310. @staticmethod
  311. def update_member_role(tenant: Tenant, member: Account, new_role: str, operator: Account) -> None:
  312. """Update member role"""
  313. TenantService.check_member_permission(tenant, operator, member, 'update')
  314. target_member_join = TenantAccountJoin.query.filter_by(
  315. tenant_id=tenant.id,
  316. account_id=member.id
  317. ).first()
  318. if target_member_join.role == new_role:
  319. raise RoleAlreadyAssignedError("The provided role is already assigned to the member.")
  320. if new_role == 'owner':
  321. # Find the current owner and change their role to 'admin'
  322. current_owner_join = TenantAccountJoin.query.filter_by(
  323. tenant_id=tenant.id,
  324. role='owner'
  325. ).first()
  326. current_owner_join.role = 'admin'
  327. # Update the role of the target member
  328. target_member_join.role = new_role
  329. db.session.commit()
  330. @staticmethod
  331. def dissolve_tenant(tenant: Tenant, operator: Account) -> None:
  332. """Dissolve tenant"""
  333. if not TenantService.check_member_permission(tenant, operator, operator, 'remove'):
  334. raise NoPermissionError('No permission to dissolve tenant.')
  335. db.session.query(TenantAccountJoin).filter_by(tenant_id=tenant.id).delete()
  336. db.session.delete(tenant)
  337. db.session.commit()
  338. @staticmethod
  339. def get_custom_config(tenant_id: str) -> None:
  340. tenant = db.session.query(Tenant).filter(Tenant.id == tenant_id).one_or_404()
  341. return tenant.custom_config_dict
  342. class RegisterService:
  343. @classmethod
  344. def _get_invitation_token_key(cls, token: str) -> str:
  345. return f'member_invite:token:{token}'
  346. @classmethod
  347. def register(cls, email, name, password: str = None, open_id: str = None, provider: str = None) -> Account:
  348. db.session.begin_nested()
  349. """Register account"""
  350. try:
  351. account = AccountService.create_account(email, name, password)
  352. account.status = AccountStatus.ACTIVE.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, role: str = 'normal',
  368. inviter: Account = None) -> str:
  369. """Invite new member"""
  370. account = Account.query.filter_by(email=email).first()
  371. if not account:
  372. TenantService.check_member_permission(tenant, inviter, None, 'add')
  373. name = email.split('@')[0]
  374. account = AccountService.create_account(email, name)
  375. account.status = AccountStatus.PENDING.value
  376. db.session.commit()
  377. TenantService.create_tenant_member(tenant, account, role)
  378. else:
  379. TenantService.check_member_permission(tenant, inviter, account, 'add')
  380. ta = TenantAccountJoin.query.filter_by(
  381. tenant_id=tenant.id,
  382. account_id=account.id
  383. ).first()
  384. if not ta:
  385. TenantService.create_tenant_member(tenant, account, role)
  386. # Support resend invitation email when the account is pending status
  387. if account.status != AccountStatus.PENDING.value:
  388. raise AccountAlreadyInTenantError("Account already in tenant.")
  389. token = cls.generate_invite_token(tenant, account)
  390. # send email
  391. send_invite_member_mail_task.delay(
  392. language=account.interface_language,
  393. to=email,
  394. token=token,
  395. inviter_name=inviter.name if inviter else 'Dify',
  396. workspace_name=tenant.name,
  397. )
  398. return token
  399. @classmethod
  400. def generate_invite_token(cls, tenant: Tenant, account: Account) -> str:
  401. token = str(uuid.uuid4())
  402. invitation_data = {
  403. 'account_id': account.id,
  404. 'email': account.email,
  405. 'workspace_id': tenant.id,
  406. }
  407. expiryHours = current_app.config['INVITE_EXPIRY_HOURS']
  408. redis_client.setex(
  409. cls._get_invitation_token_key(token),
  410. expiryHours * 60 * 60,
  411. json.dumps(invitation_data)
  412. )
  413. return token
  414. @classmethod
  415. def revoke_token(cls, workspace_id: str, email: str, token: str):
  416. if workspace_id and email:
  417. email_hash = sha256(email.encode()).hexdigest()
  418. cache_key = 'member_invite_token:{}, {}:{}'.format(workspace_id, email_hash, token)
  419. redis_client.delete(cache_key)
  420. else:
  421. redis_client.delete(cls._get_invitation_token_key(token))
  422. @classmethod
  423. def get_invitation_if_token_valid(cls, workspace_id: str, email: str, token: str) -> Optional[Dict[str, Any]]:
  424. invitation_data = cls._get_invitation_by_token(token, workspace_id, email)
  425. if not invitation_data:
  426. return None
  427. tenant = db.session.query(Tenant).filter(
  428. Tenant.id == invitation_data['workspace_id'],
  429. Tenant.status == 'normal'
  430. ).first()
  431. if not tenant:
  432. return None
  433. tenant_account = db.session.query(Account, TenantAccountJoin.role).join(
  434. TenantAccountJoin, Account.id == TenantAccountJoin.account_id
  435. ).filter(Account.email == invitation_data['email'], TenantAccountJoin.tenant_id == tenant.id).first()
  436. if not tenant_account:
  437. return None
  438. account = tenant_account[0]
  439. if not account:
  440. return None
  441. if invitation_data['account_id'] != str(account.id):
  442. return None
  443. return {
  444. 'account': account,
  445. 'data': invitation_data,
  446. 'tenant': tenant,
  447. }
  448. @classmethod
  449. def _get_invitation_by_token(cls, token: str, workspace_id: str, email: str) -> Optional[Dict[str, str]]:
  450. if workspace_id is not None and email is not None:
  451. email_hash = sha256(email.encode()).hexdigest()
  452. cache_key = f'member_invite_token:{workspace_id}, {email_hash}:{token}'
  453. account_id = redis_client.get(cache_key)
  454. if not account_id:
  455. return None
  456. return {
  457. 'account_id': account_id.decode('utf-8'),
  458. 'email': email,
  459. 'workspace_id': workspace_id,
  460. }
  461. else:
  462. data = redis_client.get(cls._get_invitation_token_key(token))
  463. if not data:
  464. return None
  465. invitation = json.loads(data)
  466. return invitation