account_service.py 21 KB

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