Skip to content

Commit

Permalink
Add API endpoint to fetch user Zenodo token (#342)
Browse files Browse the repository at this point in the history
  • Loading branch information
petebachant authored Feb 11, 2025
1 parent ee596ae commit 7c87ae4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
12 changes: 12 additions & 0 deletions backend/app/api/routes/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,18 @@ def post_user_zenodo_auth(
return Message(message="success")


class ZenodoTokenResponse(BaseModel):
access_token: str


@router.get("/user/zenodo-token")
def get_user_zenodo_token(
session: SessionDep, current_user: CurrentUser
) -> ZenodoTokenResponse:
token = users.get_zenodo_token(session=session, user=current_user)
return ZenodoTokenResponse(access_token=token)


@router.get("/user/storage")
def get_user_storage(
session: SessionDep,
Expand Down
20 changes: 16 additions & 4 deletions backend/app/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import requests
from fastapi import HTTPException
from sqlmodel import Session, select
from requests.exceptions import JSONDecodeError

import app.stripe
from app import utcnow
Expand Down Expand Up @@ -185,11 +186,13 @@ def get_zenodo_token(session: Session, user: User) -> str:
"""Get a user's decrypted Zenodo token, automatically refreshing if
necessary.
"""
if user.zenodo_token is None:
raise HTTPException(401, "User needs to authenticate with Zenodo")
# Refresh token if necessary
# Should also handle tokens that don't exist?
# TODO: Use with_for_update
if user.zenodo_token.expires <= utcnow():
logger.info("Refreshing Zenodo token")
logger.info(f"Refreshing Zenodo token for {user.email}")
resp = requests.post(
"https://zenodo.org/oauth/token",
data=dict(
Expand All @@ -199,10 +202,19 @@ def get_zenodo_token(session: Session, user: User) -> str:
refresh_token=decrypt_secret(user.zenodo_token.refresh_token),
),
)
logger.info("Refreshed Zenodo token")
zenodo_resp = resp.json()
logger.info(f"Refreshed Zenodo token; status code: {resp.status_code}")
try:
zenodo_resp = resp.json()
except JSONDecodeError:
zenodo_resp = {}
logger.info(f"Zenodo token response keys: {list(zenodo_resp.keys())}")
# TODO: Handle failure, since all are 200 response codes
# Handle failure
if resp.status_code != 200:
msg = zenodo_resp.get("error", "Failed to authenticate")
logger.error(
f"Failed to refresh Zenodo token for {user.email}: {msg}"
)
raise HTTPException(resp.status_code, msg)
save_zenodo_token(
session,
user=user,
Expand Down

0 comments on commit 7c87ae4

Please sign in to comment.