"""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"""
您好!您正在登录或注册 CodeStar 平台。您的 6 位动态验证码为:
• 验证码有效期为 10 分钟,请勿将验证码泄露给他人。
• 如非您本人操作,请忽略此邮件。