impl/python/normalise_recovery_code.py
925 bytes · the Python implementation · view raw
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
from typing import Optional
from .auth_recovery_codes_generate_recovery_codes import RECOVERY_ALPHABET ← generateRecoveryCodes, another function of this group · built into the same file, even by a slim install
def normalise_recovery_code(code: str) -> Optional[str]:
"""A typed code in its one stored form: ASCII lower case, spaces and
hyphens dropped, i/l read as 1 and o as 0 (Crockford). None when what is
left is not exactly 16 characters of the alphabet."""
if not isinstance(code, str):
raise TypeError("code must be a string")
out = []
for ch in code:
if ch == " " or ch == "-":
continue
# ASCII only: str.lower() would also fold letters from other scripts.
if "A" <= ch <= "Z":
ch = chr(ord(ch) + 32)
if ch == "i" or ch == "l":
ch = "1"
elif ch == "o":
ch = "0"
if ch not in RECOVERY_ALPHABET:
return None
out.append(ch)
return "".join(out) if len(out) == 16 else None