function get_user_id
Maturity: 32
Retrieves the current user's email address from the Flask session object, returning 'unknown' if not found.
File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
517 - 519
517 - 519
Complexity:
simple
simple
Purpose
This function provides a simple way to identify the current authenticated user in a Flask web application by extracting their email address from the session. It's commonly used for logging, auditing, or user-specific operations. The function safely handles missing session data by returning a default 'unknown' value.
Source Code
def get_user_id():
"""Get current user ID"""
return session.get('user', {}).get('email', 'unknown')
Return Value
Returns a string representing the user's email address if present in session['user']['email'], otherwise returns the string 'unknown'. The return type is always str.
Dependencies
flask
Required Imports
from flask import session
Usage Example
from flask import Flask, session
app = Flask(__name__)
app.secret_key = 'your-secret-key'
def get_user_id():
return session.get('user', {}).get('email', 'unknown')
@app.route('/profile')
def profile():
user_id = get_user_id()
return f'Current user: {user_id}'
# Assuming session is populated elsewhere:
# session['user'] = {'email': 'user@example.com'}
# Then get_user_id() returns 'user@example.com'
# If session is empty, get_user_id() returns 'unknown'
Best Practices
- Ensure Flask session is properly configured with a SECRET_KEY before using this function
- This function assumes the session structure has 'user' dictionary with 'email' key - ensure consistency across the application
- Consider using a more robust user identification method (like user ID) instead of email for internal operations
- The function name 'get_user_id' is misleading as it returns email, not a numeric ID - consider renaming to 'get_user_email' for clarity
- Always validate that the session is active and user is authenticated before relying on this function in security-critical operations
- The 'unknown' default may not be suitable for all use cases - consider raising an exception or returning None for unauthenticated users in security contexts
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function get_user_email 91.1% similar
-
function get_current_user 85.0% similar
-
function get_current_user_id 82.9% similar
-
function get_user_name 81.3% similar
-
function get_current_username 73.2% similar