cookie.py (1728B)
1 import json 2 3 from cookies.resources.helpers import setNoCacheAndCORSHeaders 4 from wptserve.utils import isomorphic_decode 5 from wptserve.utils import isomorphic_encode 6 7 def set_cookie(headers, cookie_string): 8 """Helper method to add a Set-Cookie header""" 9 headers.append((b'Set-Cookie', isomorphic_encode(cookie_string))) 10 11 def main(request, response): 12 """Set a cookie via GET params. 13 14 Usage: `/cookie.py?set={cookie}` 15 16 The passed-in cookie string should be stringified via JSON.stringify() (in 17 the case of multiple cookie headers sent in an array) and encoded via 18 encodeURIComponent, otherwise `parse_qsl` will split on any semicolons 19 (used by the Request.GET property getter). Note that values returned by 20 Request.GET will decode any percent-encoded sequences sent in a GET param 21 (which may or may not be surprising depending on what you're doing). 22 23 Note: here we don't use Response.delete_cookie() or similar other methods 24 in this resources directory because there are edge cases that are impossible 25 to express via those APIs, namely a bare (`Path`) or empty Path (`Path=`) 26 attribute. Instead, we pipe through the entire cookie and append `max-age=0` 27 to it. 28 """ 29 headers = setNoCacheAndCORSHeaders(request, response) 30 31 if b'set' in request.GET: 32 cookie = isomorphic_decode(request.GET[b'set']) 33 cookie = json.loads(cookie) 34 cookies = cookie if isinstance(cookie, list) else [cookie] 35 for c in cookies: 36 set_cookie(headers, c) 37 38 if b'location' in request.GET: 39 headers.append((b'Location', request.GET[b'location'])) 40 return 302, headers, b'{"redirect": true}' 41 42 return headers, b'{"success": true}'