Skip to content

Commit 9f5a84c

Browse files
committed
Remove unused and unnecessary stuff
1 parent e4b2445 commit 9f5a84c

File tree

2 files changed

+16
-109
lines changed

2 files changed

+16
-109
lines changed

fastapi_oauth2/base.py

Lines changed: 12 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import json
22
import os
3-
import sys
4-
import warnings
53
from typing import Any, Dict, List, Optional
64

75
import httpx
@@ -10,15 +8,6 @@
108
from starlette.requests import Request
119
from starlette.responses import RedirectResponse
1210

13-
if sys.version_info >= (3, 8):
14-
from typing import TypedDict
15-
else:
16-
from typing_extensions import TypedDict
17-
18-
DiscoveryDocument = TypedDict(
19-
"DiscoveryDocument", {"authorization_endpoint": str, "token_endpoint": str, "userinfo_endpoint": str}
20-
)
21-
2211

2312
class UnsetStateWarning(UserWarning):
2413
"""Warning about unset state parameter"""
@@ -41,13 +30,16 @@ class SSOBase:
4130
_oauth_client: Optional[WebApplicationClient] = None
4231
additional_headers: Optional[Dict[str, Any]] = None
4332

33+
authorization_endpoint: str = NotImplemented
34+
token_endpoint: str = NotImplemented
35+
userinfo_endpoint: str = NotImplemented
36+
4437
def __init__(
4538
self,
4639
client_id: str,
4740
client_secret: str,
4841
redirect_uri: Optional[str] = None,
4942
allow_insecure_http: bool = False,
50-
use_state: bool = False,
5143
scope: Optional[List[str]] = None,
5244
):
5345
self.client_id = client_id
@@ -56,33 +48,11 @@ def __init__(
5648
self.allow_insecure_http = allow_insecure_http
5749
if allow_insecure_http:
5850
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
59-
# TODO: Remove use_state argument and attribute
60-
if use_state:
61-
warnings.warn(
62-
(
63-
"Argument 'use_state' of SSOBase's constructor is deprecated and will be removed in "
64-
"future releases. Use 'state' argument of individual methods instead."
65-
),
66-
DeprecationWarning,
67-
)
6851
self.scope = scope or self.scope
69-
self._refresh_token: Optional[str] = None
70-
self._state: Optional[str] = None
71-
72-
@property
73-
def state(self) -> Optional[str]:
74-
"""Gets state as it was returned from the server"""
75-
if self._state is None:
76-
warnings.warn(
77-
"'state' parameter is unset. This means the server either "
78-
"didn't return state (was this expected?) or 'verify_and_process' hasn't been called yet.",
79-
UnsetStateWarning,
80-
)
81-
return self._state
52+
self.state: Optional[str] = None
8253

8354
@property
8455
def oauth_client(self) -> WebApplicationClient:
85-
"""OAuth Client to help us generate requests and parse responses"""
8656
if self.client_id == NotImplemented:
8757
raise NotImplementedError(f"Provider {self.provider} not supported")
8858
if self._oauth_client is None:
@@ -91,55 +61,29 @@ def oauth_client(self) -> WebApplicationClient:
9161

9262
@property
9363
def access_token(self) -> Optional[str]:
94-
"""Access token from token endpoint"""
9564
return self.oauth_client.access_token
9665

9766
@property
9867
def refresh_token(self) -> Optional[str]:
99-
"""Get refresh token (if returned from provider)"""
100-
return self._refresh_token or self.oauth_client.refresh_token
68+
return self.oauth_client.refresh_token
10169

10270
@classmethod
10371
async def openid_from_response(cls, response: dict) -> dict:
104-
"""Return {dict} object from provider's user info endpoint response"""
10572
raise NotImplementedError(f"Provider {cls.provider} not supported")
10673

107-
async def get_discovery_document(self) -> DiscoveryDocument:
108-
"""Get discovery document containing handy urls"""
109-
raise NotImplementedError(f"Provider {self.provider} not supported")
110-
111-
@property
112-
async def authorization_endpoint(self) -> Optional[str]:
113-
"""Return `authorization_endpoint` from discovery document"""
114-
discovery = await self.get_discovery_document()
115-
return discovery.get("authorization_endpoint")
116-
117-
@property
118-
async def token_endpoint(self) -> Optional[str]:
119-
"""Return `token_endpoint` from discovery document"""
120-
discovery = await self.get_discovery_document()
121-
return discovery.get("token_endpoint")
122-
123-
@property
124-
async def userinfo_endpoint(self) -> Optional[str]:
125-
"""Return `userinfo_endpoint` from discovery document"""
126-
discovery = await self.get_discovery_document()
127-
return discovery.get("userinfo_endpoint")
128-
12974
async def get_login_url(
13075
self,
13176
*,
13277
redirect_uri: Optional[str] = None,
13378
params: Optional[Dict[str, Any]] = None,
13479
state: Optional[str] = None,
13580
) -> Any:
136-
"""Return prepared login url. This is low-level, see {get_login_redirect} instead."""
13781
params = params or {}
13882
redirect_uri = redirect_uri or self.redirect_uri
13983
if redirect_uri is None:
14084
raise ValueError("redirect_uri must be provided, either at construction or request time")
14185
return self.oauth_client.prepare_request_uri(
142-
await self.authorization_endpoint, redirect_uri=redirect_uri, state=state, scope=self.scope, **params
86+
self.authorization_endpoint, redirect_uri=redirect_uri, state=state, scope=self.scope, **params
14387
)
14488

14589
async def get_login_redirect(
@@ -149,20 +93,8 @@ async def get_login_redirect(
14993
params: Optional[Dict[str, Any]] = None,
15094
state: Optional[str] = None,
15195
) -> RedirectResponse:
152-
"""Return redirect response by Starlette to login page of Oauth SSO provider
153-
154-
Arguments:
155-
redirect_uri {Optional[str]} -- Override redirect_uri specified on this instance (default: None)
156-
params {Optional[Dict[str, Any]]} -- Add additional query parameters to the login request.
157-
state {Optional[str]} -- Add state parameter. This is useful if you want
158-
the server to return something specific back to you.
159-
160-
Returns:
161-
RedirectResponse -- Starlette response (may directly be returned from FastAPI)
162-
"""
16396
login_uri = await self.get_login_url(redirect_uri=redirect_uri, params=params, state=state)
164-
response = RedirectResponse(login_uri, 303)
165-
return response
97+
return RedirectResponse(login_uri, 303)
16698

16799
async def verify_and_process(
168100
self,
@@ -172,21 +104,11 @@ async def verify_and_process(
172104
headers: Optional[Dict[str, Any]] = None,
173105
redirect_uri: Optional[str] = None,
174106
) -> Optional[dict]:
175-
"""Get FastAPI (Starlette) Request object and process login.
176-
This handler should be used for your /callback path.
177-
178-
Arguments:
179-
request {Request} -- FastAPI request object (or Starlette)
180-
params {Optional[Dict[str, Any]]} -- Optional additional query parameters to pass to the provider
181-
182-
Returns:
183-
Optional[dict] -- dict if the login was successfully
184-
"""
185107
headers = headers or {}
186108
code = request.query_params.get("code")
187109
if code is None:
188110
raise SSOLoginError(400, "'code' parameter was not found in callback request")
189-
self._state = request.query_params.get("state")
111+
self.state = request.query_params.get("state")
190112
return await self.process_login(
191113
code, request, params=params, additional_headers=headers, redirect_uri=redirect_uri
192114
)
@@ -200,13 +122,6 @@ async def process_login(
200122
additional_headers: Optional[Dict[str, Any]] = None,
201123
redirect_uri: Optional[str] = None,
202124
) -> Optional[dict]:
203-
"""This method should be called from callback endpoint to verify the user and request user info endpoint.
204-
This is low level, you should use {verify_and_process} instead.
205-
206-
Arguments:
207-
params {Optional[Dict[str, Any]]} -- Optional additional query parameters to pass to the provider
208-
additional_headers {Optional[Dict[str, Any]]} -- Optional additional headers to be added to all requests
209-
"""
210125
params = params or {}
211126
additional_headers = additional_headers or {}
212127
additional_headers.update(self.additional_headers or {})
@@ -220,7 +135,7 @@ async def process_login(
220135
current_path = f"{scheme}://{url.netloc}{url.path}"
221136

222137
token_url, headers, body = self.oauth_client.prepare_token_request(
223-
await self.token_endpoint,
138+
self.token_endpoint,
224139
authorization_response=current_url,
225140
redirect_url=redirect_uri or self.redirect_uri or current_path,
226141
code=code,
@@ -236,11 +151,10 @@ async def process_login(
236151
async with httpx.AsyncClient() as session:
237152
response = await session.post(token_url, headers=headers, content=body, auth=auth)
238153
content = response.json()
239-
self._refresh_token = content.get("refresh_token")
240154
self.oauth_client.parse_request_body_response(json.dumps(content))
241155

242-
uri, headers, _ = self.oauth_client.add_token(await self.userinfo_endpoint)
156+
uri, headers, _ = self.oauth_client.add_token(self.userinfo_endpoint)
243157
response = await session.get(uri, headers=headers)
244158
content = response.json()
245159

246-
return await self.openid_from_response(content)
160+
return content

fastapi_oauth2/github.py

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from .base import DiscoveryDocument, SSOBase
1+
from .base import SSOBase
22

33

44
class GithubSSO(SSOBase):
@@ -8,13 +8,6 @@ class GithubSSO(SSOBase):
88
scope = ["user:email"]
99
additional_headers = {"accept": "application/json"}
1010

11-
async def get_discovery_document(self) -> DiscoveryDocument:
12-
return {
13-
"authorization_endpoint": "https://github.com/login/oauth/authorize",
14-
"token_endpoint": "https://github.com/login/oauth/access_token",
15-
"userinfo_endpoint": "https://api.github.com/user",
16-
}
17-
18-
@classmethod
19-
async def openid_from_response(cls, response: dict) -> dict:
20-
return {**response, "provider": cls.provider}
11+
authorization_endpoint = "https://github.com/login/oauth/authorize"
12+
token_endpoint = "https://github.com/login/oauth/access_token"
13+
userinfo_endpoint = "https://api.github.com/user"

0 commit comments

Comments
 (0)