41 lines
1.6 KiB
Python
41 lines
1.6 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 functools import lru_cache
|
|
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
|
|
|
|
@lru_cache
|
|
async def get_authority(user_id: str) -> UserAuthority:
|
|
postgres_database = ray_actor_hook("postgres_database")
|
|
user_authority = await postgres_database.get_user_authority.remote(user_id=user_id)
|
|
return user_authority
|
|
|
|
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
|
|
|