tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

helpers.py (2203B)


      1 from urllib.parse import parse_qs
      2 
      3 from wptserve.utils import isomorphic_encode
      4 
      5 def setNoCacheAndCORSHeaders(request, response):
      6    """Set Cache-Control, CORS and Content-Type headers appropriate for the cookie tests."""
      7    headers = [(b"Content-Type", b"application/json"),
      8               (b"Access-Control-Allow-Credentials", b"true")]
      9 
     10    origin = b"*"
     11    if b"origin" in request.headers:
     12        origin = request.headers[b"origin"]
     13 
     14    headers.append((b"Access-Control-Allow-Origin", origin))
     15    #headers.append(("Access-Control-Allow-Credentials", "true"))
     16    headers.append((b"Cache-Control", b"no-cache"))
     17    headers.append((b"Expires", b"Fri, 01 Jan 1990 00:00:00 GMT"))
     18 
     19    return headers
     20 
     21 def makeCookieHeader(name, value, otherAttrs):
     22    """Make a Set-Cookie header for a cookie with the name, value and attributes provided."""
     23    def makeAV(a, v):
     24        if None == v or b"" == v:
     25            return a
     26        if isinstance(v, int):
     27            return b"%s=%i" % (a, v)
     28        else:
     29            return b"%s=%s" % (a, v)
     30 
     31    # ensure cookie name is always first
     32    attrs = [b"%s=%s" % (name, value)]
     33    attrs.extend(makeAV(a, v) for (a, v) in otherAttrs.items())
     34    return (b"Set-Cookie", b"; ".join((attrs)))
     35 
     36 def makeDropCookie(name, secure):
     37    attrs = {b"max-age": 0, b"path": b"/"}
     38    if secure:
     39        attrs[b"secure"] = b""
     40    return makeCookieHeader(name, b"", attrs)
     41 
     42 def readParameter(request, paramName, requireValue):
     43    """Read a parameter from the request. Raise if requireValue is set and the
     44    parameter has an empty value or is not present."""
     45    params = parse_qs(request.url_parts.query)
     46    param = params[paramName][0].strip()
     47    if len(param) == 0:
     48        raise Exception(u"Empty or missing name parameter.")
     49    return isomorphic_encode(param)
     50 
     51 def readCookies(request):
     52    """Read the cookies from the client present in the request."""
     53    cookies = {}
     54    for key in request.cookies:
     55        for cookie in request.cookies.get_list(key):
     56            # do we care we'll clobber cookies here? If so, do we
     57            # need to modify the test to take cookie names and value lists?
     58            cookies[key] = cookie.value
     59    return cookies