@@ -79,8 +79,14 @@ def _unmask_cipher_token(token):
79
79
return '' .join (chars [x - y ] for x , y in pairs ) # Note negative values are ok
80
80
81
81
82
- def _get_new_csrf_token ():
83
- return _mask_cipher_secret (_get_new_csrf_string ())
82
+ def _add_new_csrf_cookie (request ):
83
+ """Generate a new random CSRF_COOKIE value, and add it to request.META."""
84
+ csrf_secret = _get_new_csrf_string ()
85
+ request .META .update ({
86
+ 'CSRF_COOKIE' : _mask_cipher_secret (csrf_secret ),
87
+ 'CSRF_COOKIE_NEEDS_UPDATE' : True ,
88
+ })
89
+ return csrf_secret
84
90
85
91
86
92
def get_token (request ):
@@ -93,15 +99,14 @@ def get_token(request):
93
99
header to the outgoing response. For this reason, you may need to use this
94
100
function lazily, as is done by the csrf context processor.
95
101
"""
96
- if "CSRF_COOKIE" not in request .META :
97
- csrf_secret = _get_new_csrf_string ()
98
- request .META ["CSRF_COOKIE" ] = _mask_cipher_secret (csrf_secret )
99
- else :
102
+ if 'CSRF_COOKIE' in request .META :
100
103
csrf_secret = _unmask_cipher_token (request .META ["CSRF_COOKIE" ])
101
- # Since the cookie is being used, flag to send the cookie in
102
- # process_response() (even if the client already has it) in order to renew
103
- # the expiry timer.
104
- request .META ['CSRF_COOKIE_NEEDS_UPDATE' ] = True
104
+ # Since the cookie is being used, flag to send the cookie in
105
+ # process_response() (even if the client already has it) in order to
106
+ # renew the expiry timer.
107
+ request .META ['CSRF_COOKIE_NEEDS_UPDATE' ] = True
108
+ else :
109
+ csrf_secret = _add_new_csrf_cookie (request )
105
110
return _mask_cipher_secret (csrf_secret )
106
111
107
112
@@ -110,10 +115,7 @@ def rotate_token(request):
110
115
Change the CSRF token in use for a request - should be done on login
111
116
for security purposes.
112
117
"""
113
- request .META .update ({
114
- 'CSRF_COOKIE' : _get_new_csrf_token (),
115
- 'CSRF_COOKIE_NEEDS_UPDATE' : True ,
116
- })
118
+ _add_new_csrf_cookie (request )
117
119
118
120
119
121
class InvalidTokenFormat (Exception ):
@@ -377,12 +379,11 @@ def process_request(self, request):
377
379
try :
378
380
csrf_token = self ._get_token (request )
379
381
except InvalidTokenFormat :
380
- csrf_token = _get_new_csrf_token ()
381
- request .META ["CSRF_COOKIE_NEEDS_UPDATE" ] = True
382
-
383
- if csrf_token is not None :
384
- # Use same token next time.
385
- request .META ['CSRF_COOKIE' ] = csrf_token
382
+ _add_new_csrf_cookie (request )
383
+ else :
384
+ if csrf_token is not None :
385
+ # Use same token next time.
386
+ request .META ['CSRF_COOKIE' ] = csrf_token
386
387
387
388
def process_view (self , request , callback , callback_args , callback_kwargs ):
388
389
if getattr (request , 'csrf_processing_done' , False ):
0 commit comments