oidc: Add support for requiring groups

This commit is contained in:
Mustafa Gezen 2023-07-02 07:54:37 +02:00
parent 9b8cf8f34a
commit a880481cc7
2 changed files with 18 additions and 1 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
.idea
__pycache__ __pycache__
.venv .venv
*.egg-info *.egg-info

View File

@ -1,4 +1,4 @@
from dataclasses import dataclass from dataclasses import dataclass, field
import httpx import httpx
@ -9,6 +9,7 @@ from fastapi.responses import JSONResponse
@dataclass @dataclass
class OIDCConfig: class OIDCConfig:
userinfo_endpoint: str userinfo_endpoint: str
required_groups: list[str] = field(default_factory=list)
def add_oidc_middleware(app: FastAPI, config: OIDCConfig): def add_oidc_middleware(app: FastAPI, config: OIDCConfig):
@ -65,6 +66,21 @@ def add_oidc_middleware(app: FastAPI, config: OIDCConfig):
content={"detail": "Invalid token"}, content={"detail": "Invalid token"},
) )
if config.required_groups:
if not userinfo.get("groups"):
return JSONResponse(
status_code=401,
content={"detail": "User does not have any groups"},
)
if not any(
group in userinfo["groups"] for group in config.required_groups
):
return JSONResponse(
status_code=401,
content={"detail": "User does not have required groups"},
)
request.state.userinfo = userinfo request.state.userinfo = userinfo
return await call_next(request) return await call_next(request)