account_service.py 18 KB

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