54 lines
2.1 KiB
Python
54 lines
2.1 KiB
Python
# 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 typing import Annotated
|
|
from fastapi import Depends, HTTPException
|
|
from pretor.utils.access import Accessor, TokenData
|
|
from pretor.core.database.table.user import UserAuthority
|
|
from pretor.utils.ray_hook import ray_actor_hook
|
|
|
|
async def get_authority(user_id: str) -> UserAuthority:
|
|
from pretor.utils.error import UserNotExistError
|
|
postgres_database = ray_actor_hook("postgres_database").postgres_database
|
|
try:
|
|
user_authority = await postgres_database.get_user_authority.remote(user_id=user_id)
|
|
return user_authority
|
|
except UserNotExistError:
|
|
raise HTTPException(
|
|
status_code=401,
|
|
detail="用户不存在或已被删除,请重新登录"
|
|
)
|
|
except Exception as e:
|
|
# Check if it's a RayTaskError wrapping UserNotExistError
|
|
if "UserNotExistError" in str(e):
|
|
raise HTTPException(
|
|
status_code=401,
|
|
detail="用户不存在或已被删除,请重新登录"
|
|
)
|
|
raise
|
|
|
|
class RoleChecker:
|
|
def __init__(self, **kwargs):
|
|
self.allowed_roles = kwargs.get("allowed_roles", )
|
|
|
|
async def __call__(self,
|
|
token_data: Annotated[TokenData, Depends(Accessor.get_current_user)]):
|
|
user_authority = await get_authority(token_data.user_id)
|
|
if user_authority < self.allowed_roles:
|
|
raise HTTPException(
|
|
status_code=403,
|
|
detail={"message": f"User {token_data.user_id} does not have allowed roles"},
|
|
)
|
|
return token_data
|
|
|