Updated OAuth2 router generator for better OpenAPI docs (#793)

* Added OAuth2 authorize route response_model

* Changed OAuth2 "authorize" route backend param type.

On OAuth2 router creation, an enum is created for the `authentication_backend` parameter. This allows us to generate OpenAPI docs correctly.

* Reformatted with "make format"

* Updated OAuth2 authorize url docs

- /authorize now returns 422 instead of 400 for an invalid authentication backend
This commit is contained in:
Matyáš Richter
2021-11-10 07:55:40 +01:00
committed by GitHub
parent 4aef8f8a17
commit f578a01a8b
4 changed files with 19 additions and 15 deletions

View File

@@ -229,9 +229,7 @@ Return the authorization URL for the OAuth service where you should redirect you
```
!!! fail "`422 Validation Error`"
!!! fail "`400 Bad Request`"
Unknown authentication backend.
Invalid parameters - e.g. unknown authentication backend.
### `GET /callback`

View File

@@ -79,3 +79,7 @@ class BaseOAuthAccountMixin(BaseModel):
"""Adds OAuth accounts list to a User model."""
oauth_accounts: List[BaseOAuthAccount] = []
class OAuth2AuthorizeResponse(BaseModel):
authorization_url: str

View File

@@ -1,3 +1,4 @@
import enum
from typing import Dict, List
import jwt
@@ -43,27 +44,28 @@ def get_oauth_router(
route_name=callback_route_name,
)
@router.get("/authorize", name="oauth:authorize")
AuthenticationBackendName: enum.EnumMeta = enum.Enum(
"AuthenticationBackendName",
{backend.name: backend.name for backend in authenticator.backends},
)
@router.get(
"/authorize",
name="oauth:authorize",
response_model=models.OAuth2AuthorizeResponse,
)
async def authorize(
request: Request,
authentication_backend: str,
authentication_backend: AuthenticationBackendName,
scopes: List[str] = Query(None),
):
# Check that authentication_backend exists
backend_exists = any(
backend.name == authentication_backend for backend in authenticator.backends
)
if not backend_exists:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
if redirect_url is not None:
authorize_redirect_url = redirect_url
else:
authorize_redirect_url = request.url_for(callback_route_name)
state_data = {
"authentication_backend": authentication_backend,
"authentication_backend": str(authentication_backend),
}
state = generate_state_token(state_data, state_secret)
authorization_url = await oauth_client.get_authorization_url(

View File

@@ -101,7 +101,7 @@ class TestAuthorize:
},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
async def test_success(
self,