account_service.py 17 KB

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