Spaces:
Paused
Paused
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,14 +1,123 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
@
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import secrets
|
| 3 |
+
import requests
|
| 4 |
+
from fastapi import FastAPI, Depends, HTTPException, Header
|
| 5 |
+
from sqlalchemy import create_engine, Column, Integer, String, Boolean, DateTime, func
|
| 6 |
+
from sqlalchemy.ext.declarative import declarative_base
|
| 7 |
+
from sqlalchemy.orm import sessionmaker, Session
|
| 8 |
+
from pydantic import BaseModel
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
|
| 11 |
+
# Load environment variables from .env file
|
| 12 |
+
load_dotenv()
|
| 13 |
|
| 14 |
+
# Environment variables for MySQL and main API settings
|
| 15 |
+
MYSQL_USER = os.getenv("MYSQL_USER")
|
| 16 |
+
MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD")
|
| 17 |
+
MYSQL_HOST = os.getenv("MYSQL_HOST")
|
| 18 |
+
MYSQL_DB = os.getenv("MYSQL_DB")
|
| 19 |
+
MAIN_API_KEY = os.getenv("MAIN_API_KEY")
|
| 20 |
+
MAIN_API_URL = os.getenv("MAIN_API_URL", "https://api.typegpt.net/v1/chat/completions")
|
| 21 |
+
MODEL_NAME = os.getenv("MODEL_NAME", "Image-Generator")
|
| 22 |
|
| 23 |
+
DATABASE_URL = f"mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}/{MYSQL_DB}"
|
| 24 |
+
|
| 25 |
+
# SQLAlchemy setup
|
| 26 |
+
engine = create_engine(DATABASE_URL)
|
| 27 |
+
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
| 28 |
+
Base = declarative_base()
|
| 29 |
+
|
| 30 |
+
# User model
|
| 31 |
+
class User(Base):
|
| 32 |
+
__tablename__ = "users"
|
| 33 |
+
id = Column(Integer, primary_key=True, index=True)
|
| 34 |
+
username = Column(String(50), unique=True, index=True, nullable=False)
|
| 35 |
+
hashed_password = Column(String(128), nullable=False)
|
| 36 |
+
api_key = Column(String(64), unique=True, index=True, nullable=False)
|
| 37 |
+
is_admin = Column(Boolean, default=False)
|
| 38 |
+
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
| 39 |
+
|
| 40 |
+
# Create tables
|
| 41 |
+
Base.metadata.create_all(bind=engine)
|
| 42 |
+
|
| 43 |
+
app = FastAPI(title="API Key Generator & Proxy Service")
|
| 44 |
+
|
| 45 |
+
# Dependency: Database session
|
| 46 |
+
def get_db():
|
| 47 |
+
db = SessionLocal()
|
| 48 |
+
try:
|
| 49 |
+
yield db
|
| 50 |
+
finally:
|
| 51 |
+
db.close()
|
| 52 |
+
|
| 53 |
+
# Utility: Generate a unique API key
|
| 54 |
+
def generate_api_key() -> str:
|
| 55 |
+
return secrets.token_hex(16)
|
| 56 |
+
|
| 57 |
+
# Pydantic models
|
| 58 |
+
class UserCreate(BaseModel):
|
| 59 |
+
username: str
|
| 60 |
+
password: str
|
| 61 |
+
|
| 62 |
+
class UserOut(BaseModel):
|
| 63 |
+
id: int
|
| 64 |
+
username: str
|
| 65 |
+
api_key: str
|
| 66 |
+
is_admin: bool
|
| 67 |
+
|
| 68 |
+
class Config:
|
| 69 |
+
orm_mode = True
|
| 70 |
+
|
| 71 |
+
# Dependency: Validate API key from header and return current user
|
| 72 |
+
def get_current_user(x_api_key: str = Header(...), db: Session = Depends(get_db)) -> User:
|
| 73 |
+
user = db.query(User).filter(User.api_key == x_api_key).first()
|
| 74 |
+
if not user:
|
| 75 |
+
raise HTTPException(status_code=401, detail="Invalid API Key")
|
| 76 |
+
return user
|
| 77 |
+
|
| 78 |
+
# --- Endpoints ---
|
| 79 |
+
|
| 80 |
+
# 1. User Registration (generates a unique API key)
|
| 81 |
+
@app.post("/register", response_model=UserOut)
|
| 82 |
+
def register(user: UserCreate, db: Session = Depends(get_db)):
|
| 83 |
+
if db.query(User).filter(User.username == user.username).first():
|
| 84 |
+
raise HTTPException(status_code=400, detail="Username already exists")
|
| 85 |
+
new_api_key = generate_api_key()
|
| 86 |
+
# In production, use proper password hashing
|
| 87 |
+
new_user = User(username=user.username, hashed_password=user.password, api_key=new_api_key, is_admin=False)
|
| 88 |
+
db.add(new_user)
|
| 89 |
+
db.commit()
|
| 90 |
+
db.refresh(new_user)
|
| 91 |
+
return new_user
|
| 92 |
+
|
| 93 |
+
# 2. User Panel: Get current user info
|
| 94 |
+
@app.get("/user/me", response_model=UserOut)
|
| 95 |
+
def read_user_me(current_user: User = Depends(get_current_user)):
|
| 96 |
+
return current_user
|
| 97 |
+
|
| 98 |
+
# 3. Admin Panel: List all users (admin-only)
|
| 99 |
+
@app.get("/admin/users", response_model=list[UserOut])
|
| 100 |
+
def list_users(current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
| 101 |
+
if not current_user.is_admin:
|
| 102 |
+
raise HTTPException(status_code=403, detail="Not authorized")
|
| 103 |
+
users = db.query(User).all()
|
| 104 |
+
return users
|
| 105 |
+
|
| 106 |
+
# 4. Endpoint to access the main API (proxying request using main API key)
|
| 107 |
+
class RequestPayload(BaseModel):
|
| 108 |
+
prompt: str
|
| 109 |
+
|
| 110 |
+
@app.post("/generate")
|
| 111 |
+
def generate_image(payload: RequestPayload, current_user: User = Depends(get_current_user)):
|
| 112 |
+
headers = {
|
| 113 |
+
"Authorization": f"Bearer {MAIN_API_KEY}",
|
| 114 |
+
"Content-Type": "application/json"
|
| 115 |
+
}
|
| 116 |
+
data = {
|
| 117 |
+
"model": MODEL_NAME,
|
| 118 |
+
"prompt": payload.prompt
|
| 119 |
+
}
|
| 120 |
+
response = requests.post(MAIN_API_URL, json=data, headers=headers)
|
| 121 |
+
if response.status_code != 200:
|
| 122 |
+
raise HTTPException(status_code=response.status_code, detail="Error from main API")
|
| 123 |
+
return response.json()
|