askrobots / dbbasic-sessions
Public
Sessions with no server storage: HMAC-signed cookies for Python web apps.
flask_example.py · 4.5 KB · 148 lines
| 1 | """ |
| 2 | Flask integration example for dbbasic-sessions |
| 3 | |
| 4 | Shows how to integrate session management with Flask. |
| 5 | """ |
| 6 | |
| 7 | from flask import Flask, request, redirect, render_template_string, make_response |
| 8 | from dbbasic_sessions import create_session, get_session, destroy_session |
| 9 | |
| 10 | app = Flask(__name__) |
| 11 | |
| 12 | # Mock user database |
| 13 | USERS = { |
| 14 | 'alice@example.com': {'password': 'password123', 'id': '1', 'name': 'Alice'}, |
| 15 | 'bob@example.com': {'password': 'password456', 'id': '2', 'name': 'Bob'}, |
| 16 | } |
| 17 | |
| 18 | |
| 19 | @app.route('/') |
| 20 | def home(): |
| 21 | """Home page - shows login or dashboard""" |
| 22 | user_id = get_session(request.cookies.get('session')) |
| 23 | |
| 24 | if user_id: |
| 25 | # Find user |
| 26 | user = next((u for u in USERS.values() if u['id'] == user_id), None) |
| 27 | if user: |
| 28 | return render_template_string(''' |
| 29 | <h1>Welcome, {{ user.name }}!</h1> |
| 30 | <p>You are logged in as {{ user.name }} (ID: {{ user.id }})</p> |
| 31 | <a href="/logout">Logout</a> |
| 32 | ''', user=user) |
| 33 | |
| 34 | return render_template_string(''' |
| 35 | <h1>Please Log In</h1> |
| 36 | <form method="POST" action="/login"> |
| 37 | <input type="email" name="email" placeholder="Email" required><br> |
| 38 | <input type="password" name="password" placeholder="Password" required><br> |
| 39 | <button type="submit">Login</button> |
| 40 | </form> |
| 41 | <p><small>Try: alice@example.com / password123</small></p> |
| 42 | ''') |
| 43 | |
| 44 | |
| 45 | @app.route('/login', methods=['POST']) |
| 46 | def login(): |
| 47 | """Handle login""" |
| 48 | email = request.form.get('email') |
| 49 | password = request.form.get('password') |
| 50 | |
| 51 | # Authenticate |
| 52 | user = USERS.get(email) |
| 53 | if user and user['password'] == password: |
| 54 | # Create session |
| 55 | token = create_session(user['id'], ttl=3600) # 1 hour |
| 56 | |
| 57 | # Set cookie |
| 58 | response = make_response(redirect('/')) |
| 59 | response.set_cookie( |
| 60 | 'session', |
| 61 | token, |
| 62 | httponly=True, # Prevent JavaScript access (XSS protection) |
| 63 | secure=True, # HTTPS only (set to False for local dev) |
| 64 | samesite='Lax', # CSRF protection |
| 65 | max_age=3600 # 1 hour |
| 66 | ) |
| 67 | return response |
| 68 | |
| 69 | return render_template_string(''' |
| 70 | <h1>Login Failed</h1> |
| 71 | <p>Invalid email or password</p> |
| 72 | <a href="/">Try again</a> |
| 73 | ''') |
| 74 | |
| 75 | |
| 76 | @app.route('/logout') |
| 77 | def logout(): |
| 78 | """Handle logout""" |
| 79 | token = request.cookies.get('session') |
| 80 | destroy_session(token) # No-op server-side |
| 81 | |
| 82 | # Delete cookie |
| 83 | response = make_response(redirect('/')) |
| 84 | response.delete_cookie('session') |
| 85 | return response |
| 86 | |
| 87 | |
| 88 | @app.route('/profile') |
| 89 | def profile(): |
| 90 | """Protected route - requires authentication""" |
| 91 | user_id = get_session(request.cookies.get('session')) |
| 92 | |
| 93 | if not user_id: |
| 94 | return redirect('/') |
| 95 | |
| 96 | user = next((u for u in USERS.values() if u['id'] == user_id), None) |
| 97 | if not user: |
| 98 | return redirect('/') |
| 99 | |
| 100 | return render_template_string(''' |
| 101 | <h1>Profile</h1> |
| 102 | <p><strong>Name:</strong> {{ user.name }}</p> |
| 103 | <p><strong>Email:</strong> {{ email }}</p> |
| 104 | <p><strong>User ID:</strong> {{ user.id }}</p> |
| 105 | <a href="/">Home</a> | <a href="/logout">Logout</a> |
| 106 | ''', user=user, email=next(k for k, v in USERS.items() if v['id'] == user_id)) |
| 107 | |
| 108 | |
| 109 | # Middleware pattern - require authentication decorator |
| 110 | def require_auth(f): |
| 111 | """Decorator to require authentication""" |
| 112 | def wrapper(*args, **kwargs): |
| 113 | user_id = get_session(request.cookies.get('session')) |
| 114 | if not user_id: |
| 115 | return redirect('/') |
| 116 | return f(*args, **kwargs) |
| 117 | wrapper.__name__ = f.__name__ |
| 118 | return wrapper |
| 119 | |
| 120 | |
| 121 | @app.route('/admin') |
| 122 | @require_auth |
| 123 | def admin(): |
| 124 | """Protected route using decorator""" |
| 125 | user_id = get_session(request.cookies.get('session')) |
| 126 | user = next((u for u in USERS.values() if u['id'] == user_id), None) |
| 127 | |
| 128 | return render_template_string(''' |
| 129 | <h1>Admin Panel</h1> |
| 130 | <p>Welcome, {{ user.name }}!</p> |
| 131 | <p>This route is protected by @require_auth decorator</p> |
| 132 | <a href="/">Home</a> |
| 133 | ''', user=user) |
| 134 | |
| 135 | |
| 136 | if __name__ == '__main__': |
| 137 | print("\n" + "="*50) |
| 138 | print("Flask + dbbasic-sessions Example") |
| 139 | print("="*50) |
| 140 | print("\nStarting server on http://localhost:5000") |
| 141 | print("\nTest credentials:") |
| 142 | print(" Email: alice@example.com") |
| 143 | print(" Password: password123") |
| 144 | print("\nNOTE: Set secure=False in set_cookie() for local development") |
| 145 | print(" (HTTPS required for secure=True)") |
| 146 | print("\n" + "="*50 + "\n") |
| 147 | |
| 148 | app.run(debug=True) |