Selaa lähdekoodia

Authentication variables are now in the env file

proxy2core
root 2 kuukautta sitten
vanhempi
commit
ef36fba1c1
8 muutettua tiedostoa jossa 55 lisäystä ja 39 poistoa
  1. BIN
      __pycache__/app.cpython-310.pyc
  2. BIN
      __pycache__/security.cpython-310.pyc
  3. +2
    -2
      app.old
  4. +11
    -2
      app.py
  5. +15
    -0
      config_env.py
  6. BIN
      routes/__pycache__/reslevis.cpython-310.pyc
  7. +12
    -27
      routes/reslevis.py
  8. +15
    -8
      security.py

BIN
__pycache__/app.cpython-310.pyc Näytä tiedosto


BIN
__pycache__/security.cpython-310.pyc Näytä tiedosto


+ 2
- 2
app.old Näytä tiedosto

@@ -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 Näytä tiedosto

@@ -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 Näytä tiedosto

@@ -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")


BIN
routes/__pycache__/reslevis.cpython-310.pyc Näytä tiedosto


+ 12
- 27
routes/reslevis.py Näytä tiedosto

@@ -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 Näytä tiedosto

@@ -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"]


Ladataan…
Peruuta
Tallenna