|
| 1 | +"""Example showing how to use SQLSpec session backend with Litestar.""" |
| 2 | + |
| 3 | +from litestar import Litestar, get, post |
| 4 | +from litestar.config.session import SessionConfig |
| 5 | +from litestar.datastructures import State |
| 6 | + |
| 7 | +from sqlspec.adapters.sqlite.config import SqliteConfig |
| 8 | +from sqlspec.extensions.litestar import SQLSpec, SQLSpecSessionBackend |
| 9 | + |
| 10 | +# Configure SQLSpec with SQLite database |
| 11 | +sqlite_config = SqliteConfig( |
| 12 | + pool_config={"database": "sessions.db"}, |
| 13 | + migration_config={"script_location": "migrations", "version_table_name": "sqlspec_migrations"}, |
| 14 | +) |
| 15 | + |
| 16 | +# Create SQLSpec plugin |
| 17 | +sqlspec_plugin = SQLSpec(sqlite_config) |
| 18 | + |
| 19 | +# Create session backend using SQLSpec |
| 20 | +session_backend = SQLSpecSessionBackend( |
| 21 | + config=sqlite_config, |
| 22 | + table_name="user_sessions", |
| 23 | + session_lifetime=3600, # 1 hour |
| 24 | +) |
| 25 | + |
| 26 | +# Configure session middleware |
| 27 | +session_config = SessionConfig( |
| 28 | + backend=session_backend, |
| 29 | + cookie_https_only=False, # Set to True in production |
| 30 | + cookie_secure=False, # Set to True in production with HTTPS |
| 31 | + cookie_domain="localhost", |
| 32 | + cookie_path="/", |
| 33 | + cookie_max_age=3600, |
| 34 | + cookie_same_site="lax", |
| 35 | + cookie_http_only=True, |
| 36 | + session_cookie_name="sqlspec_session", |
| 37 | +) |
| 38 | + |
| 39 | + |
| 40 | +@get("/") |
| 41 | +async def index() -> dict[str, str]: |
| 42 | + """Homepage route.""" |
| 43 | + return {"message": "SQLSpec Session Example"} |
| 44 | + |
| 45 | + |
| 46 | +@get("/login") |
| 47 | +async def login_form() -> str: |
| 48 | + """Simple login form.""" |
| 49 | + return """ |
| 50 | + <html> |
| 51 | + <body> |
| 52 | + <h2>Login</h2> |
| 53 | + <form method="post" action="/login"> |
| 54 | + <input type="text" name="username" placeholder="Username" required> |
| 55 | + <input type="password" name="password" placeholder="Password" required> |
| 56 | + <button type="submit">Login</button> |
| 57 | + </form> |
| 58 | + </body> |
| 59 | + </html> |
| 60 | + """ |
| 61 | + |
| 62 | + |
| 63 | +@post("/login") |
| 64 | +async def login(data: dict[str, str], request) -> dict[str, str]: |
| 65 | + """Handle login and create session.""" |
| 66 | + username = data.get("username") |
| 67 | + password = data.get("password") |
| 68 | + |
| 69 | + # Simple authentication (use proper auth in production) |
| 70 | + if username == "admin" and password == "secret": |
| 71 | + # Store user data in session |
| 72 | + request.set_session( |
| 73 | + {"user_id": 1, "username": username, "login_time": "2024-01-01T12:00:00Z", "roles": ["admin", "user"]} |
| 74 | + ) |
| 75 | + return {"message": f"Welcome, {username}!"} |
| 76 | + |
| 77 | + return {"error": "Invalid credentials"} |
| 78 | + |
| 79 | + |
| 80 | +@get("/profile") |
| 81 | +async def profile(request) -> dict[str, str]: |
| 82 | + """User profile route - requires session.""" |
| 83 | + session_data = request.session |
| 84 | + |
| 85 | + if not session_data or "user_id" not in session_data: |
| 86 | + return {"error": "Not logged in"} |
| 87 | + |
| 88 | + return { |
| 89 | + "user_id": session_data["user_id"], |
| 90 | + "username": session_data["username"], |
| 91 | + "login_time": session_data["login_time"], |
| 92 | + "roles": session_data["roles"], |
| 93 | + } |
| 94 | + |
| 95 | + |
| 96 | +@post("/logout") |
| 97 | +async def logout(request) -> dict[str, str]: |
| 98 | + """Logout and clear session.""" |
| 99 | + request.clear_session() |
| 100 | + return {"message": "Logged out successfully"} |
| 101 | + |
| 102 | + |
| 103 | +@get("/admin/sessions") |
| 104 | +async def admin_sessions(request, state: State) -> dict[str, any]: |
| 105 | + """Admin route to view all active sessions.""" |
| 106 | + session_data = request.session |
| 107 | + |
| 108 | + if not session_data or "admin" not in session_data.get("roles", []): |
| 109 | + return {"error": "Admin access required"} |
| 110 | + |
| 111 | + # Get session backend from state |
| 112 | + backend = session_backend |
| 113 | + session_ids = await backend.get_all_session_ids() |
| 114 | + |
| 115 | + return { |
| 116 | + "active_sessions": len(session_ids), |
| 117 | + "session_ids": session_ids[:10], # Limit to first 10 for display |
| 118 | + } |
| 119 | + |
| 120 | + |
| 121 | +@post("/admin/cleanup") |
| 122 | +async def cleanup_sessions(request, state: State) -> dict[str, str]: |
| 123 | + """Admin route to clean up expired sessions.""" |
| 124 | + session_data = request.session |
| 125 | + |
| 126 | + if not session_data or "admin" not in session_data.get("roles", []): |
| 127 | + return {"error": "Admin access required"} |
| 128 | + |
| 129 | + # Clean up expired sessions |
| 130 | + backend = session_backend |
| 131 | + await backend.delete_expired_sessions() |
| 132 | + |
| 133 | + return {"message": "Expired sessions cleaned up"} |
| 134 | + |
| 135 | + |
| 136 | +# Create Litestar application |
| 137 | +app = Litestar( |
| 138 | + route_handlers=[index, login_form, login, profile, logout, admin_sessions, cleanup_sessions], |
| 139 | + plugins=[sqlspec_plugin], |
| 140 | + session_config=session_config, |
| 141 | + debug=True, |
| 142 | +) |
| 143 | + |
| 144 | + |
| 145 | +if __name__ == "__main__": |
| 146 | + import uvicorn |
| 147 | + |
| 148 | + print("Starting SQLSpec Session Example...") |
| 149 | + print("Visit http://localhost:8000 to view the application") |
| 150 | + print("Login with username 'admin' and password 'secret'") |
| 151 | + |
| 152 | + uvicorn.run(app, host="0.0.0.0", port=8000) |
0 commit comments