Skip to content

Commit 01f3c8b

Browse files
committed
chore: update GitHub Actions and refactor authentication logic
- Added pnpm installation step in the GitHub Actions workflow for improved dependency management. - Updated JWT token decoding in the extension authentication routes to use the jwt library directly. - Refactored user retrieval logic to utilize session.get for better clarity and performance. - Modified Google OAuth login parameter type for improved type safety. - Updated database connection utilities to use the psycopg driver instead of psycopg2 for better compatibility.
1 parent 586141c commit 01f3c8b

File tree

7 files changed

+38
-26
lines changed

7 files changed

+38
-26
lines changed

.github/workflows/playwright.yml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,9 +109,14 @@ jobs:
109109
runs-on: ubuntu-latest
110110
steps:
111111
- uses: actions/checkout@v4
112+
- name: Install pnpm
113+
uses: pnpm/action-setup@v3
114+
with:
115+
version: 9.9.0
112116
- uses: actions/setup-node@v4
113117
with:
114118
node-version: 20
119+
cache: 'pnpm'
115120
- name: Install dependencies
116121
run: pnpm install --frozen-lockfile
117122
working-directory: frontend

backend/app/api/routes/extension_auth.py

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
from datetime import timedelta
22
from typing import Any
33

4+
import jwt
45
from fastapi import APIRouter, HTTPException, Request
6+
from jwt.exceptions import InvalidTokenError
57

6-
from app import crud
78
from app.api.deps import SessionDep
89
from app.core import security
910
from app.core.config import settings
10-
from app.models import Token, UserPublic
11+
from app.models import Token, User, UserPublic
1112

1213
router = APIRouter(tags=["extension"])
1314

@@ -24,18 +25,22 @@ def check_extension_auth_status(request: Request, session: SessionDep) -> Any:
2425
auth_header = request.headers.get("Authorization")
2526
if auth_header and auth_header.startswith("Bearer "):
2627
token = auth_header.replace("Bearer ", "")
27-
payload = security.decode_access_token(token)
28+
payload = jwt.decode(
29+
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
30+
)
2831
user_id = payload.get("sub")
29-
user = crud.get_user(session=session, id=user_id)
32+
user = session.get(User, user_id)
3033
if user and user.is_active:
3134
return {"authenticated": True, "user": UserPublic.model_validate(user)}
3235

3336
# 从 cookie 获取令牌
3437
cookie_token = request.cookies.get("accessToken")
3538
if cookie_token:
36-
payload = security.decode_access_token(cookie_token)
39+
payload = jwt.decode(
40+
cookie_token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
41+
)
3742
user_id = payload.get("sub")
38-
user = crud.get_user(session=session, id=user_id)
43+
user = session.get(User, user_id)
3944
if user and user.is_active:
4045
return {"authenticated": True, "user": UserPublic.model_validate(user)}
4146

@@ -56,9 +61,11 @@ def get_extension_token(request: Request, session: SessionDep) -> Any:
5661
cookie_token = request.cookies.get("accessToken")
5762
if cookie_token:
5863
try:
59-
payload = security.decode_access_token(cookie_token)
64+
payload = jwt.decode(
65+
cookie_token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
66+
)
6067
user_id = payload.get("sub")
61-
user = crud.get_user(session=session, id=user_id)
68+
user = session.get(User, user_id)
6269

6370
if user and user.is_active:
6471
# 为扩展创建新令牌
@@ -70,7 +77,7 @@ def get_extension_token(request: Request, session: SessionDep) -> Any:
7077
)
7178

7279
return Token(access_token=token)
73-
except Exception as e:
80+
except InvalidTokenError as e:
7481
raise HTTPException(status_code=401, detail=f"无效的网页会话: {str(e)}")
7582

7683
raise HTTPException(status_code=401, detail="未找到有效的网页会话")

backend/app/api/routes/google_oauth.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ async def google_callback_api(
9090
@router.get("/login/google")
9191
async def google_login(
9292
request: Request,
93-
extension_callback: str = None, # 添加扩展回调链接参数
93+
extension_callback: str | None = None, # 添加扩展回调链接参数
9494
):
9595
"""
9696
Initiate Google OAuth2 authentication flow

backend/app/core/config.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,6 @@ def posthog_enabled(self) -> bool:
207207
# Google OAuth
208208
GOOGLE_CLIENT_ID: str = ""
209209
GOOGLE_CLIENT_SECRET: str = ""
210-
FRONTEND_HOST: str = "http://localhost:3000"
211210
# 后端 API URL 配置,可通过环境变量覆盖
212211
BACKEND_API_URL: str = "http://localhost:8000"
213212

backend/app/core/supabase_service.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ def get_supabase_client() -> Any | None:
4040

4141
# Create and return the Supabase client
4242
try:
43+
# 使用 type: ignore[attr-defined] 忽略 mypy 警告,因为 supabase 库在运行时确实有 create_client 方法
4344
client = supabase.create_client( # type: ignore[attr-defined]
4445
url, settings.SUPABASE_API_KEY
4546
)

backend/app/tests/test_initial_data.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ def test_direct_execution():
126126
)
127127

128128
# Verify execution was successful
129-
assert "Success: Module executed" in result.stdou
129+
assert "Success: Module executed" in result.stdout
130130
finally:
131131
# Clean up
132132
if os.path.exists(temp_file):

backend/app/tests/utils/test_db.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -40,26 +40,26 @@ def get_test_db_url() -> str:
4040
main_url = str(settings.SQLALCHEMY_DATABASE_URI)
4141
test_db_name = get_test_db_name()
4242

43-
# 替换数据库名称部分,并确保使用 psycopg2 驱动
43+
# 替换数据库名称部分,并确保使用 psycopg 驱动
4444
if "postgres://" in main_url or "postgresql://" in main_url:
4545
# 替换数据库名称
4646
db_name_part = main_url.split("/")[-1]
4747
new_url = main_url.replace(db_name_part, test_db_name)
4848

49-
# 确保使用 psycopg2 驱动
50-
if "+psycopg" in new_url:
51-
new_url = new_url.replace("+psycopg", "+psycopg2")
49+
# 确保使用 psycopg 驱动 (不是 psycopg2)
50+
if "+psycopg2" in new_url:
51+
new_url = new_url.replace("+psycopg2", "+psycopg")
5252
elif (
5353
"postgresql://" in new_url
5454
and "+psycopg" not in new_url
5555
and "+psycopg2" not in new_url
5656
):
57-
new_url = new_url.replace("postgresql://", "postgresql+psycopg2://")
57+
new_url = new_url.replace("postgresql://", "postgresql+psycopg://")
5858

5959
return new_url
6060

61-
# 如无法解析,则构建新的 URL,显式使用 psycopg2
62-
return f"postgresql+psycopg2://{settings.POSTGRES_USER}:{settings.POSTGRES_PASSWORD}@{settings.POSTGRES_SERVER}:{settings.POSTGRES_PORT}/{test_db_name}"
61+
# 如无法解析,则构建新的 URL,显式使用 psycopg
62+
return f"postgresql+psycopg://{settings.POSTGRES_USER}:{settings.POSTGRES_PASSWORD}@{settings.POSTGRES_SERVER}:{settings.POSTGRES_PORT}/{test_db_name}"
6363

6464

6565
def get_connection_string() -> str:
@@ -171,12 +171,12 @@ def setup_test_db() -> Engine:
171171
driver_name = "postgresql+psycopg"
172172

173173
# 使用importlib.util.find_spec检查模块可用性
174-
if importlib.util.find_spec("psycopg2"):
175-
driver_name = "postgresql+psycopg2"
176-
logger.info("Using psycopg2 driver for database connection")
177-
elif importlib.util.find_spec("psycopg"):
174+
if importlib.util.find_spec("psycopg"):
178175
driver_name = "postgresql+psycopg"
179176
logger.info("Using psycopg (v3) driver for database connection")
177+
elif importlib.util.find_spec("psycopg2"):
178+
driver_name = "postgresql+psycopg2"
179+
logger.info("Using psycopg2 driver for database connection")
180180
else:
181181
logger.error(
182182
"Neither psycopg nor psycopg2 is available. Please install one of them."
@@ -248,10 +248,10 @@ def test_database_connection() -> bool:
248248
driver_name = "postgresql+psycopg"
249249

250250
# 使用importlib.util.find_spec检查模块可用性
251-
if importlib.util.find_spec("psycopg2"):
252-
driver_name = "postgresql+psycopg2"
253-
elif importlib.util.find_spec("psycopg"):
251+
if importlib.util.find_spec("psycopg"):
254252
driver_name = "postgresql+psycopg"
253+
elif importlib.util.find_spec("psycopg2"):
254+
driver_name = "postgresql+psycopg2"
255255
else:
256256
return False # 如果两个驱动都不可用,则连接失败
257257

0 commit comments

Comments
 (0)