validation.py 886 Bytes
import json, random

class Validation:
  
  FILE = "tokens.json"
  LENGTH = 128
  STRING = "\
1234567890\
qwertyuiopasdfghjklzxcvbnm\
QWERTYUIOPASDFGHJKLZXCVBNM\
"

  def __init__(self):
    with open(self.FILE, "+r") as f:
      self.data = f.read()
    try:
      self.data = set(json.loads(self.data))
    except (ValueError, json.decoder.JSONDecodeError):
      print ("malformed or empty JSON file, defaulting to empty dictionary...")
      self.data = set()


  def make_token(self):
    s = ""
    i = 0
    
    while i < self.LENGTH:
      s += self.STRING[random.randrange(0,len(self.STRING))]
      i += 1
    
    self.data.add(s)
    
    return s

  def check_token(self,token):
    return token in self.data

  def remove_token(self,token)
    self.data.discard(token)

  def __del__(self):
    with open(self.FILE, "+w") as f:
      f.write(json.dumps(list(self.data)))