-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwindow_main.py
More file actions
585 lines (528 loc) · 22.8 KB
/
window_main.py
File metadata and controls
585 lines (528 loc) · 22.8 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
import urllib.request
from password_strength import PasswordStats
from pwnedpasswords import check as check_pwned
from pyperclip import copy as copy_to_cb
from pysqlcipher3 import dbapi2 as sqlcipher
from secrets import choice as secrets_choice
from string import ascii_uppercase, ascii_lowercase, digits
from sys import exit as sys_exit
from validators import url as is_url_valid
from PySide6.QtCore import Qt, QSortFilterProxyModel
from PySide6.QtWidgets import (
QMainWindow,
QMessageBox,
QLineEdit,
QTableWidgetItem,
)
from PySide6.QtGui import QStandardItemModel, QStandardItem, QIcon
from ui_main_window import Ui_MainWindow
class MainWindow(QMainWindow):
def __init__(self, db):
super(MainWindow, self).__init__()
self.db = db
if not self.is_access_granted():
QMessageBox.critical(
self,
"Password Manager",
"Access denied.",
)
sys_exit()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.setFixedWidth(800)
self.setFixedHeight(600)
# ----- Message Boxes -----
self.dlg_no_row_selected = lambda: QMessageBox.warning(
self,
"Password Manager",
"No password selected.",
)
self.dlg_delete_confirmation = lambda: QMessageBox.question(
self,
"Password Manager",
"Are you sure you want to delete this password?",
buttons=QMessageBox.Yes | QMessageBox.No,
)
self.dlg_log_out_confirm = lambda: QMessageBox.question(
self,
"Password Manager",
"Are you sure you want to log out?",
buttons=QMessageBox.Yes | QMessageBox.Cancel,
)
# -------------------------
self.filter_proxy_model = QSortFilterProxyModel()
self.filter_proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
self.filter_proxy_model.setFilterKeyColumn(0)
self.ui.tablePasswords.setModel(self.filter_proxy_model)
self.ui.editSearch.textChanged.connect(
self.filter_proxy_model.setFilterRegularExpression
)
# ----- Side-Menu -----
self.ui.stackedWidget.setCurrentWidget(self.ui.widgetPasswords)
self.ui.buttonTabPasswords.setStyleSheet(
"background-color: #3d3d3d; border-left: 3px solid #8ab4f7"
)
self.ui.buttonTabPasswords.clicked.connect(self.show_passwords_tab)
self.update_dashboard_table()
self.ui.buttonTabAddNew.clicked.connect(self.show_add_new_tab)
self.ui.buttonTabGenerate.clicked.connect(self.show_generate_tab)
self.ui.buttonTabHealth.clicked.connect(self.show_health_tab)
self.ui.buttonLogOut.clicked.connect(self.log_out)
# ----- Password Dashboard ----------------
self.ui.buttonDelete.clicked.connect(self.delete_password)
self.ui.buttonCopyPassword.clicked.connect(self.copy_password)
# ----- Add New -----
self.ui.buttonTabPasswords.clicked.connect(self.update_dashboard_table)
self.ui.buttonAddPassword.clicked.connect(self.update_db)
self.ui.editEntryUrl.returnPressed.connect(self.update_db)
self.ui.editEntryUsername.returnPressed.connect(self.update_db)
self.ui.editEntryPassword.returnPressed.connect(self.update_db)
self.ui.editEntryPasswordConfirm.returnPressed.connect(self.update_db)
self.ui.buttonPasswordToggle.clicked.connect(self.password_toggle)
self.ui.buttonPasswordToggle2.clicked.connect(
self.password_confirm_toggle
)
self.ui.comboBoxEntryTitle.currentTextChanged.connect(self.set_url)
self.ui.comboBoxEntryTitle.currentIndexChanged.connect(self.set_url)
# ----- Generate Password -----
self.ui.horizontalSlider.valueChanged.connect(self.update_spin_box)
self.ui.spinBox.valueChanged.connect(self.update_slider)
self.ui.horizontalSlider.valueChanged.connect(self.generate_password)
self.ui.spinBox.valueChanged.connect(self.generate_password)
self.ui.checkBoxUpper.clicked.connect(self.generate_password)
self.ui.checkBoxLower.clicked.connect(self.generate_password)
self.ui.checkBoxDigits.clicked.connect(self.generate_password)
self.ui.checkBoxSymbols.clicked.connect(self.generate_password)
self.ui.buttonRegenerate.clicked.connect(self.generate_password)
self.ui.buttonCopyRandomPassword.clicked.connect(
self.copy_generated_pwd
)
self.ui.checkBoxUpper.clicked.connect(self.disable_check_box)
self.ui.checkBoxLower.clicked.connect(self.disable_check_box)
self.ui.checkBoxDigits.clicked.connect(self.disable_check_box)
self.ui.checkBoxSymbols.clicked.connect(self.disable_check_box)
self.generate_password()
# ----- Password Health -----
self.ui.buttonTabHealth.clicked.connect(self.update_health_stats)
self.ui.buttonTabHealth.clicked.connect(self.update_compromised_table)
self.ui.buttonTabHealth.clicked.connect(self.update_reused_table)
self.ui.buttonTabHealth.clicked.connect(self.update_weak_table)
self.ui.buttonTabHealth.clicked.connect(self.update_safe_table)
# ----- Side-Menu -----
def show_passwords_tab(self):
"""Highlights the 'Passwords' tab."""
self.ui.buttonTabPasswords.setStyleSheet(
"background-color: #3d3d3d; border-left: 4px solid #8ab4f7"
)
self.ui.buttonTabAddNew.setStyleSheet("")
self.ui.buttonTabGenerate.setStyleSheet("")
self.ui.buttonTabHealth.setStyleSheet("")
self.ui.stackedWidget.setCurrentWidget(self.ui.widgetPasswords)
def show_add_new_tab(self):
"""Highlights the 'Add New' tab."""
self.ui.buttonTabAddNew.setStyleSheet(
"background-color: #3d3d3d; border-left: 4px solid #8ab4f7"
)
self.ui.buttonTabPasswords.setStyleSheet("")
self.ui.buttonTabGenerate.setStyleSheet("")
self.ui.buttonTabHealth.setStyleSheet("")
self.ui.stackedWidget.setCurrentWidget(self.ui.widgetAdd)
def show_generate_tab(self):
"""Highlights the 'Generate Passwords' tab."""
self.ui.buttonTabGenerate.setStyleSheet(
"background-color: #3d3d3d; border-left: 4px solid #8ab4f7"
)
self.ui.buttonTabPasswords.setStyleSheet("")
self.ui.buttonTabAddNew.setStyleSheet("")
self.ui.buttonTabHealth.setStyleSheet("")
self.ui.stackedWidget.setCurrentWidget(self.ui.widgetGenerate)
def show_health_tab(self):
"""Highlights the 'Health Check' tab."""
self.ui.buttonTabHealth.setStyleSheet(
"background-color: #3d3d3d; border-left: 4px solid #8ab4f7"
)
self.ui.buttonTabPasswords.setStyleSheet("")
self.ui.buttonTabAddNew.setStyleSheet("")
self.ui.buttonTabGenerate.setStyleSheet("")
self.ui.stackedWidget.setCurrentWidget(self.ui.widgetHealth)
# ----- Passwords Dashboard -----
def update_dashboard_table(self):
"""Inserts the data from the database into the dashboard's passwords table."""
data = self.db.execute(
"SELECT name, url, username, password FROM Password"
).fetchall()
model = QStandardItemModel(len(data), 3)
model.setHorizontalHeaderLabels(
["Name", "URL", "Username", "Password"]
)
for row_index, row in enumerate(data):
for col_index, col_data in enumerate(row):
if col_index == 3:
col_data = "*" * len(col_data)
model.setItem(row_index, col_index, QStandardItem(col_data))
self.filter_proxy_model.setSourceModel(model)
self.ui.tablePasswords.setColumnWidth(1, 150)
self.ui.tablePasswords.setColumnWidth(3, 152)
def delete_password(self):
"""Removes the selected row from the database."""
try:
selected_name = self.ui.tablePasswords.selectedIndexes()[0].data()
with self.db:
if self.dlg_delete_confirmation() == QMessageBox.Yes:
self.db.execute(
f"DELETE FROM Password WHERE name='{selected_name}'"
)
self.update_dashboard_table()
except IndexError:
self.dlg_no_row_selected()
def edit_password(self):
pass
def copy_password(self):
"""Inserts the password of the row selected into the clipboard."""
try:
selected_row_name = self.ui.tablePasswords.selectedIndexes()[
0
].data()
with self.db:
copy_to_cb(
self.db.execute(
f"SELECT password FROM Password WHERE name='{selected_row_name}'"
).fetchall()[0][0]
)
except IndexError:
self.dlg_no_row_selected()
# ----- Add New -----
def update_db(self):
"""
Inserts the data from the 'Add New' form along with password
statistics into the database.
"""
try:
form_data = [
self.ui.comboBoxEntryTitle.currentText().replace(" ", ""),
self.ui.editEntryUrl.text().lower().replace(" ", ""),
self.ui.editEntryUsername.text(),
self.ui.editEntryPassword.text(),
self.ui.editEntryPasswordConfirm.text(),
self.is_password_compromised(self.ui.editEntryPassword.text()),
self.get_password_strength(self.ui.editEntryPassword.text()),
]
if not (form_data[3] == form_data[4]):
QMessageBox.warning(
self,
"Password Manager",
"Password confirmation does not match or is empty.",
)
elif not ( # Check if each box is full in form.
sum(1 if i != "" else 0 for i in form_data) == len(form_data)
):
QMessageBox.warning(
self,
"Password Manager",
"All fields are required.",
)
elif not is_url_valid(form_data[1]): # Check if url is valid.
QMessageBox.critical(
self,
"Password Manager",
"Error: URL is invalid.",
)
elif ( # Check if name in entry is found in database.
not self.is_name_unique(form_data[0])
):
QMessageBox.warning(
self,
"Password Manager",
f"Error: A password for {form_data[0]} already exists.",
)
else:
with self.db:
self.db.execute(
"""
INSERT INTO
Password (name, url, username, password, isCompromised, passwordStrength)
VALUES
(:name, :url, :username, :password, :isCompromised, :passwordStrength)
""",
{
"name": form_data[0],
"url": form_data[1],
"username": form_data[2],
"password": form_data[3],
"isCompromised": form_data[5],
"passwordStrength": form_data[6],
},
)
QMessageBox.information(
self,
"Password Manager",
"Password has been added successfully.",
)
self.clear_password_form()
except urllib.error.URLError:
QMessageBox.critical(
self, "Password Manager", "Couldn't connect to the network."
)
def password_toggle(self, checked):
self.ui.editEntryPassword.setEchoMode(
QLineEdit.EchoMode.Normal
if checked
else QLineEdit.EchoMode.Password
)
self.ui.buttonPasswordToggle.setIcon(
QIcon("icons/eye.svg")
if checked
else QIcon("icons/eye-crossed.svg")
)
def password_confirm_toggle(self, checked):
self.ui.editEntryPasswordConfirm.setEchoMode(
QLineEdit.EchoMode.Normal
if checked
else QLineEdit.EchoMode.Password
)
self.ui.buttonPasswordToggle2.setIcon(
QIcon("icons/eye.svg")
if checked
else QIcon("icons/eye-crossed.svg")
)
def is_password_compromised(self, password):
return (
1 if check_pwned(password, plain_text=True, anonymous=True) else 0
)
# ----- Generate Password -----
def update_spin_box(self):
self.ui.spinBox.setValue(self.ui.horizontalSlider.value())
def update_slider(self):
self.ui.horizontalSlider.setValue(self.ui.spinBox.value())
def generate_password(self):
len = self.ui.spinBox.value()
characters = ""
if self.ui.checkBoxUpper.isChecked():
characters += ascii_uppercase
if self.ui.checkBoxLower.isChecked():
characters += ascii_lowercase
if self.ui.checkBoxDigits.isChecked():
characters += digits
if self.ui.checkBoxSymbols.isChecked():
characters += "@%$!&?#"
random_pwd = "".join(secrets_choice(characters) for i in range(len))
self.ui.labelGeneratedPwd.setText(random_pwd)
def copy_generated_pwd(self):
copy_to_cb(self.ui.labelGeneratedPwd.text())
def disable_check_box(self):
"""
Disables the check box that is checked when only one of the boxes are
checked.
"""
check_boxes_list = [
self.ui.checkBoxUpper,
self.ui.checkBoxLower,
self.ui.checkBoxDigits,
self.ui.checkBoxSymbols,
]
boxes_checked = [
check_box.isChecked()
for check_box_num, check_box in enumerate(check_boxes_list)
]
if sum(boxes_checked) == 1:
check_box_checked = boxes_checked.index(True)
check_boxes_list[check_box_checked].setEnabled(False)
else:
for check_box in check_boxes_list:
check_box.setEnabled(True)
def get_db_data(self):
"""Returns a list of the database's data."""
with self.db:
return self.db.execute("SELECT * FROM Password").fetchall()
def is_access_granted(self):
with self.db:
try:
self.db.execute("SELECT count(*) FROM sqlite_master;")
return True
except self.db.DatabaseError:
return False
def update_health_stats(self):
with self.db:
data = self.db.execute(
"""
SELECT name, password, isCompromised, passwordStrength
FROM Password
"""
).fetchall()
if data:
security_score = int(
sum(list(zip(*data))[3]) * 100 / len(data)
)
self.ui.labelSecurityScore.setText(f"{str(security_score)}%")
reused_list = self.db.execute(
"""
SELECT password, COUNT(*) AS "Count"
FROM Password
GROUP BY password
HAVING COUNT(*) > 1
"""
).fetchall()
if reused_list:
total_reused = sum(list(zip(*reused_list))[1])
self.ui.labelReused.setText(str(total_reused))
total_passwords = len(data)
self.ui.labelTotalPasswords.setText(str(total_passwords))
total_compromised = len(
[i for i in list(zip(*data))[2] if i == 1]
)
self.ui.labelCompromised.setText(str(total_compromised))
total_weak = len([i for i in list(zip(*data))[3] if i < 0.66])
self.ui.labelWeak.setText(str(total_weak))
total_safe = len([i for i in list(zip(*data))[3] if i >= 0.66])
self.ui.labelSafe.setText(str(total_safe))
def update_compromised_table(self):
"""Inserts the compromised accounts into the compromised table."""
compromised_list = self.db.execute(
"""
SELECT name, url, password
FROM Password
WHERE isCompromised=1
"""
).fetchall()
self.ui.tableCompromised.setRowCount(len(compromised_list))
for row_index, row in enumerate(compromised_list):
for col_index, col_data in enumerate(row):
if col_index == 2:
col_data = "*" * len(col_data)
self.ui.tableCompromised.setItem(
row_index, col_index, QTableWidgetItem(col_data)
)
self.ui.tableCompromised.setColumnWidth(1, 180)
self.ui.tableCompromised.setColumnWidth(2, 181)
self.ui.tableCompromised.setColumnWidth(3, 181)
def update_reused_table(self):
"""Inserts the accounts with reused passwords into the reused table."""
reused_list = self.db.execute(
"""
SELECT
y.id, y.name, y.url, y.password
FROM Password y
INNER JOIN (
SELECT name, url, password, COUNT(*) AS CountOf
FROM Password
GROUP BY password
HAVING COUNT(*) > 1
)
dt ON y.password=dt.password
"""
).fetchall()
self.ui.tableReused.setRowCount(len(reused_list))
for row_index, row in enumerate(reused_list):
for col_index, col_data in enumerate(row):
if col_index > 0:
if col_index == 3:
col_data = "*" * len(col_data)
self.ui.tableReused.setItem(
row_index, col_index - 1, QTableWidgetItem(col_data)
)
self.ui.tableReused.setColumnWidth(1, 180)
self.ui.tableReused.setColumnWidth(2, 181)
self.ui.tableReused.setColumnWidth(3, 181)
def update_weak_table(self):
"""Inserts the accounts with weak passwords into the weak table."""
weak_list = self.db.execute(
"""
SELECT name, url, password
FROM Password
WHERE passwordStrength < 0.66
"""
).fetchall()
self.ui.tableWeak.setRowCount(len(weak_list))
for row_index, row in enumerate(weak_list):
for col_index, col_data in enumerate(row):
if col_index == 2:
col_data = "*" * len(col_data)
self.ui.tableWeak.setItem(
row_index, col_index, QTableWidgetItem(col_data)
)
self.ui.tableWeak.setColumnWidth(1, 180)
self.ui.tableWeak.setColumnWidth(2, 181)
self.ui.tableWeak.setColumnWidth(3, 181)
def update_safe_table(self):
"""Inserts the accounts with safe passwords into the safe table."""
safe_list = self.db.execute(
"""
SELECT name, url, password
FROM Password
WHERE passwordStrength >= 0.66
"""
).fetchall()
self.ui.tableSafe.setRowCount(len(safe_list))
for row_index, row in enumerate(safe_list):
for col_index, col_data in enumerate(row):
if col_index == 2:
col_data = "*" * len(col_data)
self.ui.tableSafe.setItem(
row_index, col_index, QTableWidgetItem(col_data)
)
self.ui.tableSafe.setColumnWidth(1, 180)
self.ui.tableSafe.setColumnWidth(2, 181)
self.ui.tableSafe.setColumnWidth(3, 181)
def set_url(self):
url_list = [
"",
"https://www.alibaba.com",
"https://www.aliexpress.com",
"https://www.amazon.com",
"https://www.bing.com",
"https://www.cash.app",
"https://www.discord.com",
"https://www.ebay.com",
"https://www.facebook.com",
"https://www.flipkart.com",
"https://www.foodpanda.com",
"https://www.google.com",
"https://www.instagram.com",
"https://www.linkedin.com",
"https://www.mcdonalds.com",
"https://www.netflix.com",
"https://www.reddit.com",
"https://www.shopee.com",
"https://www.snapchat.com",
"https://www.spotify.com",
"https://www.starbucks.com",
"https://www.telegram.com",
"https://www.tiktok.com",
"https://www.twitch.com",
"https://www.twitter.com",
"https://www.uber.com",
"https://www.wechat.com",
"https://www.whatsapp.com",
"https://www.wish.com",
"https://www.wolt.com",
"https://www.yahoo.com",
"https://www.zoom.com",
]
try:
title_selected = self.ui.comboBoxEntryTitle.currentIndex()
self.ui.editEntryUrl.setText(url_list[title_selected])
except IndexError:
self.ui.editEntryUrl.setText("")
def clear_password_form(self):
self.ui.comboBoxEntryTitle.setCurrentIndex(0)
self.ui.editEntryUsername.clear()
self.ui.editEntryUrl.clear()
self.ui.editEntryPassword.clear()
self.ui.editEntryPasswordConfirm.clear()
def log_out(self):
if self.dlg_log_out_confirm() == QMessageBox.Yes:
sys_exit()
def get_password_strength(self, password):
if len(password) > 0:
return PasswordStats(password).strength()
def is_name_unique(self, name):
with self.db:
try:
return not name in [
i[0]
for i in self.db.execute(
"SELECT name FROM Password"
).fetchall()
]
except sqlcipher.DatabaseError:
return True