user-wsc/Utils/AccessControl/AccessUtil.py

75 lines
2.0 KiB
Python
Raw Normal View History

2022-11-08 09:46:44 +08:00
import re
2022-11-07 13:53:42 +08:00
import os
import casbin
2022-11-08 09:46:44 +08:00
import requests
import pandas as pd
2022-10-20 16:29:54 +08:00
2022-11-08 09:46:44 +08:00
from typing import Optional
from fastapi import HTTPException, Header, Request
2022-10-20 16:29:54 +08:00
2022-11-08 09:46:44 +08:00
from Utils.Authentication.TokenUtil import decode_token
from Utils.UniqueCoder.TimeSerialNumUtils import create_time_serial_num
2022-10-20 16:29:54 +08:00
2022-11-08 09:46:44 +08:00
def get_user_info_from_token(token: str):
2022-11-01 14:18:09 +08:00
user_info = decode_token(token).get("user_info")
if not user_info:
raise HTTPException(status_code=400, detail="Invalid Token")
2022-11-08 09:46:44 +08:00
return user_info
def match_req_url(regex: str, request: Request):
req_url = request.url.__str__()
m = re.search(regex, req_url)
if not m:
raise HTTPException(status_code=400, detail="Invalid Request")
return m
def get_rap_by_name(name):
url = "http://test.fecribd.com/api/user/role/role_access_policy/view?name={}"
url = url.format(name)
res = requests.post(url=url)
return res.json()
def rbac(request: Request, token: Optional[str] = Header(...)):
user_info = get_user_info_from_token(token)
sub = user_info.get("role")
raps = get_rap_by_name(name=sub)
req_url = request.url.__str__()
2022-11-08 10:09:34 +08:00
if sub == "管理员":
return True
2022-11-08 09:46:44 +08:00
for rap in raps:
regex = rap.get("obj")
m = re.search(regex, req_url)
2022-11-01 14:18:09 +08:00
2022-11-08 09:46:44 +08:00
if m:
df = pd.json_normalize(raps)
policy_file = create_time_serial_num(prefix="policy", suffix="")
df.to_csv(r".\Utils\AccessControl\{}.csv".format(policy_file), header=False, index=False)
2022-10-20 16:29:54 +08:00
2022-11-08 09:46:44 +08:00
e = casbin.Enforcer(
os.getcwd() + r"\Utils\AccessControl\model.conf",
os.getcwd() + r"\Utils\AccessControl\{}.csv".format(policy_file)
)
2022-11-07 13:53:42 +08:00
2022-11-08 09:46:44 +08:00
os.remove(r".\Utils\AccessControl\{}.csv".format(policy_file))
2022-11-07 13:53:42 +08:00
2022-11-08 09:46:44 +08:00
obj = rap.get("obj")
act = rap.get("act")
2022-10-20 16:29:54 +08:00
2022-11-08 09:46:44 +08:00
if not e.enforce(sub, obj, act):
raise HTTPException(status_code=202, detail="No Access")
2022-11-07 13:53:42 +08:00
2022-11-08 09:46:44 +08:00
return True
2022-11-01 14:02:58 +08:00
2022-11-08 09:46:44 +08:00
raise HTTPException(status_code=400, detail="Invalid Request")