# Copyright 2026 zhaoxi826 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from kilostar.core.postgres_database.model.user import User from sqlalchemy import select from kilostar.utils.error import UserNotExistError, UserPasswordError from kilostar.core.postgres_database.database_exception import database_exception from kilostar.core.postgres_database.model.user import UserAuthority from kilostar.utils.access import Accessor class AuthDatabase: """AuthDatabase 核心组件类。 这是一个数据库操作层 (DAO/Repository) 封装类,专注于处理实体模型与关系型数据库表之间的映射。它将复杂的 SQL 查询、跨表 Join 和事务回滚逻辑进行了高级抽象,向上层服务暴露简洁的数据读写接口。""" def __init__(self, async_session_maker): self.async_session_maker = async_session_maker @database_exception async def add_user(self, user_name: str, hashed_password: str) -> User: """创建并持久化新的 user 实体。 接收构建参数,执行必要的数据校验与默认值填充后,将新记录安全地写入底层存储或系统注册表中。 Args: user_name (str): 赋予该实体的人类可读名称或标题字符串,主要用于前端 UI 展示、日志记录或模糊检索。 hashed_password (str): 控制逻辑流向的具体字符串参数,指定了期望的 hashed password 内容。 Returns: (User): 经由当前业务模型加工处理后所输出的具体数据实例或领域模型对象。""" from ulid import ULID async with self.async_session_maker() as session: # Check if any users exist statement = select(User).limit(1) results = await session.execute(statement) existing_user = results.first() authority = UserAuthority.USER if existing_user is None: authority = UserAuthority.SUPER_ADMINISTRATOR user = User( user_id=str(ULID()), user_name=user_name, hashed_password=hashed_password, user_authority=authority, ) session.add(user) await session.commit() await session.refresh(user) return user @database_exception async def change_password(self, user_name, old_password, new_password) -> User: """执行与 change password 相关的核心业务流转操作。 该方法封装了具体的算法策略或状态控制逻辑,确保操作能够在事务上下文中被原子且一致地执行。 Args: user_name: 赋予该实体的人类可读名称或标题字符串,主要用于前端 UI 展示、日志记录或模糊检索。 old_password: 参与 change password 逻辑运算或数据构建的上下文依赖对象。 new_password: 参与 change password 逻辑运算或数据构建的上下文依赖对象。 Returns: (User): 经由当前业务模型加工处理后所输出的具体数据实例或领域模型对象。""" async with self.async_session_maker() as session: statement = select(User).where(User.user_name == user_name) results = await session.execute(statement) user = results.scalar_one_or_none() if user is None: raise UserNotExistError() if not Accessor.verify_password(old_password, user.hashed_password): raise UserPasswordError() user.hashed_password = new_password session.add(user) await session.commit() await session.refresh(user) return user @database_exception async def delete_user(self, user_name: str) -> None: """安全地移除或注销 user。 执行物理删除或逻辑删除操作,并妥善清理相关的关联数据及占用资源。 Args: user_name (str): 赋予该实体的人类可读名称或标题字符串,主要用于前端 UI 展示、日志记录或模糊检索。 Returns: (None): 经由当前业务模型加工处理后所输出的具体数据实例或领域模型对象。""" async with self.async_session_maker() as session: statement = select(User).where(User.user_name == user_name) results = await session.execute(statement) user = results.scalar_one_or_none() if user is None: raise UserNotExistError() session.delete(user) await session.commit() @database_exception async def delete_user_by_id(self, user_id: str) -> None: """安全地移除或注销 user by id。 执行物理删除或逻辑删除操作,并妥善清理相关的关联数据及占用资源。 Args: user_id (str): 目标对象的唯一全局标识符 (UUID/ULID),用于在数据库表或缓存结构中精准匹配该 user 实例。 Returns: (None): 经由当前业务模型加工处理后所输出的具体数据实例或领域模型对象。""" async with self.async_session_maker() as session: user = await session.get(User, user_id) if user is None: raise UserNotExistError() session.delete(user) await session.commit() @database_exception async def login_user(self, user_name: str) -> str: """执行与 login user 相关的核心业务流转操作。 该方法封装了具体的算法策略或状态控制逻辑,确保操作能够在事务上下文中被原子且一致地执行。 Args: user_name (str): 赋予该实体的人类可读名称或标题字符串,主要用于前端 UI 展示、日志记录或模糊检索。 Returns: (str): 处理流程所输出的具体字符串产物,可能是新生成的 ID 序列、格式化好的文本片段或 LLM 推理的回答内容。""" async with self.async_session_maker() as session: statement = select(User).where(User.user_name == user_name) results = await session.execute(statement) user = results.scalar_one_or_none() if user is None: raise UserNotExistError() return user @database_exception async def get_all_users(self) -> list[User]: """检索并获取特定的 all users 数据集合或实例对象。 根据提供的查询条件或上下文凭证,从数据库、缓存或第三方服务中读取对应的资源状态。 Returns: (list[User]): 经过筛选、排序或分页处理后的实体对象列表集合。""" async with self.async_session_maker() as session: statement = select(User) results = await session.execute(statement) users = results.scalars().all() return list(users) @database_exception async def get_user_authority(self, user_id: str) -> UserAuthority: """检索并获取特定的 user authority 数据集合或实例对象。 根据提供的查询条件或上下文凭证,从数据库、缓存或第三方服务中读取对应的资源状态。 Args: user_id (str): 目标对象的唯一全局标识符 (UUID/ULID),用于在数据库表或缓存结构中精准匹配该 user 实例。 Returns: (UserAuthority): 经由当前业务模型加工处理后所输出的具体数据实例或领域模型对象。""" async with self.async_session_maker() as session: user = await session.get(User, user_id) if user is None: raise UserNotExistError() return user.user_authority @database_exception async def change_user_authority( self, user_id: str, new_authority: UserAuthority ) -> User: """ Changes the authority level of a specific user. Args: user_id: The ID of the user whose authority is to be changed. new_authority: The new authority level to assign to the user. Returns: User: The updated user object. Raises: UserNotExistError: If the specified user does not exist. """ async with self.async_session_maker() as session: user = await session.get(User, user_id) if user is None: raise UserNotExistError() user.user_authority = new_authority session.add(user) await session.commit() await session.refresh(user) return user