pypi-streamlit

Description
A faster way to build and share data apps
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/pypi-streamlit@1.50.0

user-auth.md docs/

1
# User and Authentication
2
3
User authentication, login/logout functionality, and user information access. Streamlit provides built-in authentication capabilities for securing applications and managing user sessions.
4
5
## Capabilities
6
7
### User Information
8
9
Access current user information and profile data.
10
11
```python { .api }
12
user: UserInfoProxy
13
```
14
15
The user object provides access to authenticated user information including profile data, authentication status, and user attributes.
16
17
Example usage:
18
```python
19
# Check if user is authenticated
20
if st.user.is_authenticated:
21
st.write(f"Welcome, {st.user.email}!")
22
st.write(f"User ID: {st.user.id}")
23
24
# Access user profile
25
if hasattr(st.user, 'name'):
26
st.write(f"Name: {st.user.name}")
27
28
# Check user permissions
29
if st.user.has_permission('admin'):
30
st.write("Admin access granted")
31
else:
32
st.write("Please log in to continue")
33
```
34
35
### Authentication Functions
36
37
Functions for managing user authentication flow.
38
39
```python { .api }
40
def login(provider, *, oauth2=None):
41
"""
42
Initiate user login process with specified authentication provider.
43
44
Args:
45
provider (str): Authentication provider name
46
oauth2 (dict, optional): OAuth2 configuration parameters
47
48
Returns:
49
bool: True if login was successful
50
"""
51
52
def logout():
53
"""
54
Log out the current user and clear authentication state.
55
56
Returns:
57
bool: True if logout was successful
58
"""
59
```
60
61
Example usage:
62
```python
63
# Login with different providers
64
if not st.user.is_authenticated:
65
col1, col2, col3 = st.columns(3)
66
67
with col1:
68
if st.button("Login with Google"):
69
st.login("google")
70
71
with col2:
72
if st.button("Login with GitHub"):
73
st.login("github")
74
75
with col3:
76
if st.button("Login with Microsoft"):
77
st.login("microsoft")
78
else:
79
# User is authenticated
80
st.success(f"Logged in as {st.user.email}")
81
82
if st.button("Logout"):
83
st.logout()
84
st.rerun()
85
86
# Custom OAuth2 configuration
87
if st.button("Login with Custom Provider"):
88
oauth_config = {
89
"client_id": st.secrets["oauth_client_id"],
90
"client_secret": st.secrets["oauth_client_secret"],
91
"redirect_uri": "https://myapp.streamlit.app/auth/callback"
92
}
93
st.login("custom", oauth2=oauth_config)
94
```
95
96
### Legacy User Information (Deprecated)
97
98
Deprecated user information interface maintained for backward compatibility.
99
100
```python { .api }
101
experimental_user: DeprecatedUserInfoProxy
102
```
103
104
Example usage:
105
```python
106
# Deprecated - use st.user instead
107
if st.experimental_user.email:
108
st.write(f"User: {st.experimental_user.email}")
109
```
110
111
### Authentication Patterns
112
113
#### Basic Authentication Flow
114
115
```python
116
def show_login_page():
117
"""Display login page with provider options."""
118
st.title("Welcome")
119
st.write("Please log in to access the application")
120
121
# Provider selection
122
provider = st.selectbox(
123
"Choose login method:",
124
["google", "github", "microsoft", "azure"]
125
)
126
127
if st.button(f"Login with {provider.title()}"):
128
success = st.login(provider)
129
if success:
130
st.success("Login successful!")
131
st.rerun()
132
else:
133
st.error("Login failed. Please try again.")
134
135
def show_authenticated_app():
136
"""Display main application for authenticated users."""
137
# Header with user info and logout
138
col1, col2 = st.columns([3, 1])
139
with col1:
140
st.title("My Dashboard")
141
with col2:
142
st.write(f"👤 {st.user.email}")
143
if st.button("Logout"):
144
st.logout()
145
st.rerun()
146
147
# Main application content
148
st.write("Welcome to your dashboard!")
149
# ... rest of app
150
151
# Main app logic
152
if st.user.is_authenticated:
153
show_authenticated_app()
154
else:
155
show_login_page()
156
```
157
158
#### Role-Based Access Control
159
160
```python
161
def check_user_role():
162
"""Check user role and permissions."""
163
if not st.user.is_authenticated:
164
return None
165
166
# Get user role from profile or database
167
user_role = getattr(st.user, 'role', 'user')
168
return user_role
169
170
def require_role(required_role):
171
"""Decorator to require specific user role."""
172
def decorator(func):
173
def wrapper(*args, **kwargs):
174
current_role = check_user_role()
175
if current_role != required_role:
176
st.error(f"Access denied. {required_role.title()} role required.")
177
st.stop()
178
return func(*args, **kwargs)
179
return wrapper
180
return decorator
181
182
@require_role('admin')
183
def show_admin_panel():
184
"""Admin-only functionality."""
185
st.title("Admin Panel")
186
st.write("Admin controls here")
187
188
# Usage
189
user_role = check_user_role()
190
191
if user_role == 'admin':
192
show_admin_panel()
193
elif user_role == 'user':
194
st.title("User Dashboard")
195
st.write("User content here")
196
else:
197
st.error("Please log in to continue")
198
st.stop()
199
```
200
201
#### Session-Based User Management
202
203
```python
204
def initialize_user_session():
205
"""Initialize user session state."""
206
if "user_initialized" not in st.session_state:
207
st.session_state.user_initialized = True
208
209
if st.user.is_authenticated:
210
# Load user preferences
211
st.session_state.user_preferences = load_user_preferences(st.user.id)
212
st.session_state.user_data = load_user_data(st.user.id)
213
214
def save_user_preferences():
215
"""Save current user preferences."""
216
if st.user.is_authenticated:
217
save_preferences_to_db(st.user.id, st.session_state.user_preferences)
218
219
# Initialize on app start
220
initialize_user_session()
221
222
# User-specific functionality
223
if st.user.is_authenticated:
224
# Display personalized content
225
st.title(f"Welcome back, {getattr(st.user, 'name', st.user.email)}!")
226
227
# User preferences
228
with st.expander("Preferences"):
229
theme = st.selectbox("Theme", ["light", "dark"],
230
index=["light", "dark"].index(
231
st.session_state.get("user_preferences", {}).get("theme", "light")
232
))
233
234
if st.button("Save Preferences"):
235
st.session_state.user_preferences["theme"] = theme
236
save_user_preferences()
237
st.success("Preferences saved!")
238
```
239
240
#### Multi-Tenant Applications
241
242
```python
243
def get_user_tenant():
244
"""Get tenant information for current user."""
245
if not st.user.is_authenticated:
246
return None
247
248
# Extract tenant from user email domain or profile
249
email_domain = st.user.email.split('@')[1]
250
tenant = get_tenant_by_domain(email_domain)
251
return tenant
252
253
def load_tenant_data(tenant_id):
254
"""Load tenant-specific data and configuration."""
255
return {
256
"name": get_tenant_name(tenant_id),
257
"settings": get_tenant_settings(tenant_id),
258
"data": get_tenant_data(tenant_id)
259
}
260
261
# Multi-tenant app logic
262
if st.user.is_authenticated:
263
tenant = get_user_tenant()
264
265
if tenant:
266
# Load tenant-specific configuration
267
tenant_data = load_tenant_data(tenant.id)
268
269
# Configure app for tenant
270
st.set_page_config(
271
page_title=f"{tenant_data['name']} Dashboard",
272
page_icon=tenant.icon
273
)
274
275
st.title(f"{tenant_data['name']} Dashboard")
276
st.write(f"Welcome, {st.user.email}")
277
278
# Tenant-specific functionality
279
display_tenant_data(tenant_data['data'])
280
else:
281
st.error("No tenant found for your account")
282
else:
283
st.error("Please log in to continue")
284
```
285
286
#### Authentication Callbacks
287
288
```python
289
def on_login_success():
290
"""Handle successful login."""
291
st.session_state.login_timestamp = time.time()
292
st.session_state.user_preferences = load_user_preferences(st.user.id)
293
294
# Log login event
295
log_user_event(st.user.id, "login", {
296
"timestamp": st.session_state.login_timestamp,
297
"ip_address": st.context.headers.get("X-Forwarded-For", "unknown")
298
})
299
300
def on_logout():
301
"""Handle user logout."""
302
# Save any pending changes
303
if "user_data" in st.session_state:
304
save_user_data(st.user.id, st.session_state.user_data)
305
306
# Clear session state
307
for key in list(st.session_state.keys()):
308
if key.startswith("user_"):
309
del st.session_state[key]
310
311
# Log logout event
312
log_user_event(st.user.id, "logout", {
313
"timestamp": time.time()
314
})
315
316
# Authentication state management
317
if "auth_checked" not in st.session_state:
318
st.session_state.auth_checked = True
319
320
if st.user.is_authenticated:
321
on_login_success()
322
323
# Check for logout action
324
if st.session_state.get("logging_out", False):
325
on_logout()
326
st.logout()
327
del st.session_state.logging_out
328
st.rerun()
329
```