refactor(keycloak): remove authentik naming and switch to keycloak-only paths
This commit is contained in:
@@ -53,7 +53,7 @@ from app.schemas.api_clients import (
|
||||
from app.schemas.permissions import PermissionGrantRequest, PermissionRevokeRequest
|
||||
from app.security.admin_guard import require_admin_principal
|
||||
from app.security.api_client_auth import hash_api_key
|
||||
from app.services.authentik_admin_service import AuthentikAdminService
|
||||
from app.services.idp_admin_service import KeycloakAdminService
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/admin",
|
||||
@@ -133,7 +133,7 @@ def _generate_api_key() -> str:
|
||||
return secrets.token_urlsafe(36)
|
||||
|
||||
|
||||
def _sync_member_to_authentik(
|
||||
def _sync_member_to_idp(
|
||||
*,
|
||||
user_sub: str | None,
|
||||
idp_user_id: str | None,
|
||||
@@ -143,9 +143,9 @@ def _sync_member_to_authentik(
|
||||
is_active: bool,
|
||||
) -> dict[str, str]:
|
||||
if not email:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="email_required_for_authentik_sync")
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="email_required_for_idp_sync")
|
||||
settings = get_settings()
|
||||
service = AuthentikAdminService(settings=settings)
|
||||
service = KeycloakAdminService(settings=settings)
|
||||
result = service.ensure_user(
|
||||
sub=user_sub,
|
||||
email=email,
|
||||
@@ -590,11 +590,11 @@ def upsert_member(
|
||||
resolved_sub = payload.user_sub
|
||||
resolved_username = payload.username
|
||||
idp_user_id = None
|
||||
if payload.sync_to_authentik:
|
||||
if payload.sync_to_idp:
|
||||
seed_sub = payload.user_sub or payload.username
|
||||
if not seed_sub:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="user_sub_or_username_required")
|
||||
sync = _sync_member_to_authentik(
|
||||
sync = _sync_member_to_idp(
|
||||
user_sub=seed_sub,
|
||||
idp_user_id=idp_user_id,
|
||||
username=payload.username,
|
||||
@@ -642,8 +642,8 @@ def update_member(
|
||||
next_is_active = payload.is_active if payload.is_active is not None else row.is_active
|
||||
|
||||
idp_user_id = row.idp_user_id
|
||||
if payload.sync_to_authentik:
|
||||
sync = _sync_member_to_authentik(
|
||||
if payload.sync_to_idp:
|
||||
sync = _sync_member_to_idp(
|
||||
user_sub=row.user_sub,
|
||||
idp_user_id=row.idp_user_id,
|
||||
username=next_username,
|
||||
@@ -681,7 +681,7 @@ def delete_member(
|
||||
if not row:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="user_not_found")
|
||||
settings = get_settings()
|
||||
service = AuthentikAdminService(settings=settings)
|
||||
service = KeycloakAdminService(settings=settings)
|
||||
service.delete_user(
|
||||
idp_user_id=row.idp_user_id,
|
||||
email=row.email,
|
||||
@@ -703,7 +703,7 @@ def reset_member_password(
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="user_not_found")
|
||||
settings = get_settings()
|
||||
service = AuthentikAdminService(settings=settings)
|
||||
service = KeycloakAdminService(settings=settings)
|
||||
result = service.reset_password(
|
||||
idp_user_id=user.idp_user_id,
|
||||
email=user.email,
|
||||
|
||||
@@ -5,60 +5,18 @@ import httpx
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
|
||||
from app.core.config import get_settings
|
||||
from app.schemas.login import (
|
||||
LoginRequest,
|
||||
LoginResponse,
|
||||
OIDCAuthUrlResponse,
|
||||
OIDCCodeExchangeRequest,
|
||||
)
|
||||
from app.schemas.login import LoginRequest, LoginResponse, OIDCAuthUrlResponse, OIDCCodeExchangeRequest
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _resolve_username_by_email(settings, email: str) -> str | None:
|
||||
# Authentik-only helper. Keycloak does not need this path.
|
||||
if settings.use_keycloak:
|
||||
return None
|
||||
if not settings.authentik_base_url or not settings.authentik_admin_token:
|
||||
return None
|
||||
|
||||
url = urljoin(settings.authentik_base_url.rstrip("/") + "/", "api/v3/core/users/")
|
||||
try:
|
||||
resp = httpx.get(
|
||||
url,
|
||||
params={"email": email},
|
||||
timeout=10,
|
||||
verify=settings.authentik_verify_tls,
|
||||
headers={
|
||||
"Authorization": f"Bearer {settings.authentik_admin_token}",
|
||||
"Accept": "application/json",
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
if resp.status_code >= 400:
|
||||
return None
|
||||
|
||||
data = resp.json()
|
||||
results = data.get("results") if isinstance(data, dict) else None
|
||||
if not isinstance(results, list) or not results:
|
||||
return None
|
||||
|
||||
username = results[0].get("username")
|
||||
return username if isinstance(username, str) and username else None
|
||||
|
||||
|
||||
@router.post("/login", response_model=LoginResponse)
|
||||
def login(payload: LoginRequest) -> LoginResponse:
|
||||
settings = get_settings()
|
||||
client_id = settings.idp_client_id or settings.idp_audience
|
||||
|
||||
if not settings.idp_base_url or not client_id or not settings.idp_client_secret:
|
||||
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="authentik_login_not_configured")
|
||||
|
||||
token_endpoint = settings.idp_token_endpoint
|
||||
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="idp_login_not_configured")
|
||||
|
||||
form = {
|
||||
"grant_type": "password",
|
||||
@@ -68,31 +26,16 @@ def login(payload: LoginRequest) -> LoginResponse:
|
||||
"password": payload.password,
|
||||
"scope": "openid profile email",
|
||||
}
|
||||
|
||||
def _token_request(form_data: dict[str, str]) -> httpx.Response:
|
||||
try:
|
||||
resp = httpx.post(
|
||||
token_endpoint,
|
||||
data=form_data,
|
||||
settings.idp_token_endpoint,
|
||||
data=form,
|
||||
timeout=10,
|
||||
verify=settings.idp_verify_tls,
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
)
|
||||
return resp
|
||||
|
||||
try:
|
||||
resp = _token_request(form)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="authentik_unreachable") from exc
|
||||
|
||||
# If user entered email, try resolving username and retry once.
|
||||
if resp.status_code >= 400 and "@" in payload.username:
|
||||
resolved = _resolve_username_by_email(settings, payload.username)
|
||||
if resolved and resolved != payload.username:
|
||||
form["username"] = resolved
|
||||
try:
|
||||
resp = _token_request(form)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="authentik_unreachable") from exc
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="idp_unreachable") from exc
|
||||
|
||||
if resp.status_code >= 400:
|
||||
logger.warning("idp password grant failed: status=%s body=%s", resp.status_code, resp.text)
|
||||
@@ -101,8 +44,7 @@ def login(payload: LoginRequest) -> LoginResponse:
|
||||
data = resp.json()
|
||||
token = data.get("access_token")
|
||||
if not token:
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="authentik_missing_access_token")
|
||||
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="idp_missing_access_token")
|
||||
return LoginResponse(
|
||||
access_token=token,
|
||||
token_type=data.get("token_type", "Bearer"),
|
||||
@@ -123,28 +65,26 @@ def get_oidc_authorize_url(
|
||||
settings = get_settings()
|
||||
client_id = settings.idp_client_id or settings.idp_audience
|
||||
if not settings.idp_base_url or not client_id:
|
||||
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="authentik_login_not_configured")
|
||||
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="idp_login_not_configured")
|
||||
|
||||
authorize_endpoint = settings.idp_authorize_endpoint
|
||||
state = secrets.token_urlsafe(24)
|
||||
query = {
|
||||
"client_id": client_id,
|
||||
"response_type": "code",
|
||||
"scope": "openid profile email",
|
||||
"redirect_uri": redirect_uri,
|
||||
"state": state,
|
||||
"state": secrets.token_urlsafe(24),
|
||||
"prompt": prompt or "login",
|
||||
}
|
||||
if login_hint:
|
||||
query["login_hint"] = login_hint
|
||||
if idp_hint and settings.use_keycloak:
|
||||
if idp_hint:
|
||||
query["kc_idp_hint"] = idp_hint
|
||||
if code_challenge:
|
||||
query["code_challenge"] = code_challenge
|
||||
query["code_challenge_method"] = code_challenge_method or "S256"
|
||||
|
||||
params = httpx.QueryParams(query)
|
||||
return OIDCAuthUrlResponse(authorize_url=f"{authorize_endpoint}?{params}")
|
||||
return OIDCAuthUrlResponse(authorize_url=f"{settings.idp_authorize_endpoint}?{params}")
|
||||
|
||||
|
||||
@router.post("/oidc/exchange", response_model=LoginResponse)
|
||||
@@ -152,9 +92,8 @@ def exchange_oidc_code(payload: OIDCCodeExchangeRequest) -> LoginResponse:
|
||||
settings = get_settings()
|
||||
client_id = settings.idp_client_id or settings.idp_audience
|
||||
if not settings.idp_base_url or not client_id or not settings.idp_client_secret:
|
||||
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="authentik_login_not_configured")
|
||||
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="idp_login_not_configured")
|
||||
|
||||
token_endpoint = settings.idp_token_endpoint
|
||||
form = {
|
||||
"grant_type": "authorization_code",
|
||||
"client_id": client_id,
|
||||
@@ -167,24 +106,23 @@ def exchange_oidc_code(payload: OIDCCodeExchangeRequest) -> LoginResponse:
|
||||
|
||||
try:
|
||||
resp = httpx.post(
|
||||
token_endpoint,
|
||||
settings.idp_token_endpoint,
|
||||
data=form,
|
||||
timeout=10,
|
||||
verify=settings.idp_verify_tls,
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="authentik_unreachable") from exc
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="idp_unreachable") from exc
|
||||
|
||||
if resp.status_code >= 400:
|
||||
logger.warning("idp auth-code exchange failed: status=%s body=%s", resp.status_code, resp.text)
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="authentik_code_exchange_failed")
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="idp_code_exchange_failed")
|
||||
|
||||
data = resp.json()
|
||||
token = data.get("access_token")
|
||||
if not token:
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="authentik_missing_access_token")
|
||||
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="idp_missing_access_token")
|
||||
return LoginResponse(
|
||||
access_token=token,
|
||||
token_type=data.get("token_type", "Bearer"),
|
||||
|
||||
@@ -6,11 +6,11 @@ from app.db.session import get_db
|
||||
from app.repositories.permissions_repo import PermissionsRepository
|
||||
from app.schemas.internal import InternalUpsertUserBySubResponse
|
||||
from app.repositories.users_repo import UsersRepository
|
||||
from app.schemas.authentik_admin import AuthentikEnsureUserRequest, AuthentikEnsureUserResponse
|
||||
from app.schemas.idp_admin import KeycloakEnsureUserRequest, KeycloakEnsureUserResponse
|
||||
from app.schemas.permissions import PermissionSnapshotResponse
|
||||
from app.schemas.users import UserUpsertBySubRequest
|
||||
from app.security.api_client_auth import require_api_client
|
||||
from app.services.authentik_admin_service import AuthentikAdminService
|
||||
from app.services.idp_admin_service import KeycloakAdminService
|
||||
from app.services.permission_service import PermissionService
|
||||
|
||||
router = APIRouter(prefix="/internal", tags=["internal"], dependencies=[Depends(require_api_client)])
|
||||
@@ -56,16 +56,15 @@ def get_permission_snapshot(
|
||||
return PermissionService.build_snapshot(user_sub=user_sub, permissions=permissions)
|
||||
|
||||
|
||||
@router.post("/authentik/users/ensure", response_model=AuthentikEnsureUserResponse)
|
||||
@router.post("/idp/users/ensure", response_model=AuthentikEnsureUserResponse)
|
||||
@router.post("/keycloak/users/ensure", response_model=AuthentikEnsureUserResponse)
|
||||
def ensure_authentik_user(
|
||||
payload: AuthentikEnsureUserRequest,
|
||||
@router.post("/idp/users/ensure", response_model=KeycloakEnsureUserResponse)
|
||||
@router.post("/keycloak/users/ensure", response_model=KeycloakEnsureUserResponse)
|
||||
def ensure_idp_user(
|
||||
payload: KeycloakEnsureUserRequest,
|
||||
db: Session = Depends(get_db),
|
||||
) -> AuthentikEnsureUserResponse:
|
||||
) -> KeycloakEnsureUserResponse:
|
||||
settings = get_settings()
|
||||
authentik_service = AuthentikAdminService(settings=settings)
|
||||
sync_result = authentik_service.ensure_user(
|
||||
idp_service = KeycloakAdminService(settings=settings)
|
||||
sync_result = idp_service.ensure_user(
|
||||
sub=payload.user_sub,
|
||||
email=payload.email,
|
||||
username=payload.username,
|
||||
@@ -78,7 +77,7 @@ def ensure_authentik_user(
|
||||
if sync_result.user_sub:
|
||||
resolved_sub = sync_result.user_sub
|
||||
if not resolved_sub:
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="authentik_missing_sub")
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="idp_missing_sub")
|
||||
users_repo.upsert_by_sub(
|
||||
user_sub=resolved_sub,
|
||||
username=payload.username,
|
||||
@@ -87,4 +86,4 @@ def ensure_authentik_user(
|
||||
is_active=payload.is_active,
|
||||
idp_user_id=sync_result.user_id,
|
||||
)
|
||||
return AuthentikEnsureUserResponse(idp_user_id=sync_result.user_id, action=sync_result.action)
|
||||
return KeycloakEnsureUserResponse(idp_user_id=sync_result.user_id, action=sync_result.action)
|
||||
|
||||
@@ -5,9 +5,9 @@ from sqlalchemy.orm import Session
|
||||
from app.db.session import get_db
|
||||
from app.repositories.permissions_repo import PermissionsRepository
|
||||
from app.repositories.users_repo import UsersRepository
|
||||
from app.schemas.auth import AuthentikPrincipal, MeSummaryResponse
|
||||
from app.schemas.auth import KeycloakPrincipal, MeSummaryResponse
|
||||
from app.schemas.permissions import PermissionSnapshotResponse
|
||||
from app.security.authentik_jwt import require_authenticated_principal
|
||||
from app.security.idp_jwt import require_authenticated_principal
|
||||
from app.services.permission_service import PermissionService
|
||||
|
||||
router = APIRouter(prefix="/me", tags=["me"])
|
||||
@@ -15,7 +15,7 @@ router = APIRouter(prefix="/me", tags=["me"])
|
||||
|
||||
@router.get("", response_model=MeSummaryResponse)
|
||||
def get_me(
|
||||
principal: AuthentikPrincipal = Depends(require_authenticated_principal),
|
||||
principal: KeycloakPrincipal = Depends(require_authenticated_principal),
|
||||
db: Session = Depends(get_db),
|
||||
) -> MeSummaryResponse:
|
||||
try:
|
||||
@@ -39,7 +39,7 @@ def get_me(
|
||||
|
||||
@router.get("/permissions/snapshot", response_model=PermissionSnapshotResponse)
|
||||
def get_my_permission_snapshot(
|
||||
principal: AuthentikPrincipal = Depends(require_authenticated_principal),
|
||||
principal: KeycloakPrincipal = Depends(require_authenticated_principal),
|
||||
db: Session = Depends(get_db),
|
||||
) -> PermissionSnapshotResponse:
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user