Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add convenience methods for cookie creation and deletion #2706

Merged
merged 53 commits into from
Mar 21, 2023
Merged
Show file tree
Hide file tree
Changes from 47 commits
Commits
Show all changes
53 commits
Select commit Hold shift + click to select a range
6e70e74
Add convenience methods for cookie creation and deletion
ahopkins Mar 5, 2023
4f2653e
Restore del
ahopkins Mar 5, 2023
124a2ce
Backwards compat, forward thinking
ahopkins Mar 14, 2023
9c075b6
Merge branch 'main' of github.com:sanic-org/sanic into cookie-method
ahopkins Mar 14, 2023
1786289
Add delitem deprecation notice
ahopkins Mar 14, 2023
2e1ec42
Add get full deprecation notice
ahopkins Mar 14, 2023
5af8dee
Add deprecation docstring
ahopkins Mar 14, 2023
83a66d2
Better deprecation docstring
ahopkins Mar 14, 2023
3d1a677
Add has_cookie
ahopkins Mar 14, 2023
86b391b
Same defaults
ahopkins Mar 14, 2023
769ff3c
Better deprecation message
ahopkins Mar 14, 2023
cfe184f
Accessor annotations
ahopkins Mar 14, 2023
24b2c36
make pretty
ahopkins Mar 14, 2023
f971936
parse cookies
ahopkins Mar 14, 2023
bc7f204
Revert quote translator
ahopkins Mar 14, 2023
ed29169
make pretty
ahopkins Mar 14, 2023
99d09f4
make pretty
ahopkins Mar 14, 2023
db5ba6f
Add unit tests
ahopkins Mar 14, 2023
a3b7b7d
Make pretty
ahopkins Mar 14, 2023
f95262b
Fix unit tests
ahopkins Mar 15, 2023
831bb32
Directly include unquote
ahopkins Mar 15, 2023
67c3dbe
Add some more unit tests
ahopkins Mar 15, 2023
ad48286
Merge branch 'main' into cookie-method
ahopkins Mar 15, 2023
f608eb8
Merge branch 'main' into cookie-method
ahopkins Mar 15, 2023
f7a6a11
Merge branch 'main' of github.com:sanic-org/sanic into cookie-method
ahopkins Mar 16, 2023
1e262bc
Move modules into their own dir
ahopkins Mar 16, 2023
315ec51
make pretty
ahopkins Mar 16, 2023
fcf3cb9
Merge branch 'cookie-method' of github.com:sanic-org/sanic into cooki…
ahopkins Mar 16, 2023
3975329
cleanup test imports
ahopkins Mar 16, 2023
e856bc3
Add test for cookie accessor
ahopkins Mar 16, 2023
05b0bc1
Make test consistent
ahopkins Mar 16, 2023
35df6e7
Remove file
ahopkins Mar 16, 2023
e07f44d
Remove additional escaping
ahopkins Mar 16, 2023
ea7dd38
Add header style getattr for hyphens
ahopkins Mar 16, 2023
6d045a5
Add test for cookie accessor with hyphens
ahopkins Mar 16, 2023
728e429
Merge branch 'main' into cookie-method
ahopkins Mar 16, 2023
2894ce7
Add new translator
ahopkins Mar 16, 2023
f8ea413
Merge branch 'cookie-method' of github.com:sanic-org/sanic into cooki…
ahopkins Mar 16, 2023
3fbf4a2
Merge branch 'main' into cookie-method
ahopkins Mar 17, 2023
d468cbd
Merge branch 'main' into cookie-method
ahopkins Mar 19, 2023
87ab27b
Merge branch 'main' into cookie-method
ahopkins Mar 20, 2023
4483cb9
Parametrize test_request_with_duplicate_cookie_key
ahopkins Mar 20, 2023
0da66b8
Merge branch 'cookie-method' of github.com:sanic-org/sanic into cooki…
ahopkins Mar 20, 2023
fd8b524
make pretty
ahopkins Mar 20, 2023
9fc06f7
Add deprecation of direct cookie encoding
ahopkins Mar 20, 2023
6cac856
Merge branch 'main' of github.com:sanic-org/sanic into cookie-method
ahopkins Mar 20, 2023
5d26f1c
Merge branch 'main' into cookie-method
Tronic Mar 20, 2023
e5add89
Speedup Cookie creation
ahopkins Mar 20, 2023
0e31b02
Merge branch 'cookie-method' of github.com:sanic-org/sanic into cooki…
ahopkins Mar 20, 2023
33f1dbb
Implement prefixes on delete_cookie
ahopkins Mar 20, 2023
3a8d4e1
typing changes
ahopkins Mar 20, 2023
0603d40
Add passthru functions on response objects for setting cookies
ahopkins Mar 21, 2023
3f0c8cb
Add test for passthru
ahopkins Mar 21, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 0 additions & 156 deletions sanic/cookies.py

This file was deleted.

4 changes: 4 additions & 0 deletions sanic/cookies/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from .response import Cookie, CookieJar


__all__ = ("Cookie", "CookieJar")
118 changes: 118 additions & 0 deletions sanic/cookies/request.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import re

from typing import Any, Dict, List, Optional

from sanic.cookies.response import Cookie
from sanic.log import deprecation
from sanic.request.parameters import RequestParameters


COOKIE_NAME_RESERVED_CHARS = re.compile(
'[\x00-\x1F\x7F-\xFF()<>@,;:\\\\"/[\\]?={} \x09]'
)
OCTAL_PATTERN = re.compile(r"\\[0-3][0-7][0-7]")
QUOTE_PATTERN = re.compile(r"[\\].")


def _unquote(str): # no cov
if str is None or len(str) < 2:
return str
if str[0] != '"' or str[-1] != '"':
return str

str = str[1:-1]

i = 0
n = len(str)
res = []
while 0 <= i < n:
o_match = OCTAL_PATTERN.search(str, i)
q_match = QUOTE_PATTERN.search(str, i)
if not o_match and not q_match:
res.append(str[i:])
break
# else:
j = k = -1
if o_match:
j = o_match.start(0)
if q_match:
k = q_match.start(0)
if q_match and (not o_match or k < j):
res.append(str[i:k])
res.append(str[k + 1])
i = k + 2
else:
res.append(str[i:j])
res.append(chr(int(str[j + 1 : j + 4], 8))) # noqa: E203
i = j + 4
return "".join(res)


def parse_cookie(raw: str):
cookies: Dict[str, List] = {}

for token in raw.split(";"):
name, __, value = token.partition("=")
name = name.strip()
value = value.strip()

if not name:
continue

if COOKIE_NAME_RESERVED_CHARS.search(name): # no cov
continue

if len(value) > 2 and value[0] == '"' and value[-1] == '"': # no cov
value = _unquote(value)

if name in cookies:
cookies[name].append(value)
else:
cookies[name] = [value]

return cookies


class CookieRequestParameters(RequestParameters):
def __getitem__(self, key: str) -> Optional[str]:
deprecation(
f"You are accessing cookie key '{key}', which is currently in "
"compat mode returning a single cookie value. Starting in v24.3 "
"accessing a cookie value like this will return a list of values. "
"To avoid this behavior and continue accessing a single value, "
f"please upgrade from request.cookies['{key}'] to "
f"request.cookies.get('{key}'). See more details: ___.",
ahopkins marked this conversation as resolved.
Show resolved Hide resolved
24.3,
)
try:
value = self._get_prefixed_cookie(key)
except KeyError:
value = super().__getitem__(key)
ahopkins marked this conversation as resolved.
Show resolved Hide resolved
return value[0]

def __getattr__(self, key: str) -> str:
if key.startswith("_"):
return self.__getattribute__(key)
key = key.rstrip("_").replace("_", "-")
return str(self.get(key, ""))

def get(self, name: str, default: Optional[Any] = None) -> Optional[Any]:
try:
return self._get_prefixed_cookie(name)[0]
except KeyError:
return super().get(name, default)

def getlist(
self, name: str, default: Optional[Any] = None
) -> Optional[Any]:
try:
return self._get_prefixed_cookie(name)
except KeyError:
return super().getlist(name, default)

def _get_prefixed_cookie(self, name: str) -> Any:
getitem = super().__getitem__
try:
return getitem(f"{Cookie.HOST_PREFIX}{name}")
except KeyError:
return getitem(f"{Cookie.SECURE_PREFIX}{name}")
Loading