Sessions, Cookies, and State

Working with Cookies

Cookies are small pieces of data stored by the web browser and sent back to the server with each request. They provide a way to maintain state and store user preferences across HTTP requests. Django provides comprehensive cookie handling capabilities with built-in security features.

Working with Cookies

Cookies are small pieces of data stored by the web browser and sent back to the server with each request. They provide a way to maintain state and store user preferences across HTTP requests. Django provides comprehensive cookie handling capabilities with built-in security features.

Understanding Cookies

# Cookie anatomy and properties
class CookieAnatomy:
    """Understanding cookie structure and properties"""
    
    @staticmethod
    def cookie_components():
        """Essential components of HTTP cookies"""
        
        components = {
            'name_value_pair': {
                'description': 'The actual data stored in the cookie',
                'format': 'name=value',
                'example': 'user_preference=dark_theme',
                'rules': [
                    'Name is case-sensitive',
                    'Value is URL-encoded string',
                    'Both name and value cannot contain spaces, commas, or semicolons'
                ]
            },
            'domain': {
                'description': 'Specifies which hosts can receive the cookie',
                'format': 'Domain=example.com',
                'examples': [
                    'example.com (exact domain)',
                    '.example.com (domain and subdomains)'
                ],
                'rules': [
                    'Defaults to current domain',
                    'Cannot set cookies for other domains',
                    'Leading dot allows subdomain access'
                ]
            },
            'path': {
                'description': 'URL path that must exist in requested URL',
                'format': 'Path=/admin/',
                'examples': [
                    '/ (entire site)',
                    '/admin/ (admin section only)',
                    '/api/v1/ (specific API version)'
                ],
                'rules': [
                    'Defaults to current path',
                    'More specific paths take precedence',
                    'Must start with forward slash'
                ]
            },
            'expires': {
                'description': 'Absolute expiration date and time',
                'format': 'Expires=Wed, 21 Oct 2025 07:28:00 GMT',
                'rules': [
                    'Must be in GMT/UTC',
                    'Uses specific date format',
                    'Browser deletes cookie after this time'
                ]
            },
            'max_age': {
                'description': 'Cookie lifetime in seconds',
                'format': 'Max-Age=3600',
                'examples': [
                    '3600 (1 hour)',
                    '86400 (1 day)',
                    '2592000 (30 days)'
                ],
                'rules': [
                    'Takes precedence over Expires',
                    'Relative to current time',
                    'Zero or negative value deletes cookie'
                ]
            }
        }
        
        return components
    
    @staticmethod
    def security_attributes():
        """Security-related cookie attributes"""
        
        security_attrs = {
            'secure': {
                'description': 'Cookie only sent over HTTPS connections',
                'format': 'Secure',
                'importance': 'Critical for production',
                'use_cases': [
                    'Authentication cookies',
                    'Session cookies',
                    'Any sensitive data'
                ]
            },
            'httponly': {
                'description': 'Cookie not accessible via JavaScript',
                'format': 'HttpOnly',
                'importance': 'XSS attack prevention',
                'use_cases': [
                    'Session cookies',
                    'Authentication tokens',
                    'Server-only data'
                ]
            },
            'samesite': {
                'description': 'Controls cross-site request behavior',
                'format': 'SameSite=Strict|Lax|None',
                'options': {
                    'Strict': 'Never sent with cross-site requests',
                    'Lax': 'Sent with top-level navigation',
                    'None': 'Always sent (requires Secure)'
                },
                'importance': 'CSRF attack prevention'
            }
        }
        
        return security_attrs

# Cookie lifecycle management
class CookieLifecycle:
    """Managing cookie creation, modification, and deletion"""
    
    @staticmethod
    def cookie_creation_process():
        """How cookies are created and sent"""
        
        process_steps = [
            "1. Server generates Set-Cookie header in HTTP response",
            "2. Browser receives and stores cookie",
            "3. Browser validates cookie attributes (domain, path, etc.)",
            "4. Cookie stored in browser's cookie jar",
            "5. Subsequent requests to matching domain/path include cookie",
            "6. Server receives cookie in Cookie header",
            "7. Server can read and process cookie data"
        ]
        
        return process_steps
    
    @staticmethod
    def cookie_storage_limits():
        """Browser cookie storage limitations"""
        
        limits = {
            'per_cookie': {
                'size': '4KB (4096 bytes)',
                'includes': 'Name, value, and all attributes',
                'recommendation': 'Keep cookies small and focused'
            },
            'per_domain': {
                'count': '50-180 cookies (browser dependent)',
                'recommendation': 'Use sessions for large data sets'
            },
            'total_storage': {
                'size': '10MB+ (browser dependent)',
                'note': 'Shared across all domains'
            },
            'name_length': {
                'limit': 'No official limit, but keep under 4KB total',
                'recommendation': 'Use descriptive but concise names'
            }
        }
        
        return limits

Setting Cookies

# Setting cookies in Django views
def cookie_setting_examples(request):
    """Examples of setting cookies in Django"""
    
    # Basic cookie setting
    response = HttpResponse("Cookie examples")
    
    # Simple cookie
    response.set_cookie('simple_cookie', 'simple_value')
    
    # Cookie with expiration (30 days)
    response.set_cookie(
        'persistent_cookie',
        'persistent_value',
        max_age=30*24*60*60  # 30 days in seconds
    )
    
    # Secure cookie for production
    response.set_cookie(
        'secure_cookie',
        'secure_value',
        max_age=3600,        # 1 hour
        secure=True,         # HTTPS only
        httponly=True,       # No JavaScript access
        samesite='Strict'    # CSRF protection
    )
    
    # Cookie with custom domain and path
    response.set_cookie(
        'scoped_cookie',
        'scoped_value',
        domain='.example.com',  # Available to subdomains
        path='/admin/',         # Only for admin section
        max_age=86400          # 1 day
    )
    
    # Session cookie (expires when browser closes)
    response.set_cookie(
        'session_cookie',
        'session_value'
        # No max_age or expires = session cookie
    )
    
    return response

# Advanced cookie setting patterns
class AdvancedCookieManager:
    """Advanced cookie management patterns"""
    
    @staticmethod
    def set_user_preferences(response, preferences):
        """Set user preference cookies"""
        
        # Individual preference cookies
        for key, value in preferences.items():
            cookie_name = f'pref_{key}'
            response.set_cookie(
                cookie_name,
                str(value),
                max_age=365*24*60*60,  # 1 year
                secure=True,
                httponly=False,  # Allow JavaScript access for UI
                samesite='Lax'
            )
    
    @staticmethod
    def set_shopping_cart_cookie(response, cart_data):
        """Set shopping cart cookie with JSON data"""
        
        import json
        
        # Serialize cart data
        cart_json = json.dumps(cart_data)
        
        # Check size limit
        if len(cart_json.encode('utf-8')) > 3000:  # Leave room for other attributes
            raise ValueError("Cart data too large for cookie storage")
        
        response.set_cookie(
            'shopping_cart',
            cart_json,
            max_age=7*24*60*60,  # 1 week
            secure=True,
            httponly=True,
            samesite='Lax'
        )
    
    @staticmethod
    def set_analytics_cookie(response, user_id, tracking_data):
        """Set analytics tracking cookie"""
        
        import json
        from django.utils import timezone
        
        analytics_data = {
            'user_id': user_id,
            'first_visit': timezone.now().isoformat(),
            'tracking_data': tracking_data
        }
        
        response.set_cookie(
            'analytics',
            json.dumps(analytics_data),
            max_age=2*365*24*60*60,  # 2 years
            secure=True,
            httponly=True,
            samesite='Lax'
        )

# Cookie setting in different contexts
def cookie_context_examples():
    """Examples of setting cookies in different contexts"""
    
    # In a regular view
    def regular_view(request):
        response = render(request, 'template.html')
        response.set_cookie('view_cookie', 'value')
        return response
    
    # In a redirect response
    def redirect_with_cookie(request):
        response = redirect('success_page')
        response.set_cookie('redirect_cookie', 'success')
        return response
    
    # In a JSON response
    def json_with_cookie(request):
        data = {'status': 'success'}
        response = JsonResponse(data)
        response.set_cookie('json_cookie', 'api_value')
        return response
    
    # In middleware
    class CookieMiddleware:
        def __init__(self, get_response):
            self.get_response = get_response
        
        def __call__(self, request):
            response = self.get_response(request)
            
            # Set cookie on every response
            if not request.COOKIES.get('visitor_id'):
                import uuid
                response.set_cookie(
                    'visitor_id',
                    str(uuid.uuid4()),
                    max_age=365*24*60*60
                )
            
            return response
    
    return {
        'regular_view': regular_view,
        'redirect_with_cookie': redirect_with_cookie,
        'json_with_cookie': json_with_cookie,
        'middleware': CookieMiddleware
    }

Reading Cookies

# Reading cookies in Django views
def cookie_reading_examples(request):
    """Examples of reading cookies in Django"""
    
    # Basic cookie reading
    simple_value = request.COOKIES.get('simple_cookie')
    
    # Reading with default value
    theme = request.COOKIES.get('theme', 'light')
    
    # Check if cookie exists
    if 'user_id' in request.COOKIES:
        user_id = request.COOKIES['user_id']
    else:
        user_id = None
    
    # Reading all cookies
    all_cookies = request.COOKIES
    
    # Reading and parsing JSON cookie
    import json
    cart_data = request.COOKIES.get('shopping_cart')
    if cart_data:
        try:
            cart = json.loads(cart_data)
        except json.JSONDecodeError:
            cart = []
    else:
        cart = []
    
    # Reading multiple preference cookies
    preferences = {}
    for cookie_name, cookie_value in request.COOKIES.items():
        if cookie_name.startswith('pref_'):
            pref_name = cookie_name[5:]  # Remove 'pref_' prefix
            preferences[pref_name] = cookie_value
    
    context = {
        'simple_value': simple_value,
        'theme': theme,
        'user_id': user_id,
        'all_cookies': all_cookies,
        'cart': cart,
        'preferences': preferences
    }
    
    return render(request, 'cookie_display.html', context)

# Advanced cookie reading patterns
class CookieReader:
    """Advanced cookie reading utilities"""
    
    @staticmethod
    def get_user_preferences(request):
        """Extract user preferences from cookies"""
        
        default_preferences = {
            'theme': 'light',
            'language': 'en',
            'timezone': 'UTC',
            'items_per_page': 20
        }
        
        preferences = {}
        
        for pref_name, default_value in default_preferences.items():
            cookie_name = f'pref_{pref_name}'
            cookie_value = request.COOKIES.get(cookie_name, default_value)
            
            # Type conversion based on default value type
            if isinstance(default_value, int):
                try:
                    preferences[pref_name] = int(cookie_value)
                except (ValueError, TypeError):
                    preferences[pref_name] = default_value
            elif isinstance(default_value, bool):
                preferences[pref_name] = cookie_value.lower() in ('true', '1', 'yes')
            else:
                preferences[pref_name] = cookie_value
        
        return preferences
    
    @staticmethod
    def get_shopping_cart(request):
        """Extract shopping cart from cookie"""
        
        import json
        
        cart_cookie = request.COOKIES.get('shopping_cart')
        
        if not cart_cookie:
            return {'items': [], 'total': 0}
        
        try:
            cart_data = json.loads(cart_cookie)
            
            # Validate cart structure
            if not isinstance(cart_data, dict) or 'items' not in cart_data:
                return {'items': [], 'total': 0}
            
            return cart_data
        
        except json.JSONDecodeError:
            return {'items': [], 'total': 0}
    
    @staticmethod
    def get_analytics_data(request):
        """Extract analytics data from cookies"""
        
        import json
        from django.utils import timezone
        
        analytics_cookie = request.COOKIES.get('analytics')
        
        if not analytics_cookie:
            return None
        
        try:
            analytics_data = json.loads(analytics_cookie)
            
            # Parse datetime strings
            if 'first_visit' in analytics_data:
                analytics_data['first_visit'] = timezone.datetime.fromisoformat(
                    analytics_data['first_visit']
                )
            
            return analytics_data
        
        except (json.JSONDecodeError, ValueError):
            return None
    
    @staticmethod
    def get_cookie_consent_status(request):
        """Check cookie consent status"""
        
        consent_cookie = request.COOKIES.get('cookie_consent')
        
        if not consent_cookie:
            return {'given': False, 'categories': []}
        
        try:
            import json
            consent_data = json.loads(consent_cookie)
            
            return {
                'given': consent_data.get('given', False),
                'categories': consent_data.get('categories', []),
                'timestamp': consent_data.get('timestamp')
            }
        
        except json.JSONDecodeError:
            # Legacy boolean cookie
            return {
                'given': consent_cookie.lower() in ('true', '1', 'yes'),
                'categories': ['all'] if consent_cookie.lower() in ('true', '1', 'yes') else []
            }

Deleting Cookies

# Deleting cookies in Django
def cookie_deletion_examples(request):
    """Examples of deleting cookies"""
    
    response = HttpResponse("Cookie deletion examples")
    
    # Simple cookie deletion
    response.delete_cookie('simple_cookie')
    
    # Delete cookie with specific domain and path
    response.delete_cookie(
        'scoped_cookie',
        domain='.example.com',
        path='/admin/'
    )
    
    # Delete all preference cookies
    for cookie_name in request.COOKIES:
        if cookie_name.startswith('pref_'):
            response.delete_cookie(cookie_name)
    
    # Clear shopping cart cookie
    response.delete_cookie('shopping_cart')
    
    return response

# Advanced cookie deletion patterns
class CookieDeleter:
    """Advanced cookie deletion utilities"""
    
    @staticmethod
    def clear_user_session_cookies(response, request):
        """Clear all user session-related cookies"""
        
        session_cookies = [
            'sessionid',
            'csrftoken',
            'user_preferences',
            'shopping_cart',
            'last_activity'
        ]
        
        for cookie_name in session_cookies:
            if cookie_name in request.COOKIES:
                response.delete_cookie(cookie_name)
    
    @staticmethod
    def clear_tracking_cookies(response, request):
        """Clear all tracking and analytics cookies"""
        
        tracking_prefixes = ['analytics_', 'tracking_', 'ga_', 'fb_']
        
        for cookie_name in request.COOKIES:
            for prefix in tracking_prefixes:
                if cookie_name.startswith(prefix):
                    response.delete_cookie(cookie_name)
                    break
    
    @staticmethod
    def selective_cookie_cleanup(response, request, keep_cookies=None):
        """Delete all cookies except specified ones"""
        
        keep_cookies = keep_cookies or ['sessionid', 'csrftoken']
        
        for cookie_name in request.COOKIES:
            if cookie_name not in keep_cookies:
                response.delete_cookie(cookie_name)
    
    @staticmethod
    def logout_cookie_cleanup(response, request):
        """Comprehensive cookie cleanup on logout"""
        
        # Essential cookies to keep
        essential_cookies = ['csrftoken']
        
        # Cookies to explicitly delete
        delete_cookies = [
            'sessionid',
            'user_preferences',
            'shopping_cart',
            'remember_me',
            'last_login'
        ]
        
        # Delete specific cookies
        for cookie_name in delete_cookies:
            if cookie_name in request.COOKIES:
                response.delete_cookie(cookie_name)
        
        # Delete all preference cookies
        for cookie_name in request.COOKIES:
            if (cookie_name.startswith('pref_') and 
                cookie_name not in essential_cookies):
                response.delete_cookie(cookie_name)

# Cookie deletion in views
def logout_view(request):
    """Logout view with comprehensive cookie cleanup"""
    
    from django.contrib.auth import logout
    
    # Perform Django logout
    logout(request)
    
    # Create response
    response = redirect('login')
    
    # Clean up cookies
    CookieDeleter.logout_cookie_cleanup(response, request)
    
    # Add success message
    messages.success(request, 'You have been logged out successfully.')
    
    return response

def privacy_reset_view(request):
    """Reset all privacy-related cookies"""
    
    response = redirect('privacy_settings')
    
    # Clear tracking cookies
    CookieDeleter.clear_tracking_cookies(response, request)
    
    # Reset cookie consent
    response.delete_cookie('cookie_consent')
    
    messages.info(request, 'Privacy settings have been reset.')
    
    return response

Signed Cookies for Security

Understanding Signed Cookies

# Signed cookies for tamper protection
class SignedCookieManager:
    """Managing signed cookies for security"""
    
    @staticmethod
    def signed_cookie_concept():
        """Understanding signed cookies"""
        
        concept = {
            'purpose': 'Prevent cookie tampering',
            'mechanism': 'Cryptographic signature using SECRET_KEY',
            'security': 'Detects any modification to cookie value',
            'use_cases': [
                'User authentication tokens',
                'Shopping cart totals',
                'User permissions',
                'Sensitive preferences'
            ],
            'limitations': [
                'Still visible to client',
                'Not encrypted (use encryption for sensitive data)',
                'Larger cookie size due to signature'
            ]
        }
        
        return concept
    
    @staticmethod
    def signing_process():
        """How Django signs cookies"""
        
        process = [
            "1. Take original cookie value",
            "2. Create HMAC signature using SECRET_KEY and optional salt",
            "3. Combine value and signature with separator",
            "4. Base64 encode the result",
            "5. Send as cookie value",
            "6. On reading, verify signature matches value",
            "7. Raise BadSignature exception if tampered"
        ]
        
        return process

# Setting signed cookies
def signed_cookie_examples(request):
    """Examples of setting and reading signed cookies"""
    
    response = HttpResponse("Signed cookie examples")
    
    # Basic signed cookie
    response.set_signed_cookie('user_id', '12345')
    
    # Signed cookie with salt for additional security
    response.set_signed_cookie(
        'user_permissions',
        'admin,editor',
        salt='permissions-salt'
    )
    
    # Signed cookie with expiration
    response.set_signed_cookie(
        'cart_total',
        '99.99',
        max_age=3600,  # 1 hour
        salt='cart-salt'
    )
    
    # Complex data in signed cookie
    import json
    user_data = {
        'id': 12345,
        'role': 'admin',
        'permissions': ['read', 'write', 'delete']
    }
    
    response.set_signed_cookie(
        'user_context',
        json.dumps(user_data),
        salt='user-context-salt',
        max_age=86400  # 1 day
    )
    
    return response

# Reading signed cookies
def read_signed_cookies(request):
    """Examples of reading signed cookies"""
    
    from django.core.signing import BadSignature
    
    # Basic signed cookie reading
    try:
        user_id = request.get_signed_cookie('user_id')
    except BadSignature:
        user_id = None  # Cookie was tampered with
    
    # Signed cookie with salt
    try:
        permissions = request.get_signed_cookie(
            'user_permissions',
            salt='permissions-salt'
        )
        permission_list = permissions.split(',')
    except BadSignature:
        permission_list = []
    
    # Signed cookie with default value
    try:
        cart_total = request.get_signed_cookie(
            'cart_total',
            salt='cart-salt',
            default='0.00'
        )
        cart_total = float(cart_total)
    except (BadSignature, ValueError):
        cart_total = 0.00
    
    # Complex data from signed cookie
    try:
        user_context_json = request.get_signed_cookie(
            'user_context',
            salt='user-context-salt'
        )
        
        import json
        user_context = json.loads(user_context_json)
    except (BadSignature, json.JSONDecodeError):
        user_context = {}
    
    context = {
        'user_id': user_id,
        'permissions': permission_list,
        'cart_total': cart_total,
        'user_context': user_context
    }
    
    return render(request, 'signed_cookie_display.html', context)

# Advanced signed cookie patterns
class AdvancedSignedCookies:
    """Advanced patterns for signed cookies"""
    
    @staticmethod
    def secure_user_session(response, user):
        """Create secure user session with signed cookies"""
        
        import json
        from django.utils import timezone
        
        # User session data
        session_data = {
            'user_id': user.id,
            'username': user.username,
            'is_staff': user.is_staff,
            'last_login': timezone.now().isoformat(),
            'session_version': 1  # For invalidating old sessions
        }
        
        # Set signed cookie with user session
        response.set_signed_cookie(
            'secure_session',
            json.dumps(session_data),
            salt='user-session-v1',
            max_age=3600,  # 1 hour
            secure=True,
            httponly=True,
            samesite='Strict'
        )
    
    @staticmethod
    def get_secure_user_session(request):
        """Get secure user session from signed cookie"""
        
        from django.core.signing import BadSignature
        import json
        
        try:
            session_json = request.get_signed_cookie(
                'secure_session',
                salt='user-session-v1'
            )
            
            session_data = json.loads(session_json)
            
            # Validate session structure
            required_fields = ['user_id', 'username', 'session_version']
            if not all(field in session_data for field in required_fields):
                return None
            
            # Check session version
            if session_data.get('session_version') != 1:
                return None
            
            return session_data
        
        except (BadSignature, json.JSONDecodeError):
            return None
    
    @staticmethod
    def shopping_cart_with_integrity(response, cart_items):
        """Shopping cart with integrity protection"""
        
        import json
        import hashlib
        
        # Calculate cart hash for integrity
        cart_data = {
            'items': cart_items,
            'item_count': len(cart_items),
            'total': sum(item.get('price', 0) * item.get('quantity', 0) 
                        for item in cart_items)
        }
        
        # Create integrity hash
        cart_json = json.dumps(cart_data, sort_keys=True)
        cart_hash = hashlib.sha256(cart_json.encode()).hexdigest()
        
        # Store cart with hash
        signed_cart = {
            'data': cart_data,
            'hash': cart_hash
        }
        
        response.set_signed_cookie(
            'secure_cart',
            json.dumps(signed_cart),
            salt='cart-integrity-v1',
            max_age=7*24*60*60  # 1 week
        )
    
    @staticmethod
    def get_shopping_cart_with_integrity(request):
        """Get shopping cart with integrity verification"""
        
        from django.core.signing import BadSignature
        import json
        import hashlib
        
        try:
            cart_json = request.get_signed_cookie(
                'secure_cart',
                salt='cart-integrity-v1'
            )
            
            signed_cart = json.loads(cart_json)
            
            # Verify structure
            if 'data' not in signed_cart or 'hash' not in signed_cart:
                return {'items': [], 'item_count': 0, 'total': 0}
            
            # Verify integrity hash
            cart_data = signed_cart['data']
            stored_hash = signed_cart['hash']
            
            cart_json = json.dumps(cart_data, sort_keys=True)
            calculated_hash = hashlib.sha256(cart_json.encode()).hexdigest()
            
            if stored_hash != calculated_hash:
                # Cart data integrity compromised
                return {'items': [], 'item_count': 0, 'total': 0}
            
            return cart_data
        
        except (BadSignature, json.JSONDecodeError):
            return {'items': [], 'item_count': 0, 'total': 0}

Security Implementation

class CookieSecurity:
    """Cookie security best practices and implementation"""
    
    @staticmethod
    def security_checklist():
        """Essential cookie security measures"""
        
        checklist = {
            'production_settings': {
                'SESSION_COOKIE_SECURE': True,
                'CSRF_COOKIE_SECURE': True,
                'SESSION_COOKIE_HTTPONLY': True,
                'CSRF_COOKIE_HTTPONLY': True,
                'SESSION_COOKIE_SAMESITE': 'Strict',
                'CSRF_COOKIE_SAMESITE': 'Strict'
            },
            'cookie_attributes': [
                'Always use Secure flag in production (HTTPS)',
                'Use HttpOnly for server-only cookies',
                'Set appropriate SameSite policy',
                'Use shortest necessary expiration time',
                'Set specific domain and path when possible'
            ],
            'data_protection': [
                'Never store sensitive data in plain cookies',
                'Use signed cookies for tamper protection',
                'Encrypt sensitive cookie data',
                'Validate all cookie data on server',
                'Use sessions for large or sensitive data'
            ],
            'privacy_compliance': [
                'Implement cookie consent mechanism',
                'Categorize cookies by purpose',
                'Provide cookie policy and documentation',
                'Allow users to manage cookie preferences',
                'Regular audit of cookie usage'
            ]
        }
        
        return checklist
    
    @staticmethod
    def secure_cookie_middleware():
        """Middleware for enforcing cookie security"""
        
        class SecureCookieMiddleware:
            """Enforce cookie security policies"""
            
            def __init__(self, get_response):
                self.get_response = get_response
            
            def __call__(self, request):
                response = self.get_response(request)
                
                # Enforce security on all cookies
                self.secure_response_cookies(response)
                
                return response
            
            def secure_response_cookies(self, response):
                """Apply security attributes to response cookies"""
                
                # Get cookies from response
                cookies = response.cookies
                
                for cookie in cookies.values():
                    # Enforce Secure flag in production
                    if settings.DEBUG is False:
                        cookie['secure'] = True
                    
                    # Enforce HttpOnly for session cookies
                    if cookie.key in ['sessionid', 'csrftoken']:
                        cookie['httponly'] = True
                    
                    # Enforce SameSite policy
                    if not cookie.get('samesite'):
                        cookie['samesite'] = 'Lax'
                    
                    # Limit cookie lifetime
                    if cookie.key.startswith('temp_'):
                        cookie['max_age'] = 3600  # 1 hour max for temp cookies
        
        return SecureCookieMiddleware
    
    @staticmethod
    def cookie_consent_system():
        """Implement cookie consent system"""
        
        class CookieConsentManager:
            """Manage cookie consent and preferences"""
            
            COOKIE_CATEGORIES = {
                'essential': {
                    'name': 'Essential Cookies',
                    'description': 'Required for basic site functionality',
                    'required': True,
                    'cookies': ['sessionid', 'csrftoken']
                },
                'functional': {
                    'name': 'Functional Cookies',
                    'description': 'Enhance site functionality and personalization',
                    'required': False,
                    'cookies': ['user_preferences', 'language', 'theme']
                },
                'analytics': {
                    'name': 'Analytics Cookies',
                    'description': 'Help us understand how visitors use our site',
                    'required': False,
                    'cookies': ['analytics', 'ga_*', 'tracking_*']
                },
                'marketing': {
                    'name': 'Marketing Cookies',
                    'description': 'Used to deliver relevant advertisements',
                    'required': False,
                    'cookies': ['marketing_*', 'ad_*', 'fb_*']
                }
            }
            
            @classmethod
            def get_consent_status(cls, request):
                """Get current consent status"""
                
                consent_cookie = request.COOKIES.get('cookie_consent')
                
                if not consent_cookie:
                    return None
                
                try:
                    import json
                    return json.loads(consent_cookie)
                except json.JSONDecodeError:
                    return None
            
            @classmethod
            def set_consent(cls, response, categories):
                """Set cookie consent preferences"""
                
                import json
                from django.utils import timezone
                
                consent_data = {
                    'categories': categories,
                    'timestamp': timezone.now().isoformat(),
                    'version': 1
                }
                
                response.set_cookie(
                    'cookie_consent',
                    json.dumps(consent_data),
                    max_age=365*24*60*60,  # 1 year
                    secure=True,
                    httponly=True,
                    samesite='Strict'
                )
            
            @classmethod
            def is_cookie_allowed(cls, request, cookie_name):
                """Check if specific cookie is allowed"""
                
                consent = cls.get_consent_status(request)
                
                if not consent:
                    # No consent given, only allow essential cookies
                    return cls.is_essential_cookie(cookie_name)
                
                allowed_categories = consent.get('categories', [])
                
                # Check each category
                for category, config in cls.COOKIE_CATEGORIES.items():
                    if category in allowed_categories or config['required']:
                        for pattern in config['cookies']:
                            if cls.cookie_matches_pattern(cookie_name, pattern):
                                return True
                
                return False
            
            @classmethod
            def is_essential_cookie(cls, cookie_name):
                """Check if cookie is essential"""
                
                essential_config = cls.COOKIE_CATEGORIES['essential']
                
                for pattern in essential_config['cookies']:
                    if cls.cookie_matches_pattern(cookie_name, pattern):
                        return True
                
                return False
            
            @classmethod
            def cookie_matches_pattern(cls, cookie_name, pattern):
                """Check if cookie name matches pattern"""
                
                if pattern.endswith('*'):
                    return cookie_name.startswith(pattern[:-1])
                else:
                    return cookie_name == pattern
        
        return CookieConsentManager

# Cookie security views
def cookie_consent_view(request):
    """Handle cookie consent form"""
    
    if request.method == 'POST':
        # Get selected categories
        selected_categories = request.POST.getlist('categories')
        
        # Always include essential cookies
        if 'essential' not in selected_categories:
            selected_categories.append('essential')
        
        # Set consent cookie
        response = redirect('home')
        CookieSecurity.cookie_consent_system().set_consent(
            response, selected_categories
        )
        
        messages.success(request, 'Cookie preferences saved.')
        return response
    
    # Display consent form
    categories = CookieSecurity.cookie_consent_system().COOKIE_CATEGORIES
    current_consent = CookieSecurity.cookie_consent_system().get_consent_status(request)
    
    context = {
        'categories': categories,
        'current_consent': current_consent
    }
    
    return render(request, 'cookie_consent.html', context)

Cookies provide a fundamental mechanism for maintaining state in web applications. By understanding cookie properties, security attributes, and Django's cookie API, you can implement secure and efficient client-side state management while protecting user privacy and complying with regulations.