account_service.py 21 KB

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