github-actions
Sync backend from GitHub 73ae2cb
7ca6f62
Raw History Blame Contribute Delete
33.9 kB
"""Authentication and User Profile Routes supporting Instant Login, GitHub and WeChat."""
from __future__ import annotations
import re
import os
import json
import secrets
import urllib.request
import urllib.parse
import time
import hashlib
from typing import Optional, Dict, Any, List
from pydantic import BaseModel, Field
from fastapi import APIRouter, HTTPException, Depends, Header, status, Request, Response
from codestar.server.db import (
create_user,
get_user_by_username,
get_user_by_email,
get_user_by_id,
get_user_stats,
get_user_progress,
get_user_detailed_stats,
)
from codestar.server.auth import (
hash_password,
verify_password,
create_access_token,
require_current_user,
get_current_user,
)
router = APIRouter(prefix="/api/auth", tags=["Authentication"])
# In-memory store for phone verification codes (TTL 5 mins)
_phone_codes_cache: Dict[str, Dict[str, Any]] = {}
# In-memory store for email verification codes (TTL 10 mins)
_email_codes_cache: Dict[str, Dict[str, Any]] = {}
# Sliding-window rate limiter store: key -> list of float timestamps
_rate_limits: Dict[str, List[float]] = {}
# Session registry for verified social login sessions: username -> session_token
_social_sessions: Dict[str, str] = {}
def check_rate_limit(key: str, max_requests: int, window_seconds: float):
now = time.time()
cutoff = now - window_seconds
timestamps = _rate_limits.get(key, [])
valid_timestamps = [t for t in timestamps if t > cutoff]
if len(valid_timestamps) >= max_requests:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail=f"请求过于频繁,请在 {int(window_seconds)} 秒后再试",
)
valid_timestamps.append(now)
_rate_limits[key] = valid_timestamps
if len(_rate_limits) > 5000:
for k in list(_rate_limits.keys()):
_rate_limits[k] = [t for t in _rate_limits[k] if t > cutoff]
if not _rate_limits[k]:
del _rate_limits[k]
def _get_client_ip(request: Optional[Request]) -> str:
if not request:
return "127.0.0.1"
forwarded = request.headers.get("x-forwarded-for")
if forwarded:
return forwarded.split(",")[0].strip()
return request.client.host if request.client else "127.0.0.1"
class AuthRequest(BaseModel):
username: str = Field(..., min_length=2, max_length=32)
password: Optional[str] = Field(None, max_length=64)
class PhoneSendCodeRequest(BaseModel):
phone: str = Field(..., max_length=16)
class PhoneLoginRequest(BaseModel):
phone: str = Field(..., max_length=16)
code: str = Field(..., max_length=8)
class EmailSendCodeRequest(BaseModel):
email: str = Field(..., max_length=64)
class EmailLoginRequest(BaseModel):
email: str = Field(..., max_length=64)
code: str = Field(..., max_length=8)
class OAuthExchangeRequest(BaseModel):
code: str
redirect_uri: Optional[str] = None
class SocialAuthRequest(BaseModel):
account_name: Optional[str] = None
password: Optional[str] = None
credential: Optional[str] = None
class AuthResponse(BaseModel):
token: str
user: Dict[str, Any]
is_new_user: bool = False
class UserProfileResponse(BaseModel):
id: int
username: str
created_at: str
solved_count: int
attempted_count: int
total_submissions: int
is_vip: bool = False
vip_expire_at: Optional[str] = None
vip_level: str = "none"
star_coins: int = 0
class DifficultyStats(BaseModel):
solved: int
total: int
class UserStatsResponse(BaseModel):
total_solved: int
total_problems: int
easy: DifficultyStats
medium: DifficultyStats
hard: DifficultyStats
total_submissions: int
ac_submissions: int
ac_rate: float
current_streak: int
max_streak: int
active_days: int
submission_calendar: Dict[str, int]
global_rank: int
@router.post("/quick-login", response_model=AuthResponse)
def quick_login(req: AuthRequest, request: Request):
"""登录即注册:输入用户名,若账号不存在则自动一键创建账号并登录,无需繁琐注册流程。"""
ip = _get_client_ip(request)
check_rate_limit(f"quick_login:{ip}", max_requests=30, window_seconds=60)
username = req.username.strip()
if not username:
raise HTTPException(status_code=400, detail="用户名不能为空")
user = get_user_by_username(username)
is_new = False
if not user:
# Auto-register on the spot!
password = req.password or "codestar_pass_auto"
pwd_hash, salt = hash_password(password)
user_id = create_user(username, pwd_hash, salt)
user = {"id": user_id, "username": username}
is_new = True
else:
# Existing user: check if guest or password protected
is_guest_account = verify_password("codestar_pass_auto", user["password_hash"], user["salt"])
if not is_guest_account:
# Account has an explicit password set!
if not req.password:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="该账号已设置密码,请输入密码登录",
)
if not verify_password(req.password, user["password_hash"], user["salt"]):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="密码错误,请核对密码",
)
else:
if req.password and not verify_password(req.password, user["password_hash"], user["salt"]):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="密码错误,请核对密码",
)
token = create_access_token(user["id"], user["username"])
return {
"token": token,
"user": {"id": user["id"], "username": user["username"]},
"is_new_user": is_new,
}
@router.post("/github", response_model=AuthResponse)
def github_auth(
request: Request,
response: Response,
req: Optional[SocialAuthRequest] = None,
authorization: Optional[str] = Header(None),
):
"""GitHub 快捷授权登录与永久数据保存,支持自定义绑定账号或一键开户。"""
ip = _get_client_ip(request)
check_rate_limit(f"github_auth:{ip}", max_requests=30, window_seconds=60)
raw_name = req.account_name.strip() if req and req.account_name else ""
if raw_name:
clean_handle = re.sub(r"[^\w\-]", "", raw_name)[:24]
if clean_handle.lower().startswith("github_"):
clean_handle = clean_handle[7:]
else:
clean_handle = f"dev_{secrets.token_hex(3)}"
if not clean_handle:
clean_handle = f"dev_{secrets.token_hex(3)}"
username = f"github_{clean_handle}"
user = get_user_by_username(username)
is_new = False
if not user:
session_token = secrets.token_urlsafe(32)
pwd_hash, salt = hash_password(session_token)
user_id = create_user(username, pwd_hash, salt)
user = {"id": user_id, "username": username}
is_new = True
_social_sessions[username] = session_token
if response:
response.set_cookie(
key=f"cs_soc_{username}",
value=session_token,
httponly=True,
samesite="lax",
secure=_cookie_is_secure(request),
)
else:
# Existing account verification to close impersonation vulnerability
is_verified = False
if authorization and authorization.startswith("Bearer "):
bearer_token = authorization.split(" ")[1]
try:
from codestar.server.auth import decode_access_token
payload = decode_access_token(bearer_token)
if payload and (payload.get("sub") == str(user["id"]) or payload.get("username") == user["username"]):
is_verified = True
except Exception:
pass
if not is_verified and request:
cookie_val = request.cookies.get(f"cs_soc_{username}")
if cookie_val and _social_sessions.get(username) == cookie_val:
is_verified = True
if not is_verified and req and req.password:
if verify_password(req.password, user["password_hash"], user["salt"]):
is_verified = True
if not is_verified and req and req.credential:
if _social_sessions.get(username) == req.credential:
is_verified = True
if not is_verified:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="该账号已存在,为保障账号安全,禁止免密冒名登录,请提供身份凭证或密码验证",
)
session_token = secrets.token_urlsafe(32)
_social_sessions[username] = session_token
if response:
response.set_cookie(
key=f"cs_soc_{username}",
value=session_token,
httponly=True,
samesite="lax",
secure=_cookie_is_secure(request),
)
token = create_access_token(user["id"], user["username"])
return {
"token": token,
"user": {"id": user["id"], "username": user["username"]},
"is_new_user": is_new,
}
@router.post("/wechat", response_model=AuthResponse)
def wechat_auth(
request: Request,
response: Response,
req: Optional[SocialAuthRequest] = None,
authorization: Optional[str] = Header(None),
):
"""微信扫码快捷授权登录与永久数据保存,支持扫码识别与自动开户。"""
ip = _get_client_ip(request)
check_rate_limit(f"wechat_auth:{ip}", max_requests=30, window_seconds=60)
raw_name = req.account_name.strip() if req and req.account_name else ""
if raw_name:
clean_handle = re.sub(r"[^\w\-]", "", raw_name)[:24]
if clean_handle.lower().startswith("wechat_"):
clean_handle = clean_handle[7:]
else:
clean_handle = f"user_{secrets.token_hex(3)}"
if not clean_handle:
clean_handle = f"user_{secrets.token_hex(3)}"
username = f"wechat_{clean_handle}"
user = get_user_by_username(username)
is_new = False
if not user:
session_token = secrets.token_urlsafe(32)
pwd_hash, salt = hash_password(session_token)
user_id = create_user(username, pwd_hash, salt)
user = {"id": user_id, "username": username}
is_new = True
_social_sessions[username] = session_token
if response:
response.set_cookie(
key=f"cs_soc_{username}",
value=session_token,
httponly=True,
samesite="lax",
secure=_cookie_is_secure(request),
)
else:
# Existing account verification to close impersonation vulnerability
is_verified = False
if authorization and authorization.startswith("Bearer "):
bearer_token = authorization.split(" ")[1]
try:
from codestar.server.auth import decode_access_token
payload = decode_access_token(bearer_token)
if payload and (payload.get("sub") == str(user["id"]) or payload.get("username") == user["username"]):
is_verified = True
except Exception:
pass
if not is_verified and request:
cookie_val = request.cookies.get(f"cs_soc_{username}")
if cookie_val and _social_sessions.get(username) == cookie_val:
is_verified = True
if not is_verified and req and req.password:
if verify_password(req.password, user["password_hash"], user["salt"]):
is_verified = True
if not is_verified and req and req.credential:
if _social_sessions.get(username) == req.credential:
is_verified = True
if not is_verified:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="该账号已存在,为保障账号安全,禁止免密冒名登录,请提供身份凭证或密码验证",
)
session_token = secrets.token_urlsafe(32)
_social_sessions[username] = session_token
if response:
response.set_cookie(
key=f"cs_soc_{username}",
value=session_token,
httponly=True,
samesite="lax",
secure=_cookie_is_secure(request),
)
token = create_access_token(user["id"], user["username"])
return {
"token": token,
"user": {"id": user["id"], "username": user["username"]},
"is_new_user": is_new,
}
def _is_demo_auth_allowed() -> bool:
return os.getenv("CODESTAR_ALLOW_DEMO_AUTH", "").strip().lower() in ("1", "true", "yes")
def _cookie_is_secure(request: Optional[Request]) -> bool:
if not request:
return False
proto = request.headers.get("x-forwarded-proto", "")
return proto.lower() == "https" or request.url.scheme == "https"
def _get_github_client_id() -> str:
return (
os.getenv("GITHUB_CLIENT_ID", "").strip()
or os.getenv("NEXT_PUBLIC_GITHUB_CLIENT_ID", "").strip()
)
@router.get("/github/config")
def get_github_oauth_config():
"""获取 GitHub 生产 OAuth 配置状态。"""
client_id = _get_github_client_id()
client_secret = os.getenv("GITHUB_CLIENT_SECRET", "").strip()
configured = bool(client_id and client_secret)
return {
"configured": configured,
"client_id": client_id if configured else None,
"help": "在 GitHub Settings -> Developer settings -> OAuth Apps 中创建应用,获得 Client ID & Secret 后填入环境变量即可激活真实登录",
}
@router.post("/github/oauth-callback", response_model=AuthResponse)
def github_oauth_callback(req: OAuthExchangeRequest):
"""真实 GitHub OAuth2 回调:通过授权 code 获取真实 GitHub 账号资料并持久化建档。"""
client_id = _get_github_client_id()
client_secret = os.getenv("GITHUB_CLIENT_SECRET", "").strip()
if not client_id or not client_secret:
raise HTTPException(
status_code=503,
detail="后端未配置 GITHUB_CLIENT_ID 或 GITHUB_CLIENT_SECRET 环境变量,暂不支持 GitHub OAuth 登录",
)
# 1. Exchange code for access_token with GitHub
token_url = "https://github.com/login/oauth/access_token"
payload = json.dumps({
"client_id": client_id,
"client_secret": client_secret,
"code": req.code,
"redirect_uri": req.redirect_uri,
}).encode("utf-8")
token_req = urllib.request.Request(
token_url,
data=payload,
headers={
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "CodeStar-Platform",
},
)
try:
with urllib.request.urlopen(token_req, timeout=10) as resp:
token_data = json.loads(resp.read().decode("utf-8"))
except Exception as e:
raise HTTPException(status_code=502, detail=f"GitHub OAuth 通信异常: {str(e)}")
access_token = token_data.get("access_token")
if not access_token:
error_desc = token_data.get("error_description", "授权码已失效,请重新授权")
raise HTTPException(status_code=400, detail=f"GitHub 授权失败: {error_desc}")
# 2. Fetch real GitHub user profile
user_url = "https://api.github.com/user"
user_req = urllib.request.Request(
user_url,
headers={
"Authorization": f"Bearer {access_token}",
"Accept": "application/json",
"User-Agent": "CodeStar-Platform",
},
)
try:
with urllib.request.urlopen(user_req, timeout=10) as resp:
gh_profile = json.loads(resp.read().decode("utf-8"))
except Exception as e:
raise HTTPException(status_code=502, detail=f"获取 GitHub 用户资料失败: {str(e)}")
gh_login = gh_profile.get("login") or f"user_{secrets.token_hex(3)}"
username = f"github_{gh_login}"
user = get_user_by_username(username)
is_new = False
if not user:
pwd_hash, salt = hash_password(secrets.token_hex(16))
user_id = create_user(username, pwd_hash, salt)
user = {"id": user_id, "username": username}
is_new = True
token = create_access_token(user["id"], user["username"])
return {
"token": token,
"user": {"id": user["id"], "username": user["username"]},
"is_new_user": is_new,
}
@router.get("/wechat/config")
def get_wechat_oauth_config():
"""获取微信生产扫码登录配置状态。"""
app_id = os.getenv("WECHAT_APP_ID", "").strip()
return {
"configured": bool(app_id),
"app_id": app_id if app_id else None,
"help": "在微信开放平台 (open.weixin.qq.com) 创建网站应用,获得 AppID & AppSecret 后填入环境变量即可激活真实微信扫码",
}
@router.post("/wechat/oauth-callback", response_model=AuthResponse)
def wechat_oauth_callback(req: OAuthExchangeRequest):
"""真实微信扫码登录回调:通过 code 换取微信真实 OpenID 并自动开户。"""
app_id = os.getenv("WECHAT_APP_ID", "").strip()
app_secret = os.getenv("WECHAT_APP_SECRET", "").strip()
if not app_id or not app_secret:
raise HTTPException(
status_code=400,
detail="后端未配置 WECHAT_APP_ID 或 WECHAT_APP_SECRET 环境变量",
)
# 1. Exchange code for access_token with WeChat
token_url = (
f"https://api.weixin.qq.com/sns/oauth2/access_token?"
f"appid={app_id}&secret={app_secret}&code={req.code}&grant_type=authorization_code"
)
try:
with urllib.request.urlopen(token_url, timeout=10) as resp:
wx_token_data = json.loads(resp.read().decode("utf-8"))
except Exception as e:
raise HTTPException(status_code=502, detail=f"微信开放平台通信异常: {str(e)}")
openid = wx_token_data.get("openid")
if not openid:
err_msg = wx_token_data.get("errmsg", "微信授权码失效或未通过审核")
raise HTTPException(status_code=400, detail=f"微信授权失败: {err_msg}")
username = f"wechat_{openid[-8:]}"
user = get_user_by_username(username)
is_new = False
if not user:
pwd_hash, salt = hash_password(secrets.token_hex(16))
user_id = create_user(username, pwd_hash, salt)
user = {"id": user_id, "username": username}
is_new = True
token = create_access_token(user["id"], user["username"])
return {
"token": token,
"user": {"id": user["id"], "username": user["username"]},
"is_new_user": is_new,
}
@router.post("/phone/send-code")
def send_phone_code(req: PhoneSendCodeRequest, request: Request):
"""手机验证码下发接口:支持真实格式校验与防刷限流。"""
ip = _get_client_ip(request)
phone = req.phone.strip()
if not re.match(r"^1[3-9]\d{9}$", phone):
raise HTTPException(status_code=400, detail="请输入正确的 11 位中国大陆手机号码")
check_rate_limit(f"send_code_ip:{ip}", max_requests=10, window_seconds=60)
check_rate_limit(f"send_code_phone:{phone}", max_requests=5, window_seconds=60)
code = "".join([str(secrets.randbelow(10)) for _ in range(6)])
_phone_codes_cache[phone] = {
"code": code,
"expires_at": time.time() + 300,
"attempts": 0,
}
# Plaintext code is strictly NOT echoed in response
return {
"status": "ok",
"message": "短信验证码已发送",
}
@router.post("/phone/login", response_model=AuthResponse)
def phone_login(req: PhoneLoginRequest, request: Request):
"""手机号+短信验证码登录/自动注册。"""
ip = _get_client_ip(request)
phone = req.phone.strip()
code = req.code.strip()
if not re.match(r"^1[3-9]\d{9}$", phone):
raise HTTPException(status_code=400, detail="手机号码格式不正确")
if not code:
raise HTTPException(status_code=400, detail="请输入短信验证码")
check_rate_limit(f"phone_login_ip:{ip}", max_requests=30, window_seconds=60)
check_rate_limit(f"phone_login_phone:{phone}", max_requests=10, window_seconds=60)
cached = _phone_codes_cache.get(phone)
valid = False
if cached and cached["expires_at"] > time.time():
if secrets.compare_digest(cached["code"], code):
valid = True
else:
cached["attempts"] = cached.get("attempts", 0) + 1
if cached["attempts"] >= 5:
_phone_codes_cache.pop(phone, None)
if not valid:
raise HTTPException(status_code=400, detail="验证码错误或已失效,请重新获取")
_phone_codes_cache.pop(phone, None)
# Use unique identifier phone to prevent collision between numbers with identical prefix/suffix
username = f"phone_{phone}"
user = get_user_by_username(username)
is_new = False
if not user:
pwd_hash, salt = hash_password(secrets.token_hex(16))
user_id = create_user(username, pwd_hash, salt)
user = {"id": user_id, "username": username}
is_new = True
token = create_access_token(user["id"], user["username"])
return {
"token": token,
"user": {"id": user["id"], "username": user["username"]},
"is_new_user": is_new,
}
def send_email_smtp(to_email: str, code: str) -> bool:
"""Send verification email via SMTP strictly using environment credentials."""
smtp_host = os.getenv("SMTP_HOST", "").strip()
smtp_port_str = os.getenv("SMTP_PORT", "587").strip() or "587"
try:
smtp_port = int(smtp_port_str)
except ValueError:
smtp_port = 587
smtp_user = os.getenv("SMTP_USER", "").strip()
smtp_pass = os.getenv("SMTP_PASS", "").strip()
from_name = os.getenv("SMTP_FROM_NAME", "").strip() or "CodeStar 大模型判题平台"
if not smtp_host or not smtp_user or not smtp_pass:
return False
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
html_content = f"""
<div style="max-width: 500px; margin: 0 auto; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #0e0e12; color: #e4e4e7; border-radius: 16px; border: 1px solid #27272a; padding: 32px; box-shadow: 0 10px 30px rgba(0,0,0,0.5);">
<div style="margin-bottom: 20px;">
<span style="font-size: 24px; color: #f59e0b; font-weight: bold;">CodeStar</span>
<span style="font-size: 13px; color: #a1a1aa; margin-left: 8px;">大模型 AI 手撕·在线判题平台</span>
</div>
<p style="font-size: 14px; color: #a1a1aa; line-height: 1.6; margin-bottom: 20px;">
您好!您正在登录或注册 CodeStar 平台。您的 6 位动态验证码为:
</p>
<div style="background: #18181b; border: 1px solid #3f3f46; border-radius: 12px; padding: 18px; text-align: center; margin-bottom: 20px;">
<span style="font-family: monospace; font-size: 32px; font-weight: bold; letter-spacing: 6px; color: #f59e0b;">{code}</span>
</div>
<p style="font-size: 12px; color: #71717a; line-height: 1.6; margin-bottom: 0;">
• 验证码有效期为 <strong>10 分钟</strong>,请勿将验证码泄露给他人。<br>
• 如非您本人操作,请忽略此邮件。
</p>
</div>
"""
msg = MIMEText(html_content, "html", "utf-8")
msg["From"] = formataddr((str(Header(from_name, "utf-8")), smtp_user))
msg["To"] = to_email
msg["Subject"] = Header(f"【CodeStar】登录验证码: {code}", "utf-8")
# Try configured port, with intelligent fallback between 587 (STARTTLS) and 465 (SSL)
ports_to_try = [smtp_port]
if smtp_port != 587:
ports_to_try.append(587)
if smtp_port != 465:
ports_to_try.append(465)
last_error = None
for p in ports_to_try:
try:
if p == 465:
with smtplib.SMTP_SSL(smtp_host, p, timeout=8.0) as server:
server.login(smtp_user, smtp_pass)
server.sendmail(smtp_user, [to_email], msg.as_string())
return True
else:
with smtplib.SMTP(smtp_host, p, timeout=8.0) as server:
server.ehlo()
server.starttls()
server.ehlo()
server.login(smtp_user, smtp_pass)
server.sendmail(smtp_user, [to_email], msg.as_string())
return True
except Exception as e:
last_error = e
if last_error:
print(f"[SMTP Error] Failed to send email to {to_email}: {last_error}")
return False
@router.get("/email/config")
def get_email_auth_config():
"""获取邮箱验证码发信配置状态。"""
configured = bool(
os.getenv("SMTP_HOST", "").strip()
and os.getenv("SMTP_USER", "").strip()
and os.getenv("SMTP_PASS", "").strip()
)
return {
"configured": configured,
"demo_allowed": _is_demo_auth_allowed(),
}
@router.post("/email/send-code")
def send_email_code(req: EmailSendCodeRequest, request: Request):
"""下发邮箱登录验证码:零成本,支持 QQ 邮箱 / 163 邮箱 / Gmail 等免费 SMTP 发信。"""
ip = _get_client_ip(request)
email = req.email.strip().lower()
if not re.match(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", email):
raise HTTPException(status_code=400, detail="请输入正确的邮箱地址")
check_rate_limit(f"send_email_ip:{ip}", max_requests=15, window_seconds=60)
check_rate_limit(f"send_email_addr:{email}", max_requests=5, window_seconds=60)
code = "".join([str(secrets.randbelow(10)) for _ in range(6)])
_email_codes_cache[email] = {
"code": code,
"expires_at": time.time() + 600,
"attempts": 0,
}
sent = send_email_smtp(email, code)
if sent:
return {
"status": "ok",
"message": "验证码已成功发送至您的邮箱,请查收",
"has_smtp": True,
}
# Never expose OTP codes in production; only allow demo fallback when explicitly enabled
if _is_demo_auth_allowed():
return {
"status": "ok",
"message": f"【开发/演示模式】验证码已生成: {code} (配置 SMTP 后将直接真机发信)",
"has_smtp": False,
"demo_code": code,
}
_email_codes_cache.pop(email, None)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="邮箱验证码服务暂不可用,请改用 GitHub 登录或账号密码登录",
)
@router.post("/email/login", response_model=AuthResponse)
def email_login(req: EmailLoginRequest, request: Request):
"""邮箱 + 验证码一键免密登录与自动建号(严格绑定唯一邮箱,防止不同域名同名冲突)。"""
ip = _get_client_ip(request)
email = req.email.strip().lower()
code = req.code.strip()
if not re.match(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", email):
raise HTTPException(status_code=400, detail="邮箱地址格式不正确")
if not code:
raise HTTPException(status_code=400, detail="请输入邮箱验证码")
check_rate_limit(f"email_login_ip:{ip}", max_requests=30, window_seconds=60)
check_rate_limit(f"email_login_addr:{email}", max_requests=10, window_seconds=60)
cached = _email_codes_cache.get(email)
valid = False
if cached and cached["expires_at"] > time.time():
if secrets.compare_digest(cached["code"], code):
valid = True
else:
cached["attempts"] = cached.get("attempts", 0) + 1
if cached["attempts"] >= 5:
_email_codes_cache.pop(email, None)
if not valid:
raise HTTPException(status_code=400, detail="验证码错误或已失效,请重新获取")
_email_codes_cache.pop(email, None)
# Strictly look up by normalized email first to prevent cross-domain takeover (alex@qq.com vs alex@gmail.com)
user = get_user_by_email(email)
is_new = False
if not user:
prefix = email.split("@")[0]
base_name = re.sub(r"[^a-zA-Z0-9_]", "_", prefix)[:16] or "user"
email_hash = hashlib.sha256(email.encode("utf-8")).hexdigest()[:6]
candidate = f"mail_{base_name}"
if get_user_by_username(candidate):
candidate = f"mail_{base_name}_{email_hash}"
pwd_hash, salt = hash_password(secrets.token_hex(16))
try:
user_id = create_user(candidate, pwd_hash, salt, email=email)
username = candidate
except Exception:
username = f"mail_{base_name}_{secrets.token_hex(3)}"
user_id = create_user(username, pwd_hash, salt, email=email)
user = {"id": user_id, "username": username}
is_new = True
token = create_access_token(user["id"], user["username"])
return {
"token": token,
"user": {"id": user["id"], "username": user["username"]},
"is_new_user": is_new,
}
@router.post("/register", response_model=AuthResponse)
def register(req: AuthRequest, request: Request):
ip = _get_client_ip(request)
check_rate_limit(f"reg_ip:{ip}", max_requests=20, window_seconds=60)
username = req.username.strip()
if not username or len(username) < 2:
raise HTTPException(status_code=400, detail="用户名长度不能少于 2 个字符")
if not re.match(r"^[\w\-\u4e00-\u9fff]+$", username):
raise HTTPException(status_code=400, detail="用户名仅支持字母、数字、下划线、连字符或中文")
user = get_user_by_username(username)
if user:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="用户名已被使用,请更换或直接登录",
)
if not req.password or len(req.password) < 6:
raise HTTPException(
status_code=400,
detail="注册账号需设置至少 6 位密码",
)
pwd_hash, salt = hash_password(req.password)
user_id = create_user(username, pwd_hash, salt)
token = create_access_token(user_id, username)
return {
"token": token,
"user": {"id": user_id, "username": username},
"is_new_user": True,
}
@router.post("/login", response_model=AuthResponse)
def login(req: AuthRequest, request: Request):
ip = _get_client_ip(request)
check_rate_limit(f"login_ip:{ip}", max_requests=30, window_seconds=60)
username = req.username.strip()
if not username:
raise HTTPException(status_code=400, detail="用户名不能为空")
user = get_user_by_username(username)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="用户不存在或密码错误",
)
is_guest_account = verify_password("codestar_pass_auto", user["password_hash"], user["salt"])
if not is_guest_account:
if not req.password:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="该账号已设置密码,请输入密码登录",
)
if not verify_password(req.password, user["password_hash"], user["salt"]):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="密码错误,请核对密码",
)
else:
if req.password and not verify_password(req.password, user["password_hash"], user["salt"]):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="密码错误,请核对密码",
)
token = create_access_token(user["id"], user["username"])
return {
"token": token,
"user": {"id": user["id"], "username": user["username"]},
"is_new_user": False,
}
@router.get("/me", response_model=UserProfileResponse)
def get_me(user_info: Dict[str, Any] = Depends(require_current_user)):
user_id = user_info["id"]
user = get_user_by_id(user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
stats = get_user_stats(user_id)
return {
"id": user["id"],
"username": user["username"],
"created_at": user["created_at"],
"solved_count": stats["solved_count"],
"attempted_count": stats["attempted_count"],
"total_submissions": stats["total_submissions"],
"is_vip": bool(user.get("is_vip", 0)),
"vip_expire_at": user.get("vip_expire_at"),
"vip_level": user.get("vip_level", "none"),
"star_coins": int(user.get("star_coins", 0)),
}
@router.get("/progress", response_model=Dict[str, str])
def get_my_progress(user_info: Dict[str, Any] = Depends(require_current_user)):
"""Returns mapping of problem_slug -> 'AC' | 'Attempted' for current user."""
return get_user_progress(user_info["id"])
@router.get("/stats", response_model=UserStatsResponse)
def get_stats(user_info: Dict[str, Any] = Depends(require_current_user)):
"""Returns comprehensive LeetCode-style profile statistics for current user."""
user_id = user_info["id"]
return get_user_detailed_stats(user_id)