Skip to content

Commit 5f57cc2

Browse files
authored
Merge pull request #45 from Sheldenburg/bug/fix-set-cookies
change the github auth code
2 parents 4952a9c + 2f16d48 commit 5f57cc2

File tree

6 files changed

+116
-30
lines changed

6 files changed

+116
-30
lines changed

backend/src/app/api/routes/login.py

+21-25
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,14 @@
1111
from app.core import security
1212
from app.core.config import settings
1313
from app.core.security import get_password_hash
14-
from app.models import Message, NewPassword, Token, UserCreateOauth, UserPublic
14+
from app.models import (
15+
Message,
16+
NewPassword,
17+
OauthRequest,
18+
Token,
19+
UserCreateOauth,
20+
UserPublic,
21+
)
1522
from app.utils import (
1623
generate_password_reset_token,
1724
generate_reset_password_email,
@@ -215,17 +222,18 @@ def google_oauth(session: SessionDep, code: str, response: Response):
215222

216223

217224
# Handle Github OAuth callback
218-
@router.get("/auth/github")
219-
def github_oauth(session: SessionDep, code: str, response: Response):
225+
@router.post("/auth/github")
226+
def github_oauth(session: SessionDep, body: OauthRequest) -> Token:
220227
token_url = "https://github.com/login/oauth/access_token"
221228
token_data = {
222-
"code": code,
229+
"code": body.code,
223230
"client_id": settings.GH_CLIENT_ID,
224231
"client_secret": settings.GH_CLIENT_SECRET,
225232
}
226233
headers = {"Accept": "application/json"}
227234

228235
token_r = requests.post(token_url, data=token_data, headers=headers)
236+
print(token_r.json())
229237
token_json = token_r.json()
230238
if "error" in token_json:
231239
raise HTTPException(
@@ -245,20 +253,13 @@ def github_oauth(session: SessionDep, code: str, response: Response):
245253

246254
# Check if the user already exists
247255
user = crud.get_user_by_email(session=session, email=user_emails[0]["email"])
248-
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
249256
if user:
250-
response = RedirectResponse(settings.OAUTH_REDIRECT_URI)
251-
response.set_cookie(
252-
key="access_token",
253-
value=security.create_access_token(
257+
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
258+
return Token(
259+
access_token=security.create_access_token(
254260
user.id, expires_delta=access_token_expires
255-
),
256-
# httponly=True,
257-
secure=True,
258-
samesite="none",
259-
domain=".vercel.app",
261+
)
260262
)
261-
return response
262263

263264
# Check if the app is open for new user registration
264265
if not settings.USERS_OPEN_REGISTRATION:
@@ -277,14 +278,9 @@ def github_oauth(session: SessionDep, code: str, response: Response):
277278
}
278279
)
279280
user = crud.create_user_oauth(session=session, user_create=user_create)
280-
281-
response = RedirectResponse(settings.OAUTH_REDIRECT_URI)
282-
response.set_cookie(
283-
key="access_token",
284-
value=security.create_access_token(user.id, expires_delta=access_token_expires),
285-
# httponly=True,
286-
secure=True,
287-
samesite="none",
288-
domain=".vercel.app",
281+
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
282+
return Token(
283+
access_token=security.create_access_token(
284+
user.id, expires_delta=access_token_expires
285+
)
289286
)
290-
return response

backend/src/app/models.py

+4
Original file line numberDiff line numberDiff line change
@@ -193,3 +193,7 @@ class ChatPublic(SQLModel):
193193
created_at: datetime
194194
updated_at: datetime
195195
owner_id: int
196+
197+
198+
class OauthRequest(SQLModel):
199+
code: str
+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"use server";
2+
import initiateClient from "@/lib/api";
3+
import { revalidatePath } from "next/cache";
4+
import { redirect } from "next/navigation";
5+
import { cookies } from "next/headers";
6+
7+
export async function getAccessTokenGithubAuth(code: string) {
8+
const client = initiateClient();
9+
const { data, error } = await client.POST("/api/v1/auth/github", {
10+
body: {
11+
code: code,
12+
} as { code: string },
13+
cache: "no-store",
14+
});
15+
if (error) {
16+
console.log(error);
17+
// redirect("/login");
18+
}
19+
if (data) {
20+
cookies().set("access_token", data.access_token);
21+
// revalidatePath("/", "layout");
22+
redirect("/dashboard");
23+
}
24+
}

frontend/app/callback/github/page.tsx

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"use client";
2+
3+
// callback function to handle OAuth2 authorization code flow, authenticators will redirect to this page
4+
// after the user has authenticated on their platoform (e.g., Google, GitHub, etc.)
5+
6+
import { useEffect, useState } from "react";
7+
import { getAccessTokenGithubAuth } from "./actions";
8+
9+
const BACKEND_URL = process.env.NEXT_PUBLIC_API_BASE_URL;
10+
11+
export default function Callback() {
12+
const [hasFetched, setHasFetched] = useState(false);
13+
useEffect(() => {
14+
if (!hasFetched) {
15+
const queryParams = new URLSearchParams(window.location.search);
16+
const code = queryParams.get("code");
17+
if (code) {
18+
const getAccessTokenGithubAuthwithCode = getAccessTokenGithubAuth.bind(
19+
null,
20+
code as string
21+
);
22+
getAccessTokenGithubAuthwithCode();
23+
setHasFetched(true);
24+
} else {
25+
console.error("Authorization code is missing");
26+
}
27+
}
28+
}, [hasFetched]);
29+
30+
return <div>Processing login...</div>;
31+
}

frontend/lib/api/openapi.json

+1-1
Large diffs are not rendered by default.

frontend/lib/api/v1.d.ts

+35-4
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,12 @@ export interface paths {
4949
get: operations["login_google_api_v1_login_google_get"];
5050
};
5151
"/api/v1/auth/google": {
52-
/** Auth */
53-
get: operations["auth_api_v1_auth_google_get"];
52+
/** Google Oauth */
53+
get: operations["google_oauth_api_v1_auth_google_get"];
54+
};
55+
"/api/v1/auth/github": {
56+
/** Github Oauth */
57+
post: operations["github_oauth_api_v1_auth_github_post"];
5458
};
5559
"/api/v1/users/": {
5660
/**
@@ -337,6 +341,11 @@ export interface components {
337341
/** New Password */
338342
new_password: string;
339343
};
344+
/** OauthRequest */
345+
OauthRequest: {
346+
/** Code */
347+
code: string;
348+
};
340349
/** Token */
341350
Token: {
342351
/** Access Token */
@@ -595,8 +604,8 @@ export interface operations {
595604
};
596605
};
597606
};
598-
/** Auth */
599-
auth_api_v1_auth_google_get: {
607+
/** Google Oauth */
608+
google_oauth_api_v1_auth_google_get: {
600609
parameters: {
601610
query: {
602611
code: string;
@@ -617,6 +626,28 @@ export interface operations {
617626
};
618627
};
619628
};
629+
/** Github Oauth */
630+
github_oauth_api_v1_auth_github_post: {
631+
requestBody: {
632+
content: {
633+
"application/json": components["schemas"]["OauthRequest"];
634+
};
635+
};
636+
responses: {
637+
/** @description Successful Response */
638+
200: {
639+
content: {
640+
"application/json": components["schemas"]["Token"];
641+
};
642+
};
643+
/** @description Validation Error */
644+
422: {
645+
content: {
646+
"application/json": components["schemas"]["HTTPValidationError"];
647+
};
648+
};
649+
};
650+
};
620651
/**
621652
* Read Users
622653
* @description Retrieve users.

0 commit comments

Comments
 (0)