account_service.py 21 KB

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