79 lines
2.1 KiB
Python
79 lines
2.1 KiB
Python
import datetime
|
|
import re
|
|
from dataclasses import dataclass
|
|
import socket
|
|
|
|
# TODO: disallow underscores. Will break many tests with usernames that include _
|
|
VALID_USERNAME_RE = re.compile(r"^[a-z][a-z0-9-_]+$")
|
|
|
|
|
|
class fuzzy_result:
|
|
def __init__(self, string, score):
|
|
self.string = string
|
|
self.score = score
|
|
|
|
# consider a score worse if the edit distance is larger
|
|
def __lt__(self, other):
|
|
return self.score > other.score
|
|
|
|
def __gt__(self, other):
|
|
return self.score < other.score
|
|
|
|
def __le__(self, other):
|
|
return self.score >= other.score
|
|
|
|
def __ge__(self, other):
|
|
return self.score <= other.score
|
|
|
|
def __eq__(self, other):
|
|
return self.score == other.score
|
|
|
|
def __ne__(self, other):
|
|
return self.score != other.score
|
|
|
|
|
|
# compute levenshtein edit distance, adapted from rosetta code
|
|
def fuzzy_match(s1, s2):
|
|
if len(s1) == 0:
|
|
return len(s2)
|
|
if len(s2) == 0:
|
|
return len(s1)
|
|
edits = [i for i in range(len(s2) + 1)]
|
|
for i in range(len(s1)):
|
|
corner = i
|
|
edits[0] = i + 1
|
|
for j in range(len(s2)):
|
|
upper = edits[j + 1]
|
|
if s1[i] == s2[j]:
|
|
edits[j + 1] = corner
|
|
else:
|
|
m = min(corner, upper, edits[j])
|
|
edits[j + 1] = m + 1
|
|
corner = upper
|
|
return edits[-1]
|
|
|
|
|
|
def get_current_datetime() -> datetime.datetime:
|
|
# We place this in a separate function so that we can mock it out
|
|
# in our unit tests.
|
|
return datetime.datetime.now()
|
|
|
|
|
|
@dataclass
|
|
class UsernameValidationResult:
|
|
is_valid: bool
|
|
error_message: str = ''
|
|
|
|
|
|
def validate_username(username: str) -> UsernameValidationResult:
|
|
if not username:
|
|
return UsernameValidationResult(False, 'Username must not be empty')
|
|
if not VALID_USERNAME_RE.fullmatch(username):
|
|
return UsernameValidationResult(False, 'Username is invalid')
|
|
return UsernameValidationResult(True)
|
|
|
|
|
|
def is_in_development() -> bool:
|
|
"""This is a hack to determine if we're in the dev env or not"""
|
|
return socket.getfqdn().endswith('.csclub.internal')
|