Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

user_service.py 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import hashlib
  17. from datetime import datetime
  18. import peewee
  19. from werkzeug.security import generate_password_hash, check_password_hash
  20. from api.db import UserTenantRole
  21. from api.db.db_models import DB, UserTenant
  22. from api.db.db_models import User, Tenant
  23. from api.db.services.common_service import CommonService
  24. from api.utils import get_uuid, current_timestamp, datetime_format
  25. from api.db import StatusEnum
  26. from rag.settings import MINIO
  27. class UserService(CommonService):
  28. """Service class for managing user-related database operations.
  29. This class extends CommonService to provide specialized functionality for user management,
  30. including authentication, user creation, updates, and deletions.
  31. Attributes:
  32. model: The User model class for database operations.
  33. """
  34. model = User
  35. @classmethod
  36. @DB.connection_context()
  37. def filter_by_id(cls, user_id):
  38. """Retrieve a user by their ID.
  39. Args:
  40. user_id: The unique identifier of the user.
  41. Returns:
  42. User object if found, None otherwise.
  43. """
  44. try:
  45. user = cls.model.select().where(cls.model.id == user_id).get()
  46. return user
  47. except peewee.DoesNotExist:
  48. return None
  49. @classmethod
  50. @DB.connection_context()
  51. def query_user(cls, email, password):
  52. """Authenticate a user with email and password.
  53. Args:
  54. email: User's email address.
  55. password: User's password in plain text.
  56. Returns:
  57. User object if authentication successful, None otherwise.
  58. """
  59. user = cls.model.select().where((cls.model.email == email),
  60. (cls.model.status == StatusEnum.VALID.value)).first()
  61. if user and check_password_hash(str(user.password), password):
  62. return user
  63. else:
  64. return None
  65. @classmethod
  66. @DB.connection_context()
  67. def save(cls, **kwargs):
  68. if "id" not in kwargs:
  69. kwargs["id"] = get_uuid()
  70. if "password" in kwargs:
  71. kwargs["password"] = generate_password_hash(
  72. str(kwargs["password"]))
  73. kwargs["create_time"] = current_timestamp()
  74. kwargs["create_date"] = datetime_format(datetime.now())
  75. kwargs["update_time"] = current_timestamp()
  76. kwargs["update_date"] = datetime_format(datetime.now())
  77. obj = cls.model(**kwargs).save(force_insert=True)
  78. return obj
  79. @classmethod
  80. @DB.connection_context()
  81. def delete_user(cls, user_ids, update_user_dict):
  82. with DB.atomic():
  83. cls.model.update({"status": 0}).where(
  84. cls.model.id.in_(user_ids)).execute()
  85. @classmethod
  86. @DB.connection_context()
  87. def update_user(cls, user_id, user_dict):
  88. with DB.atomic():
  89. if user_dict:
  90. user_dict["update_time"] = current_timestamp()
  91. user_dict["update_date"] = datetime_format(datetime.now())
  92. cls.model.update(user_dict).where(
  93. cls.model.id == user_id).execute()
  94. class TenantService(CommonService):
  95. """Service class for managing tenant-related database operations.
  96. This class extends CommonService to provide functionality for tenant management,
  97. including tenant information retrieval and credit management.
  98. Attributes:
  99. model: The Tenant model class for database operations.
  100. """
  101. model = Tenant
  102. @classmethod
  103. @DB.connection_context()
  104. def get_info_by(cls, user_id):
  105. fields = [
  106. cls.model.id.alias("tenant_id"),
  107. cls.model.name,
  108. cls.model.llm_id,
  109. cls.model.embd_id,
  110. cls.model.rerank_id,
  111. cls.model.asr_id,
  112. cls.model.img2txt_id,
  113. cls.model.tts_id,
  114. cls.model.parser_ids,
  115. UserTenant.role]
  116. return list(cls.model.select(*fields)
  117. .join(UserTenant, on=((cls.model.id == UserTenant.tenant_id) & (UserTenant.user_id == user_id) & (UserTenant.status == StatusEnum.VALID.value) & (UserTenant.role == UserTenantRole.OWNER)))
  118. .where(cls.model.status == StatusEnum.VALID.value).dicts())
  119. @classmethod
  120. @DB.connection_context()
  121. def get_joined_tenants_by_user_id(cls, user_id):
  122. fields = [
  123. cls.model.id.alias("tenant_id"),
  124. cls.model.name,
  125. cls.model.llm_id,
  126. cls.model.embd_id,
  127. cls.model.asr_id,
  128. cls.model.img2txt_id,
  129. UserTenant.role]
  130. return list(cls.model.select(*fields)
  131. .join(UserTenant, on=((cls.model.id == UserTenant.tenant_id) & (UserTenant.user_id == user_id) & (UserTenant.status == StatusEnum.VALID.value) & (UserTenant.role == UserTenantRole.NORMAL)))
  132. .where(cls.model.status == StatusEnum.VALID.value).dicts())
  133. @classmethod
  134. @DB.connection_context()
  135. def decrease(cls, user_id, num):
  136. num = cls.model.update(credit=cls.model.credit - num).where(
  137. cls.model.id == user_id).execute()
  138. if num == 0:
  139. raise LookupError("Tenant not found which is supposed to be there")
  140. @classmethod
  141. @DB.connection_context()
  142. def user_gateway(cls, tenant_id):
  143. hashobj = hashlib.sha256(tenant_id.encode("utf-8"))
  144. return int(hashobj.hexdigest(), 16)%len(MINIO)
  145. class UserTenantService(CommonService):
  146. """Service class for managing user-tenant relationship operations.
  147. This class extends CommonService to handle the many-to-many relationship
  148. between users and tenants, managing user roles and tenant memberships.
  149. Attributes:
  150. model: The UserTenant model class for database operations.
  151. """
  152. model = UserTenant
  153. @classmethod
  154. @DB.connection_context()
  155. def filter_by_id(cls, user_tenant_id):
  156. try:
  157. user_tenant = cls.model.select().where((cls.model.id == user_tenant_id) & (cls.model.status == StatusEnum.VALID.value)).get()
  158. return user_tenant
  159. except peewee.DoesNotExist:
  160. return None
  161. @classmethod
  162. @DB.connection_context()
  163. def save(cls, **kwargs):
  164. if "id" not in kwargs:
  165. kwargs["id"] = get_uuid()
  166. obj = cls.model(**kwargs).save(force_insert=True)
  167. return obj
  168. @classmethod
  169. @DB.connection_context()
  170. def get_by_tenant_id(cls, tenant_id):
  171. fields = [
  172. cls.model.id,
  173. cls.model.user_id,
  174. cls.model.status,
  175. cls.model.role,
  176. User.nickname,
  177. User.email,
  178. User.avatar,
  179. User.is_authenticated,
  180. User.is_active,
  181. User.is_anonymous,
  182. User.status,
  183. User.update_date,
  184. User.is_superuser]
  185. return list(cls.model.select(*fields)
  186. .join(User, on=((cls.model.user_id == User.id) & (cls.model.status == StatusEnum.VALID.value) & (cls.model.role != UserTenantRole.OWNER)))
  187. .where(cls.model.tenant_id == tenant_id)
  188. .dicts())
  189. @classmethod
  190. @DB.connection_context()
  191. def get_tenants_by_user_id(cls, user_id):
  192. fields = [
  193. cls.model.tenant_id,
  194. cls.model.role,
  195. User.nickname,
  196. User.email,
  197. User.avatar,
  198. User.update_date
  199. ]
  200. return list(cls.model.select(*fields)
  201. .join(User, on=((cls.model.tenant_id == User.id) & (UserTenant.user_id == user_id) & (UserTenant.status == StatusEnum.VALID.value)))
  202. .where(cls.model.status == StatusEnum.VALID.value).dicts())
  203. @classmethod
  204. @DB.connection_context()
  205. def get_num_members(cls, user_id: str):
  206. cnt_members = cls.model.select(peewee.fn.COUNT(cls.model.id)).where(cls.model.tenant_id == user_id).scalar()
  207. return cnt_members
  208. @classmethod
  209. @DB.connection_context()
  210. def filter_by_tenant_and_user_id(cls, tenant_id, user_id):
  211. try:
  212. user_tenant = cls.model.select().where(
  213. (cls.model.tenant_id == tenant_id) & (cls.model.status == StatusEnum.VALID.value) &
  214. (cls.model.user_id == user_id)
  215. ).first()
  216. return user_tenant
  217. except peewee.DoesNotExist:
  218. return None