| |
| from fastapi import Depends, HTTPException, status |
| from fastapi.security import HTTPBasic, HTTPBasicCredentials |
| from datetime import datetime, timedelta |
| import jwt |
| import os |
|
|
| security = HTTPBasic() |
|
|
| |
| USERS = { |
| "user@example.com": { |
| "password": "password123", |
| "name": "Test User", |
| "user_id": "usr001" |
| } |
| } |
|
|
| SECRET_KEY = os.getenv("SECRET_KEY", "your-secret-key-here") |
| ALGORITHM = "HS256" |
|
|
| def create_access_token(data: dict): |
| to_encode = data.copy() |
| expire = datetime.utcnow() + timedelta(hours=24) |
| to_encode.update({"exp": expire}) |
| encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) |
| return encoded_jwt |
|
|
| def verify_token(token: str): |
| try: |
| payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) |
| return payload |
| except jwt.PyJWTError: |
| return None |
|
|
| |
| @app.post("/api/auth/login") |
| async def login(request: Request): |
| data = await request.json() |
| email = data.get("email") |
| password = data.get("password") |
| |
| if email in USERS and USERS[email]["password"] == password: |
| token = create_access_token({"sub": email, "user_id": USERS[email]["user_id"]}) |
| return { |
| "access_token": token, |
| "token_type": "bearer", |
| "user": { |
| "email": email, |
| "name": USERS[email]["name"], |
| "user_id": USERS[email]["user_id"] |
| } |
| } |
| raise HTTPException(status_code=401, detail="Invalid credentials") |
|
|
| @app.post("/api/auth/register") |
| async def register(request: Request): |
| data = await request.json() |
| email = data.get("email") |
| password = data.get("password") |
| name = data.get("name") |
| |
| if email in USERS: |
| raise HTTPException(status_code=400, detail="User already exists") |
| |
| USERS[email] = { |
| "password": password, |
| "name": name, |
| "user_id": f"usr{len(USERS)+1:03d}" |
| } |
| |
| token = create_access_token({"sub": email, "user_id": USERS[email]["user_id"]}) |
| return { |
| "access_token": token, |
| "token_type": "bearer", |
| "user": { |
| "email": email, |
| "name": name, |
| "user_id": USERS[email]["user_id"] |
| } |
| } |