| 1 |
import math |
| 2 |
import secrets |
| 3 |
import string |
| 4 |
from typing import TypedDict |
| 5 |
|
| 6 |
from django.utils.crypto import get_random_string |
| 7 |
|
| 8 |
|
| 9 |
class UserCodeFormat(TypedDict, total=False): |
| 10 |
dashed: bool |
| 11 |
length: int |
| 12 |
numeric: bool |
| 13 |
|
| 14 |
|
| 15 |
# https://datatracker.ietf.org/doc/html/rfc8628#section-6.1 |
| 16 |
_ALPHA_ALLOWED_CHARS = "BCDFGHJKLMNPQRSTVWXZ" |
| 17 |
|
| 18 |
|
| 19 |
def generate_user_code( |
| 20 |
*, |
| 21 |
length: int | None = None, |
| 22 |
numeric: bool = False, |
| 23 |
allowed_chars: str | None = None, |
| 24 |
dashed: bool = True, |
| 25 |
) -> str: |
| 26 |
""" """ |
| 27 |
if not allowed_chars: |
| 28 |
if numeric: |
| 29 |
allowed_chars = string.digits |
| 30 |
else: |
| 31 |
allowed_chars = _ALPHA_ALLOWED_CHARS |
| 32 |
if length is None: |
| 33 |
length = 9 if numeric else 8 |
| 34 |
code = get_random_string(length=length, allowed_chars=allowed_chars) |
| 35 |
if dashed: |
| 36 |
parts = 2 if length <= 8 else 3 |
| 37 |
chunk = math.ceil(length / parts) |
| 38 |
code = "-".join(code[i : i + chunk] for i in range(0, length, chunk)) |
| 39 |
return code |
| 40 |
|
| 41 |
|
| 42 |
def _strip_punctuation(code: str) -> str: |
| 43 |
"""https://datatracker.ietf.org/doc/html/rfc8628#section-6.1 |
| 44 |
|
| 45 |
When processing the inputted user code, the server should strip dashes and |
| 46 |
other punctuation that it added for readability (making the inclusion of |
| 47 |
such punctuation by the user optional). |
| 48 |
""" |
| 49 |
return code.translate(str.maketrans("", "", string.punctuation + string.whitespace)) |
| 50 |
|
| 51 |
|
| 52 |
def compare_user_code(*, actual: str, expected: str) -> bool: |
| 53 |
actual = _strip_punctuation(actual).lower() |
| 54 |
expected = _strip_punctuation(expected).lower() |
| 55 |
return bool(expected) and secrets.compare_digest(actual, expected) |