Sergidev commited on
Commit
1bf3605
·
verified ·
1 Parent(s): 4f0e997

Delete helper.py

Browse files
Files changed (1) hide show
  1. helper.py +0 -248
helper.py DELETED
@@ -1,248 +0,0 @@
1
- import os
2
- import sqlite3
3
- import secrets
4
- import hashlib
5
- import time
6
- from argon2 import PasswordHasher
7
- from cryptography.fernet import Fernet
8
- from transformers import AutoTokenizer, AutoModel
9
- import torch
10
- import numpy as np
11
-
12
- # Initialize global variables
13
- TOKEN = os.getenv("HF_TOKEN")
14
- MODEL_NAME = os.getenv("SECRET_M")
15
- ADMIN_USERNAME = os.getenv("ADMIN_USERNAME")
16
- ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD")
17
-
18
- tokenizer = None
19
- model = None
20
-
21
- # Initialize Argon2 hasher and Fernet cipher
22
- ph = PasswordHasher()
23
- cipher_key = Fernet.generate_key()
24
- cipher = Fernet(cipher_key)
25
-
26
- # Database file path
27
- DB_FILE = 'grimvault.db'
28
-
29
- def get_db_connection():
30
- conn = sqlite3.connect(DB_FILE)
31
- conn.row_factory = sqlite3.Row
32
- return conn
33
-
34
- def create_tables():
35
- conn = get_db_connection()
36
- c = conn.cursor()
37
- c.execute('''CREATE TABLE IF NOT EXISTS users
38
- (username TEXT PRIMARY KEY, password_hash TEXT, embedding_hash TEXT,
39
- salt TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
40
- c.execute('''CREATE TABLE IF NOT EXISTS files
41
- (id INTEGER PRIMARY KEY, username TEXT, filename TEXT,
42
- content BLOB, size INTEGER, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
43
- conn.commit()
44
- conn.close()
45
-
46
- def get_embedding(text):
47
- global tokenizer, model
48
-
49
- if tokenizer is None or model is None:
50
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
51
- model = AutoModel.from_pretrained(MODEL_NAME, torch_dtype=torch.float16)
52
-
53
- if tokenizer.pad_token is None:
54
- tokenizer.pad_token = tokenizer.eos_token
55
-
56
- model.resize_token_embeddings(len(tokenizer))
57
-
58
- inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512)
59
- with torch.no_grad():
60
- outputs = model(**inputs)
61
- return outputs.last_hidden_state.mean(dim=1).squeeze().numpy()
62
-
63
- def hash_embedding(embedding, salt):
64
- salted_embedding = np.concatenate([embedding, np.frombuffer(salt, dtype=np.float32)])
65
- return hashlib.sha256(salted_embedding.tobytes()).hexdigest()
66
-
67
- def create_user(username, password):
68
- conn = get_db_connection()
69
- c = conn.cursor()
70
-
71
- # Check if username already exists
72
- c.execute("SELECT * FROM users WHERE username = ?", (username,))
73
- if c.fetchone():
74
- conn.close()
75
- return "Username already exists."
76
-
77
- # Generate salt and create password hash
78
- salt = secrets.token_bytes(16)
79
- password_hash = ph.hash(password + salt.hex())
80
-
81
- # Generate embedding and hash it
82
- embedding = get_embedding(password)
83
- embedding_hash = hash_embedding(embedding, salt)
84
-
85
- # Store user data
86
- c.execute("INSERT INTO users (username, password_hash, embedding_hash, salt) VALUES (?, ?, ?, ?)",
87
- (username, password_hash, embedding_hash, salt))
88
- conn.commit()
89
- conn.close()
90
-
91
- return "User created successfully."
92
-
93
- def verify_user(username, password):
94
- conn = get_db_connection()
95
- c = conn.cursor()
96
-
97
- c.execute("SELECT * FROM users WHERE username = ?", (username,))
98
- user = c.fetchone()
99
- conn.close()
100
-
101
- if not user:
102
- return False
103
-
104
- try:
105
- # Verify password
106
- ph.verify(user['password_hash'], password + user['salt'].hex())
107
-
108
- # Verify embedding
109
- embedding = get_embedding(password)
110
- embedding_hash = hash_embedding(embedding, user['salt'])
111
- if embedding_hash != user['embedding_hash']:
112
- return False
113
-
114
- return True
115
- except:
116
- return False
117
-
118
- def get_user_files(username):
119
- conn = get_db_connection()
120
- c = conn.cursor()
121
- c.execute("SELECT filename, size FROM files WHERE username = ?", (username,))
122
- files = c.fetchall()
123
- conn.close()
124
- return files
125
-
126
- def upload_file(username, filename, content):
127
- conn = get_db_connection()
128
- c = conn.cursor()
129
-
130
- # Check if file already exists
131
- c.execute("SELECT * FROM files WHERE username = ? AND filename = ?", (username, filename))
132
- if c.fetchone():
133
- conn.close()
134
- return f"File {filename} already exists."
135
-
136
- # Insert file data
137
- c.execute("INSERT INTO files (username, filename, content, size) VALUES (?, ?, ?, ?)",
138
- (username, filename, content, len(content)))
139
- conn.commit()
140
- conn.close()
141
-
142
- return f"File {filename} uploaded successfully."
143
-
144
- def download_file(username, filename):
145
- conn = get_db_connection()
146
- c = conn.cursor()
147
- c.execute("SELECT content FROM files WHERE username = ? AND filename = ?", (username, filename))
148
- file = c.fetchone()
149
- conn.close()
150
-
151
- if file:
152
- return file['content']
153
- else:
154
- return None
155
-
156
- def delete_file(username, filename):
157
- conn = get_db_connection()
158
- c = conn.cursor()
159
- c.execute("DELETE FROM files WHERE username = ? AND filename = ?", (username, filename))
160
- if c.rowcount == 0:
161
- conn.close()
162
- return f"File {filename} not found."
163
- conn.commit()
164
- conn.close()
165
- return f"File {filename} deleted successfully."
166
-
167
- def empty_vault(username):
168
- conn = get_db_connection()
169
- c = conn.cursor()
170
- c.execute("DELETE FROM files WHERE username = ?", (username,))
171
- conn.commit()
172
- conn.close()
173
- return "All files in your vault have been deleted."
174
-
175
- def is_admin(username):
176
- return username == ADMIN_USERNAME
177
-
178
- def get_all_accounts():
179
- conn = get_db_connection()
180
- c = conn.cursor()
181
- c.execute("SELECT username, created_at FROM users")
182
- accounts = c.fetchall()
183
- conn.close()
184
- return accounts
185
-
186
- def delete_account(username):
187
- if username == ADMIN_USERNAME:
188
- return "Cannot delete admin account."
189
-
190
- conn = get_db_connection()
191
- c = conn.cursor()
192
- c.execute("DELETE FROM users WHERE username = ?", (username,))
193
- c.execute("DELETE FROM files WHERE username = ?", (username,))
194
- conn.commit()
195
- conn.close()
196
- return f"Account {username} and all associated files have been deleted."
197
-
198
- def encrypt_file(filename, content):
199
- return cipher.encrypt(content)
200
-
201
- def decrypt_file(filename, encrypted_content):
202
- return cipher.decrypt(encrypted_content)
203
-
204
- # Rate limiting
205
- RATE_LIMIT = 5 # maximum number of requests per minute
206
- rate_limit_dict = {}
207
-
208
- def is_rate_limited(username):
209
- current_time = time.time()
210
- if username in rate_limit_dict:
211
- last_request_time, count = rate_limit_dict[username]
212
- if current_time - last_request_time < 60: # within 1 minute
213
- if count >= RATE_LIMIT:
214
- return True
215
- rate_limit_dict[username] = (last_request_time, count + 1)
216
- else:
217
- rate_limit_dict[username] = (current_time, 1)
218
- else:
219
- rate_limit_dict[username] = (current_time, 1)
220
- return False
221
-
222
- # Account lockout
223
- MAX_LOGIN_ATTEMPTS = 5
224
- LOCKOUT_TIME = 300 # 5 minutes
225
- lockout_dict = {}
226
-
227
- def is_account_locked(username):
228
- if username in lockout_dict:
229
- attempts, lockout_time = lockout_dict[username]
230
- if attempts >= MAX_LOGIN_ATTEMPTS:
231
- if time.time() - lockout_time < LOCKOUT_TIME:
232
- return True
233
- else:
234
- del lockout_dict[username]
235
- return False
236
-
237
- def record_login_attempt(username, success):
238
- if username not in lockout_dict:
239
- lockout_dict[username] = [0, 0]
240
-
241
- if success:
242
- del lockout_dict[username]
243
- else:
244
- lockout_dict[username][0] += 1
245
- lockout_dict[username][1] = time.time()
246
-
247
- # Initialize database
248
- create_tables()