Skip to content

Commit

Permalink
Add API key token generation endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
logerzerox committed Feb 24, 2025
1 parent 7ab5f3e commit 748faff
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
22 changes: 22 additions & 0 deletions py/core/main/api/v3/users_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,28 @@ def __init__(
self.github_redirect_uri = os.environ.get("GITHUB_REDIRECT_URI")

def _setup_routes(self):
@self.router.post(
"/users/generate-tokens",
response_model=WrappedTokenResponse,
openapi_extra={
"x-codeSamples": [
{
"lang": "cURL",
"source": "curl -X POST https://api.example.com/v3/users/generate-tokens -H 'x-api-key: YOUR_API_KEY'"
}
]
}
)
@self.base_endpoint
async def generate_tokens_via_api_key(
auth_user=Depends(self.providers.auth.auth_wrapper(public=True))
) -> WrappedTokenResponse:
"""Generate new access and refresh tokens using API key authentication."""
result = await self.services.auth.generate_tokens_via_api_key(
user_id=auth_user.id
)
return result

@self.router.post(
"/users",
# dependencies=[Depends(self.rate_limit_dependency)],
Expand Down
4 changes: 4 additions & 0 deletions py/core/main/services/auth_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,3 +330,7 @@ async def list_user_api_keys(self, user_id: UUID) -> list[dict]:
dict: Contains the list of API keys
"""
return await self.providers.auth.list_user_api_keys(user_id)

async def generate_tokens_via_api_key(self, user_id: UUID) -> dict[str, Token]:
"""Expose the provider method through the service layer."""
return await self.providers.auth.generate_tokens_via_api_key(user_id)
16 changes: 16 additions & 0 deletions py/core/providers/auth/r2r_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -699,3 +699,19 @@ async def oauth_callback_handler(
"access_token": Token(token=access_token, token_type="access"),
"refresh_token": Token(token=refresh_token, token_type="refresh"),
}

async def generate_tokens_via_api_key(self, user_id: UUID) -> dict[str, Token]:
"""Generate new tokens for API key authenticated users."""
user = await self.database_provider.users_handler.get_user_by_id(user_id)

access_token = self.create_access_token(
data={"sub": normalize_email(user.email)}
)
refresh_token = self.create_refresh_token(
data={"sub": normalize_email(user.email)}
)

return {
"access_token": Token(token=access_token, token_type="access"),
"refresh_token": Token(token=refresh_token, token_type="refresh"),
}

0 comments on commit 748faff

Please sign in to comment.