-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Google OAuth endpoints and UI login (#804)
- Loading branch information
Showing
21 changed files
with
513 additions
and
56 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -116,4 +116,4 @@ djqs.db | |
.pdm.toml | ||
|
||
# oauth credentials | ||
client_secret.json | ||
client_secret* |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
108 changes: 108 additions & 0 deletions
108
datajunction-server/datajunction_server/api/authentication/google.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
""" | ||
Google OAuth Router | ||
""" | ||
import logging | ||
import secrets | ||
from datetime import timedelta | ||
from http import HTTPStatus | ||
from typing import Optional | ||
from urllib.parse import urljoin, urlparse | ||
|
||
import google.auth.transport.requests | ||
import google.oauth2.credentials | ||
import requests | ||
from fastapi import APIRouter, Depends, Request | ||
from google.oauth2 import id_token | ||
from sqlmodel import Session, select | ||
from starlette.responses import RedirectResponse | ||
|
||
from datajunction_server.constants import AUTH_COOKIE, LOGGED_IN_FLAG_COOKIE | ||
from datajunction_server.errors import DJException | ||
from datajunction_server.internal.authentication.basic import get_password_hash | ||
from datajunction_server.internal.authentication.google import flow, get_authorize_url | ||
from datajunction_server.internal.authentication.tokens import create_token | ||
from datajunction_server.models.user import OAuthProvider, User | ||
from datajunction_server.utils import Settings, get_session, get_settings | ||
|
||
_logger = logging.getLogger(__name__) | ||
router = APIRouter(tags=["Google OAuth"]) | ||
settings = get_settings() | ||
|
||
|
||
@router.get("/google/login/", status_code=HTTPStatus.FOUND) | ||
async def login(target: Optional[str] = None): | ||
""" | ||
Login using Google OAuth | ||
""" | ||
return RedirectResponse( | ||
url=get_authorize_url(state=target), | ||
status_code=HTTPStatus.FOUND, | ||
) | ||
|
||
|
||
@router.get("/google/token/") | ||
async def get_access_token( | ||
request: Request, | ||
state: Optional[str] = None, | ||
error: Optional[str] = None, | ||
session: Session = Depends(get_session), | ||
setting: Settings = Depends(get_settings), | ||
): | ||
""" | ||
Perform a token exchange, exchanging a google auth code for a google access token. | ||
The google access token is then used to request user information and return a JWT | ||
cookie. If the user does not already exist, a new user is created. | ||
""" | ||
if error: | ||
raise DJException( | ||
http_status_code=HTTPStatus.UNAUTHORIZED, | ||
message="Ran into an error during Google auth: {error}", | ||
) | ||
hostname = urlparse(settings.url).hostname | ||
url = str(request.url) | ||
flow.fetch_token(authorization_response=url) | ||
credentials = flow.credentials | ||
request_session = requests.session() | ||
token_request = google.auth.transport.requests.Request(session=request_session) | ||
user_data = id_token.verify_oauth2_token( | ||
id_token=credentials._id_token, # pylint: disable=protected-access | ||
request=token_request, | ||
audience=setting.google_oauth_client_id, | ||
) | ||
|
||
existing_user = session.exec( | ||
select(User).where(User.email == user_data["email"]), | ||
).one_or_none() | ||
if existing_user: | ||
_logger.info("OAuth user found") | ||
user = existing_user | ||
else: | ||
_logger.info("OAuth user does not exist, creating a new user") | ||
new_user = User( | ||
username=user_data["email"], | ||
email=user_data["email"], | ||
password=get_password_hash(secrets.token_urlsafe(13)), | ||
name=user_data["name"], | ||
oauth_provider=OAuthProvider.GOOGLE, | ||
) | ||
session.add(new_user) | ||
session.commit() | ||
session.refresh(new_user) | ||
user = new_user | ||
response = RedirectResponse(url=urljoin(settings.frontend_host, state)) # type: ignore | ||
response.set_cookie( | ||
AUTH_COOKIE, | ||
create_token({"username": user.email}, expires_delta=timedelta(days=365)), | ||
httponly=True, | ||
samesite="none", | ||
secure=True, | ||
domain=hostname, | ||
) | ||
response.set_cookie( | ||
LOGGED_IN_FLAG_COOKIE, | ||
"true", | ||
samesite="none", | ||
secure=True, | ||
domain=hostname, | ||
) | ||
return response |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
104 changes: 104 additions & 0 deletions
104
datajunction-server/datajunction_server/internal/authentication/google.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
""" | ||
Google OAuth helper functions | ||
""" | ||
import logging | ||
import secrets | ||
from http import HTTPStatus | ||
from typing import Optional | ||
from urllib.parse import urljoin | ||
|
||
import google_auth_oauthlib.flow | ||
import requests | ||
from google.auth.external_account_authorized_user import Credentials | ||
from sqlmodel import select | ||
|
||
from datajunction_server.errors import DJException | ||
from datajunction_server.internal.authentication.basic import get_password_hash | ||
from datajunction_server.models.user import OAuthProvider, User | ||
from datajunction_server.utils import get_session, get_settings | ||
|
||
_logger = logging.getLogger(__name__) | ||
|
||
settings = get_settings() | ||
flow = ( # pylint: disable=invalid-name | ||
google_auth_oauthlib.flow.Flow.from_client_secrets_file( | ||
settings.google_oauth_client_secret_file, | ||
scopes=[ | ||
"https://www.googleapis.com/auth/userinfo.profile", | ||
"https://www.googleapis.com/auth/userinfo.email", | ||
"openid", | ||
], | ||
redirect_uri=urljoin(settings.url, "/google/token/"), | ||
) | ||
if settings.google_oauth_client_secret_file | ||
else None | ||
) | ||
|
||
|
||
def get_authorize_url( | ||
state: Optional[str] = None, | ||
) -> google_auth_oauthlib.flow.Flow: | ||
""" | ||
Get the authorize url for a Google OAuth app | ||
""" | ||
authorization_url, _ = flow.authorization_url( | ||
access_type="offline", | ||
include_granted_scopes="true", | ||
prompt="consent", | ||
state=state, | ||
) | ||
return authorization_url | ||
|
||
|
||
def get_google_access_token( | ||
authorization_response_url: str, | ||
) -> Credentials: | ||
""" | ||
Exchange an authorization token for an access token | ||
""" | ||
flow.fetch_token(authorization_response=authorization_response_url) | ||
return flow.credentials | ||
|
||
|
||
def get_google_user(token: str) -> User: | ||
""" | ||
Get the google user using an access token | ||
""" | ||
headers = {"Accept": "application/json", "Authorization": f"Bearer {token}"} | ||
response = requests.get( | ||
"https://www.googleapis.com/oauth2/v2/userinfo?alt=json", | ||
headers=headers, | ||
timeout=10, | ||
) | ||
if not response.ok: | ||
raise DJException( | ||
http_status_code=HTTPStatus.FORBIDDEN, | ||
message=f"Error retrieving Google user: {response.text}", | ||
) | ||
user_data = response.json() | ||
if "message" in user_data and user_data["message"] == "Bad credentials": | ||
raise DJException( | ||
http_status_code=HTTPStatus.FORBIDDEN, | ||
message=f"Error retrieving Google user: {response.text}", | ||
) | ||
session = next(get_session()) | ||
existing_user = session.exec( | ||
select(User).where(User.email == user_data["login"]), | ||
).one_or_none() | ||
if existing_user: | ||
_logger.info("OAuth user found") | ||
user = existing_user | ||
else: | ||
_logger.info("OAuth user does not exist, creating a new user") | ||
new_user = User( | ||
username=user_data["email"], | ||
email=user_data["email"], | ||
password=get_password_hash(secrets.token_urlsafe(13)), | ||
name=user_data["name"], | ||
oauth_provider=OAuthProvider.GOOGLE, | ||
) | ||
session.add(new_user) | ||
session.commit() | ||
session.refresh(new_user) | ||
user = new_user | ||
return user |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.