account_service.py 15 KB

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