59 lines
2.0 KiB
Python
59 lines
2.0 KiB
Python
from datetime import datetime, timedelta
|
|
from jose import jwt
|
|
from passlib.context import CryptContext
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
|
|
SECRET_KEY = "your-secret-key"
|
|
ALGORITHM = "HS256"
|
|
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
|
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False)
|
|
|
|
def create_access_token(data: dict, expires_delta: timedelta | None = None):
|
|
to_encode = data.copy()
|
|
if expires_delta:
|
|
expire = datetime.utcnow() + expires_delta
|
|
else:
|
|
expire = datetime.utcnow() + timedelta(minutes=15)
|
|
to_encode.update({"exp": expire})
|
|
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
|
return encoded_jwt
|
|
|
|
def get_password_hash(password):
|
|
return pwd_context.hash(password)
|
|
|
|
def verify_password(plain_password, hashed_password):
|
|
return pwd_context.verify(plain_password, hashed_password)
|
|
import requests
|
|
from sqlalchemy.orm import Session
|
|
import crud
|
|
|
|
# --- WeChat OAuth ---
|
|
WECHAT_APP_ID = "your-wechat-app-id"
|
|
WECHAT_APP_SECRET = "your-wechat-app-secret"
|
|
|
|
def get_wechat_openid(code: str) -> str | None:
|
|
"""
|
|
Simulates fetching openid from WeChat server.
|
|
In a real application, this would involve an HTTP request to WeChat's API.
|
|
"""
|
|
# url = f"https://api.weixin.qq.com/sns/jscode2session?appid={WECHAT_APP_ID}&secret={WECHAT_APP_SECRET}&js_code={code}&grant_type=authorization_code"
|
|
# response = requests.get(url)
|
|
# if response.status_code == 200:
|
|
# data = response.json()
|
|
# return data.get("openid")
|
|
# return None
|
|
|
|
# For simulation purposes, we'll just return a mock openid based on the code
|
|
if code == "valid_wechat_code":
|
|
return "mock_wechat_openid_12345"
|
|
return None
|
|
|
|
def authenticate_wechat_user(db: Session, code: str):
|
|
openid = get_wechat_openid(code)
|
|
if not openid:
|
|
return None, False
|
|
|
|
user, is_new_user = crud.get_or_create_oauth_user(db, provider="wechat", openid=openid)
|
|
return user, is_new_user |