|
3 | 3 | import hmac |
4 | 4 | import logging |
5 | 5 | import os |
| 6 | +import sys |
6 | 7 | import time |
7 | 8 |
|
8 | 9 | from http.cookies import SimpleCookie |
@@ -107,7 +108,7 @@ def _make_hashed_key(parts, hashfunc='sha256'): |
107 | 108 |
|
108 | 109 |
|
109 | 110 | def make_cookie(name, load, seed, expire=0, domain="", path="", timestamp="", |
110 | | - enc_key=None): |
| 111 | + enc_key=None, secure=True, http_only=True, same_site=""): |
111 | 112 | """ |
112 | 113 | Create and return a cookie |
113 | 114 |
|
@@ -137,6 +138,13 @@ def make_cookie(name, load, seed, expire=0, domain="", path="", timestamp="", |
137 | 138 | :type timestamp: text |
138 | 139 | :param enc_key: The key to use for cookie encryption. |
139 | 140 | :type enc_key: byte string |
| 141 | + :param secure: A secure cookie is only sent to the server with an encrypted request over the |
| 142 | + HTTPS protocol. |
| 143 | + :type secure: boolean |
| 144 | + :param http_only: HttpOnly cookies are inaccessible to JavaScript's Document.cookie API |
| 145 | + :type http_only: boolean |
| 146 | + :param same_site: Whether SameSite (None,Strict or Lax) should be added to the cookie |
| 147 | + :type same_site: byte string |
140 | 148 | :return: A tuple to be added to headers |
141 | 149 | """ |
142 | 150 | cookie = SimpleCookie() |
@@ -172,13 +180,24 @@ def make_cookie(name, load, seed, expire=0, domain="", path="", timestamp="", |
172 | 180 | cookie_signature(seed, load, timestamp).encode('utf-8')] |
173 | 181 |
|
174 | 182 | cookie[name] = (b"|".join(cookie_payload)).decode('utf-8') |
| 183 | + |
| 184 | + # Necessary if Python version < 3.8 |
| 185 | + if sys.version_info[:2] <= (3, 8): |
| 186 | + cookie[name]._reserved[str("samesite")] = str("SameSite") |
| 187 | + |
175 | 188 | if path: |
176 | 189 | cookie[name]["path"] = path |
177 | 190 | if domain: |
178 | 191 | cookie[name]["domain"] = domain |
179 | 192 | if expire: |
180 | 193 | cookie[name]["expires"] = _expiration(expire, |
181 | 194 | "%a, %d-%b-%Y %H:%M:%S GMT") |
| 195 | + if secure: |
| 196 | + cookie[name]["Secure"] = secure |
| 197 | + if http_only: |
| 198 | + cookie[name]["httponly"] = http_only |
| 199 | + if same_site: |
| 200 | + cookie[name]["SameSite"] = same_site |
182 | 201 |
|
183 | 202 | return tuple(cookie.output().split(": ", 1)) |
184 | 203 |
|
|
0 commit comments