Skip to main content

Universal Authentication & Authorization SDK for Python

Project description

opensora-uaa

Universal Authentication & Authorization SDK for Python/FastAPI.

Installation

pip install opensora-uaa

Usage

Basic Client Usage

from opensora_uaa import UAAClient

# Initialize client
uaa = UAAClient(project_id="your-project-id")

# Login with Google
async def login():
    result = await uaa.login_with_google(credential="google_jwt_token")
    print(f"User: {result.user.email}")
    print(f"Access Token: {result.access_token}")

# Verify token
async def verify():
    verification = await uaa.verify_token("access_token_here")
    if verification.valid:
        print(f"User: {verification.user.email}")
    else:
        print("Invalid token")

# Get current user
async def get_user():
    user = await uaa.get_current_user("access_token_here")
    print(f"User: {user.email}")

# Refresh token
async def refresh():
    result = await uaa.refresh_token("refresh_token_here")
    print(f"New access token: {result.access_token}")

# Logout
async def logout():
    await uaa.logout("access_token_here")
    print("Logged out successfully")

FastAPI Integration

Method 1: Using UAAAuth Dependency

from fastapi import FastAPI, Depends
from opensora_uaa import UAAAuth, User

app = FastAPI()
auth = UAAAuth()

@app.get("/api/profile")
async def get_profile(user: User = Depends(auth.get_current_user)):
    """Protected endpoint - requires authentication"""
    return {
        "email": user.email,
        "name": user.name,
        "provider": user.provider
    }

@app.get("/api/admin")
async def admin_only(user: User = Depends(auth.get_current_user)):
    """Check if user is admin (implement your own logic)"""
    if user.email not in ["admin@example.com"]:
        raise HTTPException(403, "Admin access required")

    return {"message": "Welcome admin"}

Method 2: Manual Token Verification

from fastapi import FastAPI, Header, HTTPException
from opensora_uaa import UAAClient

app = FastAPI()
uaa = UAAClient(project_id="your-project-id")

@app.get("/api/profile")
async def get_profile(authorization: str = Header(None)):
    if not authorization:
        raise HTTPException(401, "Missing authorization header")

    token = authorization.replace("Bearer ", "")
    verification = await uaa.verify_token(token)

    if not verification.valid:
        raise HTTPException(401, "Invalid or expired token")

    return {"user": verification.user}

Complete FastAPI Example

from fastapi import FastAPI, Depends, HTTPException
from opensora_uaa import UAAClient, UAAAuth, User
from pydantic import BaseModel

app = FastAPI()
uaa = UAAClient(project_id="your-project-id")
auth = UAAAuth()

# Request models
class GoogleLoginRequest(BaseModel):
    credential: str

class AppleLoginRequest(BaseModel):
    code: str
    id_token: str

# Public endpoints
@app.post("/auth/google")
async def google_login(request: GoogleLoginRequest):
    """Login with Google"""
    try:
        result = await uaa.login_with_google(request.credential)
        return {
            "access_token": result.access_token,
            "refresh_token": result.refresh_token,
            "user": result.user
        }
    except Exception as e:
        raise HTTPException(400, str(e))

@app.post("/auth/apple")
async def apple_login(request: AppleLoginRequest):
    """Login with Apple"""
    try:
        result = await uaa.login_with_apple(request.code, request.id_token)
        return {
            "access_token": result.access_token,
            "refresh_token": result.refresh_token,
            "user": result.user
        }
    except Exception as e:
        raise HTTPException(400, str(e))

# Protected endpoints
@app.get("/api/me")
async def get_current_user_info(user: User = Depends(auth.get_current_user)):
    """Get current authenticated user"""
    return {"user": user}

@app.post("/auth/logout")
async def logout(
    authorization: str = Header(None),
    user: User = Depends(auth.get_current_user)
):
    """Logout current user"""
    token = authorization.replace("Bearer ", "")
    await uaa.logout(token)
    return {"message": "Logged out successfully"}

# Startup/Shutdown events
@app.on_event("shutdown")
async def shutdown():
    await uaa.close()

Context Manager Usage

async with UAAClient(project_id="your-project-id") as uaa:
    result = await uaa.login_with_google("credential")
    print(result.user.email)
# Client is automatically closed

API Reference

UAAClient

Main client for UAA operations.

Constructor

UAAClient(
    project_id: str,
    base_url: str = "https://auth.opensora.store/api/v1"
)

Methods

  • async login_with_google(credential: str) -> AuthResponse
  • async login_with_apple(code: str, id_token: str) -> AuthResponse
  • async verify_token(token: str) -> VerifyResponse
  • async get_current_user(token: str) -> User
  • async refresh_token(refresh_token: str) -> AuthResponse
  • async logout(token: str) -> None
  • async close() -> None

UAAAuth

FastAPI dependency for authentication.

Constructor

UAAAuth(base_url: str = "https://auth.opensora.store/api/v1")

Methods

  • async get_current_user(authorization: Optional[str] = None) -> User
    • Use as FastAPI dependency: user: User = Depends(auth.get_current_user)

Models

User

class User(BaseModel):
    id: str
    email: str
    name: Optional[str]
    avatar: Optional[str]
    provider: Literal['google', 'apple', 'wechat', 'github']
    created_at: datetime

AuthResponse

class AuthResponse(BaseModel):
    access_token: str
    refresh_token: str
    token_type: str
    expires_in: int
    user: User

VerifyResponse

class VerifyResponse(BaseModel):
    valid: bool
    user: Optional[User]

Requirements

  • Python >= 3.8
  • httpx >= 0.24.0
  • pydantic >= 2.0.0

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

opensora_uaa-1.0.1.tar.gz (4.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

opensora_uaa-1.0.1-py3-none-any.whl (5.4 kB view details)

Uploaded Python 3

File details

Details for the file opensora_uaa-1.0.1.tar.gz.

File metadata

  • Download URL: opensora_uaa-1.0.1.tar.gz
  • Upload date:
  • Size: 4.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.2

File hashes

Hashes for opensora_uaa-1.0.1.tar.gz
Algorithm Hash digest
SHA256 6f2cfad0c05f41cfcd0c466bddf30bc7de2ae606e8e72e8125a4beaca619a250
MD5 9335662257b3f3f80b01f3672244c3b4
BLAKE2b-256 0a61eb80d6cd8ca66956d32d589bacea07bbf90cf8f0494426f9a61ee9e76eb2

See more details on using hashes here.

File details

Details for the file opensora_uaa-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: opensora_uaa-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 5.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.2

File hashes

Hashes for opensora_uaa-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 901c73c5a70cd93bcbdd2a62718f68f4702b82efc0e5e1f345c629228ac9599d
MD5 790172460b99929324bd2b25dcc0a176
BLAKE2b-256 c4cb9454646991516622c3e567d9fbbf8dee29d26875c39c7c55a40be885fe15

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page