account_service.py 21 KB

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