🔍 Code Extractor

function allowed_file

Maturity: 34

Validates whether a filename has an allowed file extension by checking if it contains a dot and if the extension (after the last dot) exists in a predefined ALLOWED_EXTENSIONS collection.

File:
/tf/active/vicechatdev/leexi/app.py
Lines:
46 - 49
Complexity:
simple

Purpose

This function is a security utility commonly used in file upload functionality to restrict which file types can be uploaded to a web application. It prevents users from uploading potentially dangerous or unsupported file types by validating the file extension against a whitelist defined in ALLOWED_EXTENSIONS. This is a critical security measure in Flask applications handling file uploads.

Source Code

def allowed_file(filename):
    """Check if file extension is allowed"""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

Parameters

Name Type Default Kind
filename - - positional_or_keyword

Parameter Details

filename: A string representing the name of the file to validate, including its extension (e.g., 'document.pdf', 'image.jpg'). The function expects a filename that may or may not contain a file extension. Empty strings or filenames without extensions will return False.

Return Value

Returns a boolean value: True if the filename contains a dot AND the extension (the part after the last dot, converted to lowercase) is present in the ALLOWED_EXTENSIONS collection; False otherwise. Returns False for filenames without extensions, filenames with disallowed extensions, or edge cases like '.hiddenfile' with no extension after the dot.

Usage Example

# Define allowed extensions
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'doc', 'docx'}

# Example usage
if allowed_file('document.pdf'):
    print('File is allowed')
else:
    print('File type not allowed')

# Test cases
print(allowed_file('report.pdf'))  # True (if 'pdf' in ALLOWED_EXTENSIONS)
print(allowed_file('image.PNG'))   # True (case-insensitive)
print(allowed_file('script.exe'))  # False (if 'exe' not in ALLOWED_EXTENSIONS)
print(allowed_file('noextension')) # False (no dot in filename)
print(allowed_file('.hidden'))     # False (no extension after dot)

Best Practices

  • Always define ALLOWED_EXTENSIONS as a set rather than a list for O(1) lookup performance
  • Use this function in conjunction with werkzeug.utils.secure_filename() to sanitize filenames before saving
  • This function only checks extensions, not actual file content - consider adding MIME type validation for stronger security
  • Keep ALLOWED_EXTENSIONS restrictive and only include file types your application actually needs to process
  • Remember that file extensions can be spoofed - this should be one layer of validation, not the only security measure
  • Consider the security implications of each allowed extension (e.g., executable files, scripts)
  • Document which extensions are allowed and why in your application's configuration

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function test_multiple_file_upload 50.8% similar

    A test function that validates multiple file upload functionality to a Flask application endpoint by sending a transcript file and multiple previous report files.

    From: /tf/active/vicechatdev/leexi/test_flask_upload.py
  • function test_upload_modalities 48.4% similar

    Integration test function that validates FileCloud upload functionality by testing both new file creation and existing file update scenarios.

    From: /tf/active/vicechatdev/SPFCsync/test_upload_modalities.py
  • function download_file 47.8% similar

    Flask route handler that serves generated report files for download from a designated reports folder.

    From: /tf/active/vicechatdev/leexi/app.py
  • function validate_sharepoint_url 47.7% similar

    Validates that a given URL string conforms to SharePoint site URL format requirements, checking for proper protocol, domain, and path structure.

    From: /tf/active/vicechatdev/SPFCsync/validate_config.py
  • function is_valid_auth_cookies 45.0% similar

    Validates whether a dictionary of cookies contains valid SharePoint/Office 365 authentication cookies (FedAuth or SPOIDCRL).

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/auth/providers/saml_token_provider.py
← Back to Browse