function is_authenticated
Checks if a user is authenticated by verifying the presence of 'user' and 'access_token' keys in the Flask session object.
/tf/active/vicechatdev/vice_ai/complex_app.py
504 - 506
simple
Purpose
This function serves as a simple authentication guard in a Flask web application. It determines whether a user has successfully logged in by checking if both user information and an access token exist in the session. This is typically used to protect routes or conditionally display content based on authentication status. The function is part of an Azure SSO authentication flow, as indicated by the imports.
Source Code
def is_authenticated():
"""Check if user is authenticated"""
return 'user' in session and 'access_token' in session
Return Value
Returns a boolean value: True if both 'user' and 'access_token' keys exist in the Flask session object, False otherwise. This indicates whether the current user has valid authentication credentials stored in their session.
Dependencies
flask
Required Imports
from flask import session
Usage Example
from flask import Flask, session, redirect, url_for
def is_authenticated():
return 'user' in session and 'access_token' in session
app = Flask(__name__)
app.secret_key = 'your-secret-key-here'
@app.route('/protected')
def protected_route():
if not is_authenticated():
return redirect(url_for('login'))
return 'Welcome to the protected area!'
@app.route('/login')
def login():
# After successful authentication
session['user'] = {'id': '123', 'name': 'John Doe'}
session['access_token'] = 'token_value_here'
return redirect(url_for('protected_route'))
if __name__ == '__main__':
app.run()
Best Practices
- This function should be called before accessing protected resources or routes
- Ensure Flask session is properly configured with a strong SECRET_KEY to prevent session tampering
- Consider using Flask decorators (e.g., @login_required) to wrap this function for cleaner route protection
- This is a basic authentication check; for production use, consider additional validation such as token expiration checks
- The function relies on session state which is client-side; for enhanced security, validate tokens server-side or against a database
- Use HTTPS in production to protect session cookies from interception
- Consider implementing session timeout mechanisms to automatically invalidate old sessions
- This function does not validate the token itself, only its presence; implement token validation for stronger security
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function require_auth_v1 67.4% similar
-
function require_auth 67.2% similar
-
function is_admin_user 66.8% similar
-
function login_required 66.4% similar
-
function get_current_user_id 65.8% similar