askrobots / dbbasic-sessions
Public
Sessions with no server storage: HMAC-signed cookies for Python web apps.
cgi_example.py · 4.0 KB · 143 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | CGI script example for dbbasic-sessions |
| 4 | |
| 5 | Pure CGI - stateless, no shared state between requests. |
| 6 | Perfect for dbbasic-sessions philosophy. |
| 7 | |
| 8 | To run: |
| 9 | 1. chmod +x cgi_example.py |
| 10 | 2. Place in /usr/lib/cgi-bin/ or configure web server |
| 11 | 3. Access via http://localhost/cgi-bin/cgi_example.py |
| 12 | """ |
| 13 | |
| 14 | import os |
| 15 | import sys |
| 16 | import cgi |
| 17 | from dbbasic_sessions import create_session, get_session, destroy_session |
| 18 | |
| 19 | # Mock user database (in production, use dbbasic-tsv or real database) |
| 20 | USERS = { |
| 21 | 'alice@example.com': {'password': 'password123', 'id': '1', 'name': 'Alice'}, |
| 22 | } |
| 23 | |
| 24 | |
| 25 | def get_cookie(name): |
| 26 | """Parse cookie from HTTP_COOKIE environment variable""" |
| 27 | cookie_header = os.environ.get('HTTP_COOKIE', '') |
| 28 | for part in cookie_header.split(';'): |
| 29 | if '=' in part: |
| 30 | key, value = part.strip().split('=', 1) |
| 31 | if key == name: |
| 32 | return value |
| 33 | return None |
| 34 | |
| 35 | |
| 36 | def set_cookie(name, value, max_age=3600): |
| 37 | """Generate Set-Cookie header""" |
| 38 | return f"Set-Cookie: {name}={value}; HttpOnly; Secure; SameSite=Lax; Max-Age={max_age}" |
| 39 | |
| 40 | |
| 41 | def delete_cookie(name): |
| 42 | """Generate Set-Cookie header to delete cookie""" |
| 43 | return f"Set-Cookie: {name}=; Max-Age=0" |
| 44 | |
| 45 | |
| 46 | def render_html(content, headers=None): |
| 47 | """Render HTML response""" |
| 48 | if headers: |
| 49 | for header in headers: |
| 50 | print(header) |
| 51 | print("Content-Type: text/html\n") |
| 52 | print(content) |
| 53 | |
| 54 | |
| 55 | def home_page(user=None): |
| 56 | """Render home page""" |
| 57 | if user: |
| 58 | return f""" |
| 59 | <!DOCTYPE html> |
| 60 | <html> |
| 61 | <head><title>Welcome</title></head> |
| 62 | <body> |
| 63 | <h1>Welcome, {user['name']}!</h1> |
| 64 | <p>You are logged in as {user['name']} (ID: {user['id']})</p> |
| 65 | <a href="?action=logout">Logout</a> |
| 66 | </body> |
| 67 | </html> |
| 68 | """ |
| 69 | else: |
| 70 | return """ |
| 71 | <!DOCTYPE html> |
| 72 | <html> |
| 73 | <head><title>Login</title></head> |
| 74 | <body> |
| 75 | <h1>Please Log In</h1> |
| 76 | <form method="POST"> |
| 77 | <input type="email" name="email" placeholder="Email" required><br> |
| 78 | <input type="password" name="password" placeholder="Password" required><br> |
| 79 | <button type="submit" name="action" value="login">Login</button> |
| 80 | </form> |
| 81 | <p><small>Try: alice@example.com / password123</small></p> |
| 82 | </body> |
| 83 | </html> |
| 84 | """ |
| 85 | |
| 86 | |
| 87 | def main(): |
| 88 | """Main CGI handler - completely stateless""" |
| 89 | |
| 90 | # Get session token from cookie |
| 91 | token = get_cookie('session') |
| 92 | user_id = get_session(token) if token else None |
| 93 | |
| 94 | # Find user if logged in |
| 95 | user = None |
| 96 | if user_id: |
| 97 | user = next((u for u in USERS.values() if u['id'] == user_id), None) |
| 98 | |
| 99 | # Parse query string |
| 100 | form = cgi.FieldStorage() |
| 101 | action = form.getvalue('action', '') |
| 102 | |
| 103 | # Handle logout |
| 104 | if action == 'logout': |
| 105 | destroy_session(token) |
| 106 | render_html( |
| 107 | '<html><body>Logged out. <a href="?">Back to login</a></body></html>', |
| 108 | headers=[delete_cookie('session')] |
| 109 | ) |
| 110 | return |
| 111 | |
| 112 | # Handle login POST |
| 113 | if action == 'login' and os.environ.get('REQUEST_METHOD') == 'POST': |
| 114 | email = form.getvalue('email', '') |
| 115 | password = form.getvalue('password', '') |
| 116 | |
| 117 | db_user = USERS.get(email) |
| 118 | if db_user and db_user['password'] == password: |
| 119 | # Create session |
| 120 | new_token = create_session(db_user['id'], ttl=3600) |
| 121 | |
| 122 | # Redirect with cookie |
| 123 | render_html( |
| 124 | '<html><body>Logged in. <a href="?">Continue</a></body></html>', |
| 125 | headers=[set_cookie('session', new_token)] |
| 126 | ) |
| 127 | return |
| 128 | else: |
| 129 | render_html( |
| 130 | '<html><body>Login failed. <a href="?">Try again</a></body></html>' |
| 131 | ) |
| 132 | return |
| 133 | |
| 134 | # Show home page |
| 135 | render_html(home_page(user)) |
| 136 | |
| 137 | |
| 138 | if __name__ == '__main__': |
| 139 | try: |
| 140 | main() |
| 141 | except Exception as e: |
| 142 | print("Content-Type: text/html\n") |
| 143 | print(f"<html><body><h1>Error</h1><pre>{e}</pre></body></html>") |