account_service.py 23 KB

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