function logout
Flask route handler that logs out the current user by clearing their session and redirecting them to either the login page or index page based on authentication requirements.
/tf/active/vicechatdev/docchat/app.py
781 - 789
simple
Purpose
This function handles user logout functionality in a Flask web application. It retrieves the user's email from the session for logging purposes, clears all session data to log the user out, logs the logout event, and redirects the user to the appropriate page based on whether authentication is required (configured via config.REQUIRE_AUTH).
Source Code
def logout():
"""Logout user"""
user_email = session.get('user', {}).get('email', 'unknown')
session.clear()
logger.info(f"User {user_email} logged out")
if config.REQUIRE_AUTH:
return redirect(url_for('login'))
return redirect(url_for('index'))
Return Value
Returns a Flask redirect response object. If config.REQUIRE_AUTH is True, redirects to the 'login' route; otherwise, redirects to the 'index' route. The redirect uses Flask's url_for() function to generate the appropriate URL.
Dependencies
flasklogging
Required Imports
from flask import session
from flask import redirect
from flask import url_for
import logging
import config
Usage Example
from flask import Flask, session, redirect, url_for
import logging
import config
app = Flask(__name__)
app.secret_key = 'your-secret-key'
logger = logging.getLogger(__name__)
@app.route('/logout')
def logout():
user_email = session.get('user', {}).get('email', 'unknown')
session.clear()
logger.info(f"User {user_email} logged out")
if config.REQUIRE_AUTH:
return redirect(url_for('login'))
return redirect(url_for('index'))
# To trigger logout, user navigates to /logout endpoint
# Example: GET http://localhost:5000/logout
Best Practices
- Always clear the entire session on logout to prevent session fixation attacks
- Log logout events for security auditing and monitoring purposes
- Use url_for() instead of hardcoded URLs for better maintainability
- Handle cases where user email might not exist in session (defaults to 'unknown')
- Ensure Flask SECRET_KEY is set to a strong, random value in production
- Consider implementing CSRF protection for logout if using POST method
- The function assumes session contains a nested dictionary structure: session['user']['email']
- Ensure the 'login' and 'index' routes are properly defined in the Flask application
Tags
Similar Components
AI-powered semantic similarity - components with related functionality: