<s> """<STR_LIT>""" <EOL> from django . conf import settings <EOL> from django . http import HttpResponseForbidden <EOL> import md5 <EOL> import re <EOL> import itertools <EOL> _ERROR_MSG = '<STR_LIT>' <EOL> _POST_FORM_RE = re . compile ( r'<STR_LIT>' , re . IGNORECASE ) <EOL> _HTML_TYPES = ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> def _make_token ( session_id ) : <EOL> return md5 . new ( settings . SECRET_KEY + session_id ) . hexdigest ( ) <EOL> class CsrfMiddleware ( object ) : <EOL> """<STR_LIT>""" <EOL> def process_request ( self , request ) : <EOL> if request . POST : <EOL> try : <EOL> session_id = request . COOKIES [ settings . SESSION_COOKIE_NAME ] <EOL> except KeyError : <EOL> return None <EOL> csrf_token = _make_token ( session_id ) <EOL> try : <EOL> request_csrf_token = request . POST [ '<STR_LIT>' ] <EOL> except KeyError : <EOL> return HttpResponseForbidden ( _ERROR_MSG ) <EOL> if request_csrf_token != csrf_token : <EOL> return HttpResponseForbidden ( _ERROR_MSG ) <EOL> return None <EOL> def process_response ( self , request , response ) : <EOL> csrf_token = None <EOL> try : <EOL> cookie = response . cookies [ settings . SESSION_COOKIE_NAME ] <EOL> csrf_token = _make_token ( cookie . value ) <EOL> except KeyError : <EOL> try : <EOL> session_id = request . COOKIES [ settings . SESSION_COOKIE_NAME ] <EOL> csrf_token = _make_token ( session_id ) <EOL> except KeyError : <EOL> pass <EOL> if csrf_token is not None and response [ '<STR_LIT:Content-Type>' ] . split ( '<STR_LIT:;>' ) [ <NUM_LIT:0> ] in _HTML_TYPES : <EOL> idattributes = itertools . chain ( ( "<STR_LIT>" , ) , <EOL> itertools . repeat ( '<STR_LIT>' ) ) <EOL> def add_csrf_field ( match ) : <EOL> """<STR_LIT>""" <EOL> return match . group ( ) + "<STR_LIT>" + "<STR_LIT>" + idattributes . next ( ) + "<STR_LIT>" + csrf_token + "<STR_LIT>" <EOL> response . content = _POST_FORM_RE . sub ( add_csrf_field , response . content ) <EOL> return response </s>
