|
1 | 1 | from typing import Annotated |
2 | 2 |
|
3 | | -from fastapi import APIRouter, Depends, Header, HTTPException, status |
| 3 | +from fastapi import APIRouter, Depends, Header, HTTPException, logger, status |
4 | 4 | from fastapi.responses import RedirectResponse |
5 | 5 | from starlette.requests import Request |
6 | 6 |
|
|
9 | 9 | from carrot.app.auth.schemas import TokenResponse, UserSigninRequest |
10 | 10 | from carrot.app.auth.services import AuthService |
11 | 11 | from carrot.app.auth.settings import AUTH_SETTINGS |
| 12 | +from carrot.settings import SETTINGS |
12 | 13 |
|
13 | 14 | auth_router = APIRouter() |
14 | 15 |
|
@@ -59,22 +60,40 @@ async def delete_token( |
59 | 60 | google: StarletteOAuth2App = oauth.create_client("google") # type: ignore |
60 | 61 |
|
61 | 62 |
|
62 | | -@auth_router.get("/oauth2/login/google", status_code=status.HTTP_200_OK) |
| 63 | +def get_redirect_uri(request: Request) -> str: |
| 64 | + uri_obj = request.url_for("receive_code") |
| 65 | + |
| 66 | + if not SETTINGS.is_local: |
| 67 | + uri_obj = uri_obj.replace(scheme="https") # nginx changes scheme to https |
| 68 | + |
| 69 | + return str(uri_obj) |
| 70 | + |
| 71 | + |
| 72 | +@auth_router.get("/oauth2/login/google", status_code=status.HTTP_307_TEMPORARY_REDIRECT) |
63 | 73 | async def get_redirect_url(request: Request): |
64 | | - redirect_uri = str(request.url_for("receive_code")) |
| 74 | + redirect_uri = get_redirect_uri(request) |
65 | 75 | auth_data = await google.create_authorization_url(redirect_uri) |
66 | 76 | google_auth_url = auth_data.get("url") |
| 77 | + |
| 78 | + if google_auth_url is None: |
| 79 | + logger.logger.error("Google OAuth URL generation failed: URL is None") |
| 80 | + raise HTTPException( |
| 81 | + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, |
| 82 | + detail="구글 로그인 초기화에 실패했습니다.", |
| 83 | + ) |
| 84 | + |
67 | 85 | await google.save_authorize_data(request, **auth_data) |
68 | 86 | # print(f"DEBUG SESSION: {request.session}") |
69 | | - return {"redirect_url": google_auth_url} |
| 87 | + return RedirectResponse(google_auth_url) |
| 88 | + # return {"redirect_url": google_auth_url} |
70 | 89 |
|
71 | 90 |
|
72 | 91 | @auth_router.get("/oauth2/code/google") |
73 | 92 | async def receive_code( |
74 | 93 | request: Request, |
75 | 94 | auth_service: Annotated[AuthService, Depends()], |
76 | 95 | ): |
77 | | - redirect_uri = str(request.url_for("receive_code")) |
| 96 | + redirect_uri = get_redirect_uri(request) |
78 | 97 |
|
79 | 98 | try: |
80 | 99 | token = await google.authorize_access_token(request, redirect_uri=redirect_uri) |
|
0 commit comments