瀏覽代碼

Authentication variables are now in the env file

master
root 1 周之前
父節點
當前提交
ef36fba1c1
共有 8 個檔案被更改,包括 55 行新增39 行删除
  1. 二進制
      __pycache__/app.cpython-310.pyc
  2. 二進制
      __pycache__/security.cpython-310.pyc
  3. +2
    -2
      app.old
  4. +11
    -2
      app.py
  5. +15
    -0
      config_env.py
  6. 二進制
      routes/__pycache__/reslevis.cpython-310.pyc
  7. +12
    -27
      routes/reslevis.py
  8. +15
    -8
      security.py

二進制
__pycache__/app.cpython-310.pyc 查看文件


二進制
__pycache__/security.cpython-310.pyc 查看文件


+ 2
- 2
app.old 查看文件

@@ -64,8 +64,8 @@ reslevis_router = _reslevis.router
from fastapi import FastAPI, Security from fastapi import FastAPI, Security
from fastapi.security import OAuth2AuthorizationCodeBearer from fastapi.security import OAuth2AuthorizationCodeBearer


AUTH_URL = "https://192.168.1.3:10002/realms/API.Server.local/protocol/openid-connect/auth"
TOKEN_URL = "https://192.168.1.3:10002/realms/API.Server.local/protocol/openid-connect/token"
#AUTH_URL = "https://192.168.1.3:10002/realms/API.Server.local/protocol/openid-connect/auth"
#TOKEN_URL = "https://192.168.1.3:10002/realms/API.Server.local/protocol/openid-connect/token"


oauth2 = OAuth2AuthorizationCodeBearer( oauth2 = OAuth2AuthorizationCodeBearer(
authorizationUrl=AUTH_URL, authorizationUrl=AUTH_URL,


+ 11
- 2
app.py 查看文件

@@ -9,6 +9,9 @@ from typing import Any, Dict, List, Optional
# import wave # import wave
import os import os
import shutil import shutil
# import enviroment variables
import config_env
#other
from pathlib import Path from pathlib import Path
from tempfile import NamedTemporaryFile from tempfile import NamedTemporaryFile
from typing import Callable from typing import Callable
@@ -63,8 +66,14 @@ reslevis_router = _reslevis.router
from fastapi import FastAPI, Security from fastapi import FastAPI, Security
from fastapi.security import OAuth2AuthorizationCodeBearer from fastapi.security import OAuth2AuthorizationCodeBearer


AUTH_URL = "https://192.168.1.3:10002/realms/API.Server.local/protocol/openid-connect/auth"
TOKEN_URL = "https://192.168.1.3:10002/realms/API.Server.local/protocol/openid-connect/token"
#AUTH_URL = "https://10.251.0.30:10002/realms/API.Server.local/protocol/openid-connect/auth"
#AUTH_URL = "https://192.168.1.3:10002/realms/API.Server.local/protocol/openid-connect/auth"
#TOKEN_URL = "https://10.251.0.30:10002/realms/API.Server.local/protocol/openid-connect/token"
#TOKEN_URL = "https://192.168.1.3:10002/realms/API.Server.local/protocol/openid-connect/token"


AUTH_URL = config_env.KEYCLOAK_AUTH_URL
TOKEN_URL = config_env.KEYCLOAK_TOKEN_URL


oauth2 = OAuth2AuthorizationCodeBearer( oauth2 = OAuth2AuthorizationCodeBearer(
authorizationUrl=AUTH_URL, authorizationUrl=AUTH_URL,


+ 15
- 0
config_env.py 查看文件

@@ -0,0 +1,15 @@
#This file reads the .env where the variables should be stored
import os
from dotenv import load_dotenv

load_dotenv()

SECRET = os.getenv("SECRET")
KEYCLOAK_AUDIENCE = os.getenv("KEYCLOAK_AUDIENCE")
KEYCLOAK_SERVER = os.getenv("KEYCLOAK_SERVER")
KEYCLOAK_ISSUER = os.getenv("KEYCLOAK_ISSUER")
KEYCLOAK_PROTOCOL_ENDPOINT = os.getenv("KEYCLOAK_PROTOCOL_ENDPOINT")
KEYCLOAK_JWKS_URL = os.getenv("KEYCLOAK_JWKS_URL")
KEYCLOAK_AUTH_URL = os.getenv("KEYCLOAK_AUTH_URL")
KEYCLOAK_TOKEN_URL = os.getenv("KEYCLOAK_TOKEN_URL")


二進制
routes/__pycache__/reslevis.cpython-310.pyc 查看文件


+ 12
- 27
routes/reslevis.py 查看文件

@@ -6,15 +6,11 @@ from schemas.reslevis import (
) )
from logica_reslevis.gateway import GatewayJsonRepository from logica_reslevis.gateway import GatewayJsonRepository


# importa le dipendenze di sicurezza
from security import get_current_user, require_roles
from security import get_current_user


gateway_repo = GatewayJsonRepository() gateway_repo = GatewayJsonRepository()
router = APIRouter() router = APIRouter()


# -----------------------
# Endpoints pubblici (se vuoi che restino pubblici, niente Depends)
# -----------------------
@router.get("/getBuildings", response_model=List[BuildingItem], tags=["Reslevis"]) @router.get("/getBuildings", response_model=List[BuildingItem], tags=["Reslevis"])
def getBuildings(): def getBuildings():
return [] return []
@@ -27,9 +23,6 @@ def getPlans():
def getZones(): def getZones():
return [] return []


# -----------------------
# Endpoints protetti: richiedono almeno un Bearer token valido
# -----------------------
@router.get("/getGateways", response_model=List[GatewayItem], tags=["Reslevis"], dependencies=[Depends(get_current_user)]) @router.get("/getGateways", response_model=List[GatewayItem], tags=["Reslevis"], dependencies=[Depends(get_current_user)])
def getGateways(): def getGateways():
return gateway_repo.list() return gateway_repo.list()
@@ -54,18 +47,10 @@ def getAlarms():
def getTracks(): def getTracks():
return [] return []


# -----------------------
# Operazioni di scrittura su Gateway:
# - Token valido
# - Ruolo richiesto (esempio: "reslevis:write")
# Cambia il nome ruolo per allinearlo a come lo hai definito in Keycloak
# -----------------------
write_role = "reslevis:write" # esempio; usa il tuo realm/client role

@router.post( @router.post(
"/postGateway", "/postGateway",
tags=["Reslevis"], tags=["Reslevis"],
dependencies=[Depends(require_roles(write_role))]
dependencies=[Depends(get_current_user)]
) )
def postGateway(item: GatewayItem): def postGateway(item: GatewayItem):
try: try:
@@ -79,7 +64,7 @@ def postGateway(item: GatewayItem):
@router.put( @router.put(
"/updateGateway", "/updateGateway",
tags=["Reslevis"], tags=["Reslevis"],
dependencies=[Depends(require_roles(write_role))]
dependencies=[Depends(get_current_user)]
) )
def updateGateway(item: GatewayItem): def updateGateway(item: GatewayItem):
try: try:
@@ -96,7 +81,7 @@ def updateGateway(item: GatewayItem):
@router.delete( @router.delete(
"/removeGateway/{gateway_id}", "/removeGateway/{gateway_id}",
tags=["Reslevis"], tags=["Reslevis"],
dependencies=[Depends(require_roles(write_role))]
dependencies=[Depends(get_current_user)]
) )
def removeGateway(gateway_id: str): def removeGateway(gateway_id: str):
try: try:
@@ -107,35 +92,35 @@ def removeGateway(gateway_id: str):
except Exception as e: except Exception as e:
raise HTTPException(status_code=500, detail=f"Errore interno: {e}") raise HTTPException(status_code=500, detail=f"Errore interno: {e}")


@router.post("/postBuilding", tags=["Reslevis"], dependencies=[Depends(require_roles(write_role))])
@router.post("/postBuilding", tags=["Reslevis"], dependencies=[Depends(get_current_user)])
def postBuilding(item: BuildingItem): def postBuilding(item: BuildingItem):
return {"message": "OK"} return {"message": "OK"}


@router.post("/postPlan", tags=["Reslevis"], dependencies=[Depends(require_roles(write_role))])
@router.post("/postPlan", tags=["Reslevis"], dependencies=[Depends(get_current_user)])
def postPlan(item: PlanItem): def postPlan(item: PlanItem):
return {"message": "OK"} return {"message": "OK"}


@router.post("/postZone", tags=["Reslevis"], dependencies=[Depends(require_roles(write_role))])
@router.post("/postZone", tags=["Reslevis"], dependencies=[Depends(get_current_user)])
def postZone(item: ZoneItem): def postZone(item: ZoneItem):
return {"message": "OK"} return {"message": "OK"}


@router.post("/postTracker", tags=["Reslevis"], dependencies=[Depends(require_roles(write_role))])
@router.post("/postTracker", tags=["Reslevis"], dependencies=[Depends(get_current_user)])
def postTracker(item: TrackerItem): def postTracker(item: TrackerItem):
return {"message": "OK"} return {"message": "OK"}


@router.post("/postOperator", tags=["Reslevis"], dependencies=[Depends(require_roles(write_role))])
@router.post("/postOperator", tags=["Reslevis"], dependencies=[Depends(get_current_user)])
def postOperator(item: OperatorItem): def postOperator(item: OperatorItem):
return {"message": "OK"} return {"message": "OK"}


@router.post("/postSubject", tags=["Reslevis"], dependencies=[Depends(require_roles(write_role))])
@router.post("/postSubject", tags=["Reslevis"], dependencies=[Depends(get_current_user)])
def postSubject(item: SubjectItem): def postSubject(item: SubjectItem):
return {"message": "OK"} return {"message": "OK"}


@router.post("/postAlarm", tags=["Reslevis"], dependencies=[Depends(require_roles(write_role))])
@router.post("/postAlarm", tags=["Reslevis"], dependencies=[Depends(get_current_user)])
def postAlarm(item: AlarmItem): def postAlarm(item: AlarmItem):
return {"message": "OK"} return {"message": "OK"}


@router.post("/postTrack", tags=["Reslevis"], dependencies=[Depends(require_roles(write_role))])
@router.post("/postTrack", tags=["Reslevis"], dependencies=[Depends(get_current_user)])
def postTrack(item: TrackItem): def postTrack(item: TrackItem):
return {"message": "OK"} return {"message": "OK"}



+ 15
- 8
security.py 查看文件

@@ -3,6 +3,7 @@ from typing import Dict, Any, List, Optional
import os import os
import logging import logging
import httpx import httpx
import config_env
from jose import jwt, JWTError from jose import jwt, JWTError
from fastapi import HTTPException, status, Depends from fastapi import HTTPException, status, Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
@@ -10,14 +11,20 @@ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
logger = logging.getLogger("security") logger = logging.getLogger("security")


# === CONFIG === # === CONFIG ===
KEYCLOAK_ISSUER = os.getenv(
"KEYCLOAK_ISSUER",
"https://192.168.1.3:10002/realms/API.Server.local",
)
KEYCLOAK_JWKS_URL = os.getenv(
"KEYCLOAK_JWKS_URL",
"https://192.168.1.3:10002/realms/API.Server.local/protocol/openid-connect/certs",
)
#KEYCLOAK_ISSUER = os.getenv(
# "KEYCLOAK_ISSUER",
# "https://10.251.0.30:10002/realms/API.Server.local",
#"https://192.168.1.3:10002/realms/API.Server.local",
#)
#KEYCLOAK_JWKS_URL = os.getenv(
# "KEYCLOAK_JWKS_URL",
# "https://10.251.0.30:10002/realms/API.Server.local/protocol/openid-connect/certs",
#"https://192.168.1.3:10002/realms/API.Server.local/protocol/openid-connect/certs",
#)

KEYCLOAK_ISSUER = config_env.KEYCLOAK_ISSUER
KEYCLOAK_JWKS_URL = config_env.KEYCLOAK_JWKS_URL

KEYCLOAK_AUDIENCE = os.getenv("KEYCLOAK_AUDIENCE", "Fastapi") KEYCLOAK_AUDIENCE = os.getenv("KEYCLOAK_AUDIENCE", "Fastapi")


ALGORITHMS = ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512"] ALGORITHMS = ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512"]


Loading…
取消
儲存