2023-10-20 07:45:46 +00:00
|
|
|
import hashlib
|
|
|
|
|
|
|
|
class ParameterValidator:
|
|
|
|
def __init__(self, given_hash_or_params, params_hash_key=None):
|
2024-03-20 03:32:44 +00:00
|
|
|
from django.conf import settings
|
2023-10-20 07:45:46 +00:00
|
|
|
if params_hash_key is None:
|
|
|
|
self.given_hash = given_hash_or_params
|
|
|
|
else:
|
|
|
|
self.given_hash = given_hash_or_params.get(params_hash_key)
|
2023-10-26 02:09:50 +00:00
|
|
|
seed = settings.SECRET_KEY.encode('utf-8')
|
2023-10-20 07:45:46 +00:00
|
|
|
self.hasher = hashlib.sha256(seed)
|
|
|
|
if isinstance(self.given_hash, str):
|
|
|
|
self.hash_type = type(self.given_hash)
|
|
|
|
else:
|
|
|
|
self.hash_type = type(self.hasher.hexdigest())
|
|
|
|
self.valid = None
|
|
|
|
if not (self.given_hash and seed):
|
|
|
|
self.fail()
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
self.valid = self.valid and None
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_value, exc_tb):
|
|
|
|
if exc_type is None:
|
|
|
|
self.check()
|
|
|
|
else:
|
|
|
|
self.fail()
|
|
|
|
|
|
|
|
def validate(self, data):
|
|
|
|
self.valid = self.valid and None
|
|
|
|
self.hasher.update(data)
|
|
|
|
|
|
|
|
def check(self):
|
|
|
|
if self.valid or (self.valid is None):
|
|
|
|
self.valid = self.hash_type(self.hasher.hexdigest()) == self.given_hash
|
|
|
|
return self.valid
|
|
|
|
|
|
|
|
def fail(self):
|
|
|
|
self.valid = False
|