Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update google auth #46

Merged
merged 1 commit into from
Oct 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 14 additions & 39 deletions backend/src/app/api/routes/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
from typing import Annotated, Any

import requests
from fastapi import APIRouter, Depends, HTTPException, Response
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.security import OAuth2PasswordRequestForm

from app import crud
Expand Down Expand Up @@ -133,25 +133,12 @@ def recover_password_html_content(email: str, session: SessionDep) -> Any:
)


# Redirect user to Google's OAuth2 login page
@router.get("/login/google")
def login_google():
google_auth_url = (
"https://accounts.google.com/o/oauth2/v2/auth?"
f"client_id={settings.GOOGLE_CLIENT_ID}&"
f"redirect_uri={settings.GOOGLE_REDIRECT_URI}&"
"response_type=code&"
"scope=email profile"
)
return RedirectResponse(google_auth_url)


# Handle Google OAuth callback
@router.get("/auth/google")
def google_oauth(session: SessionDep, code: str, response: Response):
@router.post("/auth/google")
def google_oauth(session: SessionDep, body: OauthRequest) -> Token:
token_url = "https://oauth2.googleapis.com/token"
token_data = {
"code": code,
"code": body.code,
"client_id": settings.GOOGLE_CLIENT_ID,
"client_secret": settings.GOOGLE_CLIENT_SECRET,
"redirect_uri": settings.GOOGLE_REDIRECT_URI,
Expand All @@ -178,18 +165,12 @@ def google_oauth(session: SessionDep, code: str, response: Response):
user = crud.get_user_by_email(session=session, email=user_info["email"])
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
if user:
response = RedirectResponse(settings.OAUTH_REDIRECT_URI)
response.set_cookie(
key="access_token",
value=security.create_access_token(
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
return Token(
access_token=security.create_access_token(
user.id, expires_delta=access_token_expires
),
httponly=True,
secure=True,
samesite="none",
domain=".vercel.app",
)
)
return response

# Check if the app is open for new user registration
if not settings.USERS_OPEN_REGISTRATION:
Expand All @@ -208,17 +189,12 @@ def google_oauth(session: SessionDep, code: str, response: Response):
}
)
user = crud.create_user_oauth(session=session, user_create=user_create)

response = RedirectResponse(settings.OAUTH_REDIRECT_URI)
response.set_cookie(
key="access_token",
value=security.create_access_token(user.id, expires_delta=access_token_expires),
httponly=True,
secure=True,
samesite="none",
domain=".vercel.app",
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
return Token(
access_token=security.create_access_token(
user.id, expires_delta=access_token_expires
)
)
return response


# Handle Github OAuth callback
Expand All @@ -233,7 +209,6 @@ def github_oauth(session: SessionDep, body: OauthRequest) -> Token:
headers = {"Accept": "application/json"}

token_r = requests.post(token_url, data=token_data, headers=headers)
print(token_r.json())
token_json = token_r.json()
if "error" in token_json:
raise HTTPException(
Expand Down
24 changes: 24 additions & 0 deletions frontend/app/callback/google/actions.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"use server";
import initiateClient from "@/lib/api";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { cookies } from "next/headers";

export async function getAccessTokenGoogleAuth(code: string) {
const client = initiateClient();
const { data, error } = await client.POST("/api/v1/auth/google", {
body: {
code: code,
} as { code: string },
cache: "no-store",
});
if (error) {
console.log(error);
// redirect("/login");
}
if (data) {
cookies().set("access_token", data.access_token);
// revalidatePath("/", "layout");
redirect("/dashboard");
}
}
31 changes: 31 additions & 0 deletions frontend/app/callback/google/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"use client";

// callback function to handle OAuth2 authorization code flow, authenticators will redirect to this page
// after the user has authenticated on their platoform (e.g., Google, GitHub, etc.)

import { useEffect, useState } from "react";
import { getAccessTokenGoogleAuth } from "./actions";

const BACKEND_URL = process.env.NEXT_PUBLIC_API_BASE_URL;

export default function Callback() {
const [hasFetched, setHasFetched] = useState(false);
useEffect(() => {
if (!hasFetched) {
const queryParams = new URLSearchParams(window.location.search);
const code = queryParams.get("code");
if (code) {
const getAccessTokenGoogleAuthwithCode = getAccessTokenGoogleAuth.bind(
null,
code as string
);
getAccessTokenGoogleAuthwithCode();
setHasFetched(true);
} else {
console.error("Authorization code is missing");
}
}
}, [hasFetched]);

return <div>Processing login...</div>;
}
2 changes: 1 addition & 1 deletion frontend/lib/api/openapi.json

Large diffs are not rendered by default.

27 changes: 6 additions & 21 deletions frontend/lib/api/v1.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,9 @@ export interface paths {
*/
post: operations["recover_password_html_content_api_v1_password_recovery_html_content__email__post"];
};
"/api/v1/login/google": {
/** Login Google */
get: operations["login_google_api_v1_login_google_get"];
};
"/api/v1/auth/google": {
/** Google Oauth */
get: operations["google_oauth_api_v1_auth_google_get"];
post: operations["google_oauth_api_v1_auth_google_post"];
};
"/api/v1/auth/github": {
/** Github Oauth */
Expand Down Expand Up @@ -593,29 +589,18 @@ export interface operations {
};
};
};
/** Login Google */
login_google_api_v1_login_google_get: {
responses: {
/** @description Successful Response */
200: {
content: {
"application/json": unknown;
};
};
};
};
/** Google Oauth */
google_oauth_api_v1_auth_google_get: {
parameters: {
query: {
code: string;
google_oauth_api_v1_auth_google_post: {
requestBody: {
content: {
"application/json": components["schemas"]["OauthRequest"];
};
};
responses: {
/** @description Successful Response */
200: {
content: {
"application/json": unknown;
"application/json": components["schemas"]["Token"];
};
};
/** @description Validation Error */
Expand Down
Loading