]> git.ipfire.org Git - pbs.git/commitdiff
API: Add helper function to fetch the principal
authorMichael Tremer <michael.tremer@ipfire.org>
Mon, 16 Jun 2025 17:20:22 +0000 (17:20 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Mon, 16 Jun 2025 17:20:22 +0000 (17:20 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/api/auth.py

index d5420f087a624fa48d2a9f3edea1710cc3832246..db960a0318783293017d3f653501570fde0e0416 100644 (file)
@@ -77,6 +77,26 @@ def create_token(subject, type, expires_after, **kwargs):
 
        return jwt.encode(payload, TOKEN_SECRET, algorithm=TOKEN_ALGO)
 
+def get_principal(token):
+       """
+               Returns the authenticated principal from the given token
+       """
+       try:
+               payload = jwt.decode(token, TOKEN_SECRET, algorithms=[TOKEN_ALGO])
+
+       # Fail if we could not decode the token
+       except jwt.InvalidTokenError as e:
+               print(e)
+               raise fastapi.HTTPException(status_code=401, detail="Invalid refresh token")
+
+       # Extract the principal
+       principal = payload.get("sub")
+       if not principal:
+               raise fastapi.HTTPException(status_code=401, detail="Invalid refresh token")
+
+       # XXX Should this hit the database to check the principal exists?
+
+       return principal
 
 @router.post("/user")
 async def auth_user(credentials: fastapi.security.OAuth2PasswordRequestForm =
@@ -117,18 +137,8 @@ class RefreshRequest(pydantic.BaseModel):
 
 @router.post("/refresh")
 async def auth_refresh(data: RefreshRequest):
-       try:
-               payload = jwt.decode(data.refresh_token, TOKEN_SECRET, algorithms=[TOKEN_ALGO])
-
-       # Fail if we could not decode the token
-       except jwt.InvalidTokenError as e:
-               print(e)
-               raise fastapi.HTTPException(status_code=401, detail="Invalid refresh token")
-
-       # Extract the principal
-       principal = payload.get("sub")
-       if not principal:
-               raise fastapi.HTTPException(status_code=401, detail="Invalid refresh token")
+       # Fetch the principal from the given token
+       principal = get_principal(data.refresh_token)
 
        # XXX Check if the principal actually still exists