summaryrefslogtreecommitdiff
path: root/tfa.py
blob: 2cd37f4c92ba77464a896a94d68ff00c9b668767 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import time
from typing import Dict, List
import random
import string

class customstore:
  def __init__(self, ttl=300, maxsize=200):
    self.store: Dict[str, List] = {}  # key -> [expiry_time, verified_status]
    self.ttl = ttl
    #self.maxsize = maxsize, now dont need this

  def create(self):
    self.clean()
    keylength = 4
    key_added = False
    while not key_added:
      current_time = int(time.time())
      key = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(keylength))
      if key not in self.store:
        self.store[key] = [current_time + self.ttl, False]
        key_added = True
    return key

  def authenticate(self, key):
    current_time = int(time.time())
    if key in self.store and current_time <= self.store[key][0]:
      self.store[key][1] = True
      return True
    else:
      return False

  def check(self, key):
    current_time = int(time.time())
    if key in self.store and current_time <= self.store[key][0] and self.store[key][1] == True:
        return True
    else:
        return False

  def clean(self):
    current_time = int(time.time())
    expired_keys = [k for k, [expiry_time, _] in self.store.items() if current_time > expiry_time]
    for key in expired_keys:
      self.store.pop(key, None)
    return

if __name__ == "__main__":
  s1 = customstore(ttl=7)

  # Create and verify first key
  k = s1.create()
  print("Store state:", s1.store)
  print("Created key:", k)
  print("First verification:", "yeppy" if s1.authenticate(k) else "nopey")
  print("Second verification:", "yeppy" if s1.check(k) else "nopey")  
  # Wait and try again
  time.sleep(5)
  k2 = s1.create()
  print("\nStore state after 5 seconds:", s1.store)
  print("First key:", k)
  print("First key verification:", "yeppy" if s1.check(k) else "nopey")  

  # Wait and try again
  time.sleep(5)
  print("\nStore state after 5 seconds:", s1.store)
  print("First key:", k)
  print("First key verification:", "yeppy" if s1.check(k) else "nopey") 
  k = s1.create()
  print("Store state:", s1.store)
  print("Created key:", k)
  print("First verification:", "yeppy" if s1.authenticate(k) else "nopey")
  print("Second verification:", "yeppy" if s1.check(k) else "nopey")