modify the project, everything go under app folder
This commit is contained in:
+134
@@ -0,0 +1,134 @@
|
||||
import httpx
|
||||
from fastapi import APIRouter, Depends, Request, HTTPException
|
||||
from fastapi.responses import RedirectResponse
|
||||
import os
|
||||
import secrets
|
||||
from app.auth.deps import get_current_user
|
||||
from app.db import SessionLocal
|
||||
from app.models import User
|
||||
from app.auth.jwt import create_access_token, create_refresh_token, decode_token
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
GOOGLE_CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID")
|
||||
GOOGLE_CLIENT_SECRET = os.getenv("GOOGLE_CLIENT_SECRET")
|
||||
GOOGLE_REDIRECT_URI = os.getenv("GOOGLE_REDIRECT_URI")
|
||||
|
||||
GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"
|
||||
GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token"
|
||||
GOOGLE_USERINFO_URL = "https://www.googleapis.com/oauth2/v2/userinfo"
|
||||
|
||||
@router.get("/login/google")
|
||||
def login_google():
|
||||
state = secrets.token_urlsafe(16)
|
||||
|
||||
url = (
|
||||
f"{GOOGLE_AUTH_URL}"
|
||||
f"?client_id={GOOGLE_CLIENT_ID}"
|
||||
f"&redirect_uri={GOOGLE_REDIRECT_URI}"
|
||||
f"&response_type=code"
|
||||
f"&scope=openid email profile"
|
||||
f"&state={state}"
|
||||
)
|
||||
|
||||
response = RedirectResponse(url)
|
||||
response.set_cookie(
|
||||
"oauth_state",
|
||||
state,
|
||||
httponly=True,
|
||||
secure=True,
|
||||
samesite="lax"
|
||||
)
|
||||
return response
|
||||
|
||||
@router.get("/auth/callback")
|
||||
async def auth_callback(request: Request, code: str, state: str):
|
||||
cookie_state = request.cookies.get("oauth_state")
|
||||
|
||||
if not cookie_state or cookie_state != state:
|
||||
raise HTTPException(status_code=400, detail="Invalid state")
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
token_res = await client.post(
|
||||
GOOGLE_TOKEN_URL,
|
||||
data={
|
||||
"code": code,
|
||||
"client_id": GOOGLE_CLIENT_ID,
|
||||
"client_secret": GOOGLE_CLIENT_SECRET,
|
||||
"redirect_uri": GOOGLE_REDIRECT_URI,
|
||||
"grant_type": "authorization_code",
|
||||
},
|
||||
)
|
||||
|
||||
token_json = token_res.json()
|
||||
access_token = token_json["access_token"]
|
||||
|
||||
user_res = await client.get(
|
||||
GOOGLE_USERINFO_URL,
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
|
||||
user_info = user_res.json()
|
||||
|
||||
db = SessionLocal()
|
||||
|
||||
user = db.query(User).filter(User.email == user_info["email"]).first()
|
||||
|
||||
if not user:
|
||||
user = User(
|
||||
google_id=user_info["id"],
|
||||
email=user_info["email"],
|
||||
name=user_info["name"],
|
||||
avatar=user_info["picture"],
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
db.close()
|
||||
|
||||
jwt_token = create_access_token({
|
||||
"sub": user.id,
|
||||
"email": user.email,
|
||||
})
|
||||
|
||||
refresh_token = create_refresh_token({
|
||||
"sub": user.id,
|
||||
"email": user.email,
|
||||
})
|
||||
|
||||
return {
|
||||
"access_token": jwt_token,
|
||||
"refresh_token": refresh_token,
|
||||
"token_type": "bearer",
|
||||
"user": {
|
||||
"email": user.email,
|
||||
"name": user.name,
|
||||
"avatar": user.avatar,
|
||||
}
|
||||
}
|
||||
|
||||
@router.get("/me")
|
||||
def me(user = Depends(get_current_user)):
|
||||
return {
|
||||
"email": user.email,
|
||||
"name": user.name,
|
||||
"avatar": user.avatar,
|
||||
}
|
||||
|
||||
@router.post("/refresh")
|
||||
def refresh_token(refresh_token: str):
|
||||
payload = decode_token(refresh_token)
|
||||
|
||||
if payload.get("type") != "refresh":
|
||||
raise HTTPException(status_code=401)
|
||||
|
||||
user_id = payload.get("sub")
|
||||
|
||||
new_access = create_access_token({"sub": user_id})
|
||||
|
||||
return {"access_token": new_access}
|
||||
|
||||
@router.post("/logout")
|
||||
def logout():
|
||||
return {"message": "ok"}
|
||||
@@ -0,0 +1,19 @@
|
||||
from fastapi import Request, HTTPException
|
||||
import app.auth.jwt as jwt
|
||||
import os
|
||||
|
||||
JWT_SECRET = os.getenv("JWT_SECRET")
|
||||
JWT_ALGORITHM = os.getenv("JWT_ALGORITHM", "HS256")
|
||||
|
||||
|
||||
def get_current_user(request: Request):
|
||||
token = request.cookies.get("access_token")
|
||||
|
||||
if not token:
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
|
||||
try:
|
||||
payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
|
||||
return payload["user_id"]
|
||||
except:
|
||||
raise HTTPException(status_code=401, detail="Invalid token")
|
||||
@@ -0,0 +1,53 @@
|
||||
import app.auth.jwt as jwt
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import os
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
JWT_SECRET = os.getenv("JWT_SECRET")
|
||||
JWT_ALGORITHM = os.getenv("JWT_ALGORITHM", "HS256")
|
||||
|
||||
def now():
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
def create_access_token(data: dict):
|
||||
payload = {
|
||||
**data,
|
||||
"type": "access",
|
||||
"exp": now() + timedelta(minutes=60),
|
||||
"iat": now(),
|
||||
}
|
||||
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
|
||||
|
||||
def create_refresh_token(data: dict):
|
||||
payload = {
|
||||
**data,
|
||||
"type": "refresh",
|
||||
"exp": now() + timedelta(days=7),
|
||||
"iat": now(),
|
||||
}
|
||||
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
|
||||
|
||||
def decode_token(token: str):
|
||||
try:
|
||||
payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
|
||||
return payload
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise HTTPException(status_code=401, detail="Token expired")
|
||||
except jwt.InvalidTokenError:
|
||||
raise HTTPException(status_code=401, detail="Invalid token")
|
||||
|
||||
def verify_access_token(token: str):
|
||||
payload = decode_token(token)
|
||||
|
||||
if payload.get("type") != "access":
|
||||
raise HTTPException(status_code=401, detail="Invalid access token")
|
||||
|
||||
return payload
|
||||
|
||||
def verify_refresh_token(token: str):
|
||||
payload = decode_token(token)
|
||||
|
||||
if payload.get("type") != "refresh":
|
||||
raise HTTPException(status_code=401, detail="Invalid refresh token")
|
||||
|
||||
return payload
|
||||
@@ -0,0 +1,8 @@
|
||||
import os
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
DATABASE_URL = os.getenv("DATABASE_URL")
|
||||
|
||||
engine = create_engine(DATABASE_URL)
|
||||
SessionLocal = sessionmaker(bind=engine)
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
from fastapi import FastAPI
|
||||
from app.auth import router as auth_router
|
||||
from app.models import Base
|
||||
from app.db import engine
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
app.include_router(auth_router)
|
||||
@@ -0,0 +1,5 @@
|
||||
from .base import Base
|
||||
|
||||
from .user import User
|
||||
|
||||
__all__ = ["Base", "User"]
|
||||
@@ -0,0 +1,65 @@
|
||||
import hashlib
|
||||
from sqlalchemy import Column, String
|
||||
from sqlalchemy.orm import declarative_base, declared_attr
|
||||
import ulid
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
# Base62 字符集
|
||||
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||
|
||||
|
||||
def encode_base62(num: int) -> str:
|
||||
"""将一个整数编码为 Base62 字符串"""
|
||||
if num == 0:
|
||||
return ALPHABET[0]
|
||||
arr = []
|
||||
base = len(ALPHABET)
|
||||
while num:
|
||||
num, rem = divmod(num, base)
|
||||
arr.append(ALPHABET[rem])
|
||||
return "".join(reversed(arr))
|
||||
|
||||
|
||||
def encode_tablename_to_prefix(tablename: str, length: int = 3) -> str:
|
||||
"""
|
||||
将表名 encode 成固定长度的前缀,使用 MD5 拿到表名的唯一哈希值,转为整数后用 Base62 截取前 N 位
|
||||
"""
|
||||
# 计算表名的 MD5 哈希
|
||||
hasher = hashlib.md5(tablename.encode("utf-8"))
|
||||
hex_digest = hasher.hexdigest()
|
||||
|
||||
# 将十六进制哈希转为大整数
|
||||
num = int(hex_digest, 16)
|
||||
|
||||
# 转为 Base62 字符串
|
||||
b62_str = encode_base62(num)
|
||||
|
||||
# 截取固定长度(例如 3 位)作为该表的专属代码
|
||||
return b62_str[:length]
|
||||
|
||||
|
||||
def gen_convex_payload() -> str:
|
||||
"""生成 128位 ULID 转 Base62 的趋势递增 Payload"""
|
||||
u = ulid.new()
|
||||
return encode_base62(u.int)
|
||||
|
||||
|
||||
class AutoID:
|
||||
"""
|
||||
全自动 Convex 风格 ID 注入器
|
||||
不再需要手动定义任何 prefix,全自动根据 __tablename__ 编码生成
|
||||
"""
|
||||
@declared_attr
|
||||
def id(cls):
|
||||
# 运行时动态获取子类的 __tablename__
|
||||
tablename = cls.__tablename__
|
||||
|
||||
# 将表名编码为固定前缀(例如 "users" -> "7X1")
|
||||
table_prefix = encode_tablename_to_prefix(tablename, length=3)
|
||||
|
||||
# 核心工厂函数:拼接【编码后的表前缀】和【递增Payload】
|
||||
def id_factory():
|
||||
return f"{table_prefix}_{gen_convex_payload()}"
|
||||
|
||||
return Column(String(32), primary_key=True, default=id_factory)
|
||||
@@ -0,0 +1,11 @@
|
||||
from sqlalchemy import Column, DateTime, String, ForeignKey
|
||||
from sqlalchemy.sql import func
|
||||
from .base import Base, AutoID
|
||||
|
||||
class Message(Base, AutoID):
|
||||
__tablename__ = "messages"
|
||||
|
||||
user_id = Column(String, ForeignKey("users.id"), index=True)
|
||||
content = Column(String)
|
||||
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
@@ -0,0 +1,17 @@
|
||||
from sqlalchemy import Column, DateTime, String
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from .base import AutoID, Base
|
||||
|
||||
class User(Base, AutoID):
|
||||
__tablename__ = "users"
|
||||
|
||||
google_id = Column(String, unique=True, index=True)
|
||||
email = Column(String, unique=True, index=True)
|
||||
name = Column(String)
|
||||
avatar = Column(String)
|
||||
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
def __repr__(self):
|
||||
return f"<User(id={self.id}, name={self.name}, email={self.email})>"
|
||||
Reference in New Issue
Block a user