account_service.py 21 KB

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