Skip to content

Commit

Permalink
Merge pull request #232 from crestalnetwork/fix/x-auth
Browse files Browse the repository at this point in the history
Fix: rename result_uri to redirect uri
  • Loading branch information
hyacinthus authored Feb 11, 2025
2 parents e0a23ab + e56e0cf commit 5bd783c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 25 deletions.
19 changes: 10 additions & 9 deletions app/services/twitter/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@ def __init__(self, *, client_id, redirect_uri, scope, client_secret=None):
self._client.create_code_verifier(128), "S256"
)

def get_authorization_url(self, agent_id: str, result_uri: str):
def get_authorization_url(self, agent_id: str, redirect_uri: str):
"""Get the authorization URL to redirect the user to
Args:
agent_id: ID of the agent to authenticate
result_uri: URI to redirect to after authorization
redirect_uri: URI to redirect to after authorization
"""
state_params = {"agent_id": agent_id, "result_uri": result_uri}
state_params = {"agent_id": agent_id, "redirect_uri": redirect_uri}
authorization_url, _ = self.authorization_url(
"https://x.com/i/oauth2/authorize",
state=urlencode(state_params),
Expand Down Expand Up @@ -73,6 +73,7 @@ def refresh(self, refresh_token: str):
oauth2_user_handler = OAuth2UserHandler(
client_id=config.twitter_oauth2_client_id,
client_secret=config.twitter_oauth2_client_secret,
# backend uri point to twitter_oauth_callback
redirect_uri=config.twitter_oauth2_redirect_uri,
scope=[
"tweet.read",
Expand Down Expand Up @@ -101,28 +102,28 @@ class TwitterAuthResponse(BaseModel):
response_model=TwitterAuthResponse,
dependencies=[Depends(verify_jwt)],
)
async def get_twitter_auth_url(agent_id: str, result_uri: str) -> TwitterAuthResponse:
async def get_twitter_auth_url(agent_id: str, redirect_uri: str) -> TwitterAuthResponse:
"""Get Twitter OAuth2 authorization URL.
Args:
agent_id: ID of the agent to authenticate
result_uri: URI to redirect to after authorization
redirect_uri: DApp URI to redirect to after authorization from agentkit to DApp
Returns:
Object containing agent_id and authorization URL
"""
url = oauth2_user_handler.get_authorization_url(agent_id, result_uri)
url = oauth2_user_handler.get_authorization_url(agent_id, redirect_uri)
return TwitterAuthResponse(agent_id=agent_id, url=url)


def get_authorization_url(agent_id: str, result_uri: str) -> str:
def get_authorization_url(agent_id: str, redirect_uri: str) -> str:
"""Get Twitter OAuth2 authorization URL.
Args:
agent_id: ID of the agent to authenticate
result_uri: URI to redirect to after authorization
redirect_uri: DApp URI to redirect to after authorization from agentkit to DApp
Returns:
Authorization URL with agent_id as state parameter
"""
return oauth2_user_handler.get_authorization_url(agent_id, result_uri)
return oauth2_user_handler.get_authorization_url(agent_id, redirect_uri)
26 changes: 10 additions & 16 deletions app/services/twitter/oauth2_callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@ async def twitter_oauth_callback(
them in the database.
Args:
state: URL-encoded state containing agent_id and result_uri
state: URL-encoded state containing agent_id and redirect_uri
code: Authorization code from Twitter
Returns:
JSONResponse or RedirectResponse depending on result_uri
JSONResponse or RedirectResponse depending on redirect_uri
Raises:
HTTPException: If state/code is missing or token exchange fails
Expand All @@ -58,7 +58,7 @@ async def twitter_oauth_callback(
# Parse state parameter
state_params = parse_qs(state)
agent_id = state_params.get("agent_id", [""])[0]
result_uri = state_params.get("result_uri", [""])[0]
redirect_uri = state_params.get("redirect_uri", [""])[0]

if not agent_id:
raise HTTPException(
Expand Down Expand Up @@ -100,12 +100,10 @@ async def twitter_oauth_callback(
# Commit changes
await agent_data.save()

# Handle response based on result_uri
if result_uri and is_valid_url(result_uri):
# Handle response based on redirect_uri
if redirect_uri and is_valid_url(redirect_uri):
params = {"twitter_auth": "success", "username": username}
redirect_url = (
f"{result_uri}{'&' if '?' in result_uri else '?'}{urlencode(params)}"
)
redirect_url = f"{redirect_uri}{'&' if '?' in redirect_uri else '?'}{urlencode(params)}"
return RedirectResponse(url=redirect_url)
else:
return JSONResponse(
Expand All @@ -117,21 +115,17 @@ async def twitter_oauth_callback(
)
except HTTPException as http_exc:
# Handle error response
if result_uri and is_valid_url(result_uri):
if redirect_uri and is_valid_url(redirect_uri):
params = {"twitter_auth": "failed", "error": str(http_exc.detail)}
redirect_url = (
f"{result_uri}{'&' if '?' in result_uri else '?'}{urlencode(params)}"
)
redirect_url = f"{redirect_uri}{'&' if '?' in redirect_uri else '?'}{urlencode(params)}"
return RedirectResponse(url=redirect_url)
# Re-raise HTTP exceptions to preserve their status codes
raise http_exc
except Exception as e:
# Handle error response for unexpected errors
if result_uri and is_valid_url(result_uri):
if redirect_uri and is_valid_url(redirect_uri):
params = {"twitter_auth": "failed", "error": str(e)}
redirect_url = (
f"{result_uri}{'&' if '?' in result_uri else '?'}{urlencode(params)}"
)
redirect_url = f"{redirect_uri}{'&' if '?' in redirect_uri else '?'}{urlencode(params)}"
return RedirectResponse(url=redirect_url)
# For unexpected errors, use 500 status code
raise HTTPException(status_code=500, detail=str(e))

0 comments on commit 5bd783c

Please sign in to comment.