function logout_v2
Maturity: 36
Flask route handler that logs out the current user by clearing their session data and redirecting them to the login page.
File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
679 - 683
679 - 683
Complexity:
simple
simple
Purpose
This function handles user logout functionality in a Flask web application. It clears all session data to terminate the user's authenticated session, displays an informational message to confirm logout, and redirects the user to the login page. This is a standard security practice for web applications to properly terminate user sessions.
Source Code
def logout():
"""Logout user"""
session.clear()
flash('You have been logged out', 'info')
return redirect(url_for('login'))
Return Value
Returns a Flask redirect response object that redirects the user to the 'login' route. The redirect is generated using Flask's url_for() function to dynamically resolve the login route URL.
Dependencies
flask
Required Imports
from flask import session
from flask import redirect
from flask import url_for
from flask import flash
Usage Example
from flask import Flask, session, redirect, url_for, flash
app = Flask(__name__)
app.secret_key = 'your-secret-key-here'
@app.route('/login')
def login():
return 'Login Page'
@app.route('/logout')
def logout():
"""Logout user"""
session.clear()
flash('You have been logged out', 'info')
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(debug=True)
Best Practices
- Always clear the entire session on logout to prevent session fixation attacks
- Use flash messages to provide user feedback about successful logout
- Redirect to login page after logout to prevent access to protected resources
- Ensure Flask secret_key is set to a strong, random value in production
- Consider adding @login_required decorator to protected routes to enforce authentication
- In production, use secure session cookies with httponly and secure flags enabled
- Consider implementing CSRF protection for logout if using POST method instead of GET
- For enhanced security, consider regenerating session IDs on login/logout
Tags
Similar Components
AI-powered semantic similarity - components with related functionality: