-
Notifications
You must be signed in to change notification settings - Fork 3
/
access_manager.py
98 lines (79 loc) · 2.43 KB
/
access_manager.py
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import time
import os
from datetime import datetime, timedelta
from constants import EXPIRY_TIME_MINUTES, DOWNLOADS_DIRECTORY
allowed_tokens = {}
audio_files = {}
def add_token(token, file):
"""
Adds token with expiration date to allowed_tokens and token with file name to audio_files
:param token: generated access token
:param file: audio file name
:return:
"""
expiry_date = datetime.now() + timedelta(minutes=EXPIRY_TIME_MINUTES)
allowed_tokens[token] = expiry_date
audio_files[token] = file
def has_access(token):
"""
Checks if token exists in allowed_tokens
:param token: access token
:return: True if is present in allowed_tokens, False otherwise
"""
return token in allowed_tokens
def is_valid(token):
"""
Checks if token has not expired
:param token: access token
:return: True if token expired, False otherwise
"""
return allowed_tokens[token] >= datetime.now()
def file_assigned(token):
"""
Checks if file is associated with a token
:param token: access token
:return: True if file is assigned, False otherwise
"""
return token in audio_files
def get_audio_file(token):
"""
Returns audio file name
:param token: access token
:return: audio file name
"""
return audio_files[token]
def remove_expired_tokens():
"""
Adds expired token to expired_tokens list, then removes them.
Pops file names to list, which are suppose to be deleted
:return: list of file names to be deleted
"""
expired_tokens = []
files_to_delete = []
for token in allowed_tokens:
if not is_valid(token):
expired_tokens.append(token)
files_to_delete.append(audio_files.pop(token))
for expired in expired_tokens:
del allowed_tokens[expired]
return files_to_delete
def delete_expired_files(files):
"""
Removes files which were previously associated with expired tokens
:param files: file names to be deleted
:return:
"""
for file in files:
try:
os.remove(DOWNLOADS_DIRECTORY + file)
except FileNotFoundError:
print('Error occurred while deleting a file')
def manage_tokens():
"""
Checks if there are any expired tokens. If so, removes them and deletes a associated files
:return:
"""
while True:
files = remove_expired_tokens()
delete_expired_files(files)
time.sleep(1)