Sessions with no server storage: HMAC-signed cookies for Python web apps.

0 downloads

dbbasic-sessions/examples/simple_example.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-sessions.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-sessions.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-sessions.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Update README with PyPI and GitHub links 75676a8 1 year, 1 month ago History
simple_example.py · 5.5 KB · 198 lines
1"""
2Simple example showing basic usage of dbbasic-sessions
3
4This demonstrates the core functionality without any web framework.
5"""
6
7from dbbasic_sessions import create_session, get_session, destroy_session
8import time
9
10
11def example_basic_usage():
12 """Basic session creation and verification"""
13 print("="*50)
14 print("Basic Usage Example")
15 print("="*50)
16
17 # Create a session for user ID 42
18 token = create_session(user_id=42)
19 print(f"\n1. Created session token:")
20 print(f" {token}")
21 print(f" Length: {len(token)} characters")
22
23 # Verify the session
24 user_id = get_session(token)
25 print(f"\n2. Verified session:")
26 print(f" User ID: {user_id}")
27 assert user_id == '42', "User ID should match"
28
29 # Logout (no-op server-side)
30 destroy_session(token)
31 print(f"\n3. Logged out (no-op server-side)")
32
33 # Token still valid until expiry
34 user_id = get_session(token)
35 print(f" Token still valid: {user_id is not None}")
36 print(f" (Client must delete cookie)")
37
38
39def example_custom_ttl():
40 """Example with custom TTL"""
41 print("\n" + "="*50)
42 print("Custom TTL Example")
43 print("="*50)
44
45 # Create session with 2 second TTL
46 token = create_session(user_id='alice', ttl=2)
47 print(f"\n1. Created session with 2 second TTL")
48
49 # Verify immediately
50 user_id = get_session(token)
51 print(f"2. Immediately: {user_id}")
52 assert user_id == 'alice'
53
54 # Wait for expiration
55 print(f"3. Waiting 2.5 seconds...")
56 time.sleep(2.5)
57
58 # Try to verify after expiration
59 user_id = get_session(token)
60 print(f"4. After expiration: {user_id}")
61 assert user_id is None, "Should be expired"
62
63
64def example_multiple_sessions():
65 """Example with multiple concurrent sessions"""
66 print("\n" + "="*50)
67 print("Multiple Sessions Example")
68 print("="*50)
69
70 # Create sessions for different users
71 users = ['alice', 'bob', 'charlie']
72 sessions = {}
73
74 print("\n1. Creating sessions for multiple users:")
75 for user in users:
76 token = create_session(user)
77 sessions[user] = token
78 print(f" {user}: {token[:40]}...")
79
80 # Verify all sessions
81 print("\n2. Verifying all sessions:")
82 for user, token in sessions.items():
83 verified_id = get_session(token)
84 status = "✓" if verified_id == user else "✗"
85 print(f" {status} {user}: {verified_id}")
86
87
88def example_invalid_tokens():
89 """Example showing how invalid tokens are handled"""
90 print("\n" + "="*50)
91 print("Invalid Token Example")
92 print("="*50)
93
94 invalid_tokens = [
95 ('Empty string', ''),
96 ('None', None),
97 ('Invalid format', 'not-a-valid-token'),
98 ('Tampered', 'eyJhbGc.wrong-signature'),
99 ]
100
101 print("\n1. Testing invalid tokens:")
102 for name, token in invalid_tokens:
103 user_id = get_session(token)
104 print(f" {name}: {user_id}")
105 assert user_id is None, f"{name} should return None"
106
107 print("\n All invalid tokens correctly rejected ✓")
108
109
110def example_token_structure():
111 """Show the structure of a token"""
112 print("\n" + "="*50)
113 print("Token Structure Example")
114 print("="*50)
115
116 token = create_session(user_id=42, ttl=3600)
117
118 # Split token
119 payload, signature = token.split('.')
120
121 print(f"\n1. Token structure:")
122 print(f" Full token: {token}")
123 print(f"\n2. Payload (base64 encoded):")
124 print(f" {payload}")
125
126 # Decode payload (it's not secret, just signed)
127 import base64
128 import json
129 decoded = json.loads(base64.urlsafe_b64decode(payload))
130 print(f"\n3. Decoded payload:")
131 print(f" {json.dumps(decoded, indent=2)}")
132
133 print(f"\n4. Signature (HMAC-SHA256):")
134 print(f" {signature}")
135 print(f" Length: {len(signature)} hex characters (256 bits)")
136
137
138def example_web_framework_pattern():
139 """Show typical web framework usage pattern"""
140 print("\n" + "="*50)
141 print("Web Framework Pattern Example")
142 print("="*50)
143
144 # Simulate a login request
145 print("\n1. User logs in:")
146 print(" Email: alice@example.com")
147 print(" Password: ********")
148
149 # Authenticate (mock)
150 user_authenticated = True
151 user_id = '42'
152
153 if user_authenticated:
154 # Create session
155 token = create_session(user_id, ttl=2592000) # 30 days
156 print(f"\n2. Session created:")
157 print(f" Token: {token[:40]}...")
158
159 # In real app, set cookie:
160 print(f"\n3. Set cookie (in real app):")
161 print(f" response.set_cookie('session', token,")
162 print(f" httponly=True,")
163 print(f" secure=True,")
164 print(f" samesite='Lax',")
165 print(f" max_age=2592000)")
166
167 # Simulate next request
168 print(f"\n4. Next request - verify session:")
169 request_token = token # From cookie
170 verified_user_id = get_session(request_token)
171
172 if verified_user_id:
173 print(f" User authenticated: {verified_user_id}")
174 print(f" Load user data from database...")
175 else:
176 print(f" Not authenticated, redirect to login")
177
178
179def main():
180 """Run all examples"""
181 print("\n" + "="*60)
182 print(" dbbasic-sessions Examples")
183 print("="*60)
184
185 example_basic_usage()
186 example_custom_ttl()
187 example_multiple_sessions()
188 example_invalid_tokens()
189 example_token_structure()
190 example_web_framework_pattern()
191
192 print("\n" + "="*60)
193 print(" All examples completed successfully! ✓")
194 print("="*60 + "\n")
195
196
197if __name__ == '__main__':
198 main()