-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
2433 lines (2200 loc) · 101 KB
/
main.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
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import datetime
import prettytable
import msvcrt
import os
from dotenv import set_key, get_key, find_dotenv
import pymongo
import maskpass
from colorama import Fore, Style, Back, init
import random
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from keycloak import KeycloakOpenID, KeycloakAdmin
import atexit
import yaml
import sqlite3
from cryptography.fernet import Fernet
import logging
import cv2
from pyzbar.pyzbar import decode, ZBarSymbol
import numpy as np
import pyotp
import qrcode
from inputimeout import inputimeout
import string
import keyboard
# Mongo variables
global isJson
global client
global db
global activeCollection
global historyCollection
global mongoUsersCollection
global booksListCollection
global passwordsDBconnection
global passwordsDBcursor
global profileUsername
global profilePassword
global viewerRole
global librarianRole
global token
global keycloak_openid
global cipher
global adminPassword
global totp
global yamlFile
with open('config.yml', 'r') as f:
yamlFile = yaml.safe_load(f)
# Read YAML config
# Local json files
activeHiresFile = yamlFile['active_hires_file_name']
historyFile = yamlFile['history_file_name']
dateFormat = yamlFile['date_format']
# Emails config
senderEmail = yamlFile['sender_email']
receiveEmail = yamlFile['admins_emails']
senderPassword = yamlFile['sender_password']
# Keycloak role names
viewerRole = yamlFile['viewer_role_name']
librarianRole = yamlFile['librarian_role_name']
adminRole = yamlFile['admin_role_name']
# Keycloak server URL and realm
keycloakServerUrl = yamlFile['keycloak']['server_url']
keycloakRealm = yamlFile['keycloak']['realm_name']
# Make connection to passwords DB
passwordsDBconnection = sqlite3.connect('db.db')
passwordsDBcursor = passwordsDBconnection.cursor()
# Get decrypt key
with open('fernet_key.txt', 'rb') as keyFile:
fernetKey = keyFile.read()
# Check if decrypt key is empty
if fernetKey == b'':
# If yes reset DB to default values
# admin password = admin
# mongo credentials = Null (empty place)
key = Fernet.generate_key()
with open('fernet_key.txt', 'wb') as keyFile:
keyFile.write(key)
cipher = Fernet(key)
data = b'None'
encryptedata = cipher.encrypt(data)
passwordsDBcursor.execute("UPDATE pwds SET username = ?, password=? WHERE type = 'mongo'",
(encryptedata, encryptedata,))
passwordsDBconnection.commit()
else:
# If no create decrypt object
cipher = Fernet(fernetKey)
logging.basicConfig(format="[%(asctime)s %(levelname)s]: %(message)s", datefmt="%d.%m.%Y %H:%M:%S", filename='log.log', filemode='a', level=logging.INFO)
init()
class AdminTools:
def __init__(self, senderEmail: str, receiveEmail: list, password: str):
self.senderEmail = senderEmail
self.receiveEmail = receiveEmail
self.password = password
def QRcodeEmailSend(self, qrCodeImg) -> bool:
confirmCode = str(random.randint(100000, 999999))
# Tworzenie wiadomości
message = MIMEMultipart()
message['From'] = self.senderEmail
message['To'] = ', '.join(self.receiveEmail)
message['Subject'] = 'Librarian new QR code'
body = f"""
<html>
<body>
<h1>Your new QR code for your Authentication App</h1>
</body>
</html>"""
message.attach(MIMEText(body, 'html'))
message.attach(qrCodeImg)
# Utworzenie sesji SMTP
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(self.senderEmail, self.password)
# Wysłanie wiadomości
text = message.as_string()
server.sendmail(self.senderEmail, self.receiveEmail, text)
server.quit()
global keycloakAdmin
keycloakAdmin = KeycloakAdmin(server_url=keycloakServerUrl,
username=yamlFile['keycloak']['admin']['username'],
password=yamlFile['keycloak']['admin']['password'],
realm_name=keycloakRealm,
verify=True
)
def genereteTOTP(self):
global totp
characters = string.ascii_letters
key = ""
for i in range(16):
key += random.choice(characters)
totp = pyotp.TOTP(key)
set_key(find_dotenv(), "FIRST_LAUNCH", "False")
passwordsDBcursor.execute("UPDATE pwds SET password=? WHERE type='totp'", (key,))
passwordsDBconnection.commit()
uri = pyotp.totp.TOTP(key).provisioning_uri(name=yamlFile["totp_user_name"],
issuer_name=yamlFile["totp_app_name"])
qr = qrcode.make(uri).save("auth-qr.png")
try:
with open("auth-qr.png", "rb") as attachment:
img = MIMEImage(attachment.read())
img.add_header("Content-Disposition", "attachment", filename="kod_qr.png")
self.QRcodeEmailSend(img)
finally:
os.system("del auth-qr.png")
logging.info("Reseted TOTP key")
def checkRole(self, roleName: str, username: str) -> bool:
# Pobranie ID użytkownika na podstawie jego nazwy użytkownika
user_id = keycloakAdmin.get_user_id(username)
# Pobranie ról na poziomie królestwa dla użytkownika
realm_roles = keycloakAdmin.get_realm_roles_of_user(user_id=user_id)
# Sprawdzenie, czy użytkownik posiada rolę "librarian" na poziomie królestwa
if any(role['name'] == roleName for role in realm_roles):
return True
else:
return False
def addProfile(self):
print()
print(f'{Fore.LIGHTWHITE_EX}Adding user{Style.RESET_ALL}')
username = input('Enter username: ')
password = maskpass.askpass(prompt='Enter password: ', mask='*')
email = input('Enter email: ')
firstName = input('Enter first name: ')
lastName = input('Enter last name: ')
while True:
print(f'{Fore.LIGHTWHITE_EX}Roles{Style.RESET_ALL}\n'
'[1] - Viewer\n'
'[2] - Librarian\n'
'[3] - admin')
roles = int(input('Select from list above: '))
if roles in range(0, 4):
break
else:
print(f'{Fore.RED}Nie ma takiej opcji.{Style.RESET_ALL}')
print()
isEmailVerified = True
if email != '':
#Weryfikacja email-a
verifyCode = str(random.randint(100000, 999999))
# Tworzenie wiadomości
message = MIMEMultipart()
message['From'] = self.senderEmail
message['To'] = ', '.join(self.receiveEmail)
message['Subject'] = 'Librarian admin'
body = f"""<h1>There is your confirmation code for librarian</h1><font size:"16">Here is your confirmation code: <b>{verifyCode}</b></font>"""
message.attach(MIMEText(body, 'html'))
# Utworzenie sesji SMTP
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(self.senderEmail, self.password)
# Wysłanie wiadomości
text = message.as_string()
server.sendmail(self.senderEmail, self.receiveEmail, text)
server.quit()
i = 3
while i > 0:
verifyCodeInput = input('Enter email verify code: ')
if verifyCode == verifyCodeInput:
isEmailVerified = True
break
else:
if i > 0:
i = i - 1
print(f'{Fore.RED}Wrong verify code. Remaining trials: {i}{Style.RESET_ALL}')
print()
else:
print(f'{Fore.RED}Wrong verify code. Adding user canceled{Style.RESET_ALL}')
isEmailVerified = False
if isEmailVerified == False:
print(f"{Fore.RED}Adding user canceled{Style.RESET_ALL}")
return
#creating user
user = {"username": username,
"email": email,
"enabled": True,
"firstName": firstName,
"lastName": lastName,
"emailVerified": isEmailVerified}
keycloakAdmin.create_user(user)
#Adding password
user_id = keycloakAdmin.get_user_id(username)
keycloakAdmin.set_user_password(user_id, password, temporary=False)
global viewerRole
global librarianRole
global adminRole
if roles == 1:
keycloakAdmin.assign_realm_roles(user_id=user_id, roles=[{'id': '52edcaf1-5c34-42dc-8cd0-168637c79da4', 'name': 'viewer', 'description': '', 'composite': False, 'clientRole': False, 'containerId': 'librarian-keycloak'}])
elif roles == 2:
keycloakAdmin.assign_realm_roles(user_id=user_id, roles=[{'id': '093d1d40-60ef-4af4-8970-f2e0f4cfc053', 'name': 'librarian', 'description': '', 'composite': False, 'clientRole': False, 'containerId': 'librarian-keycloak'},
{'id': '52edcaf1-5c34-42dc-8cd0-168637c79da4', 'name': 'viewer', 'description': '', 'composite': False, 'clientRole': False, 'containerId': 'librarian-keycloak'}])
elif roles == 3:
keycloakAdmin.assign_realm_roles(user_id=user_id, roles=[{'id': '093d1d40-60ef-4af4-8970-f2e0f4cfc053', 'name': 'librarian', 'description': '', 'composite': False, 'clientRole': False, 'containerId': 'librarian-keycloak'},
{'id': '8bfa8729-d769-4363-9243-6fee6d8f6282', 'name': 'admin', 'description': '', 'composite': False, 'clientRole': False, 'containerId': 'librarian-keycloak'},
{'id': '52edcaf1-5c34-42dc-8cd0-168637c79da4', 'name': 'viewer', 'description': '', 'composite': False, 'clientRole': False, 'containerId': 'librarian-keycloak'}])
logging.info(f"Created profile: {username}")
print(f'{Fore.LIGHTGREEN_EX}Added profile{Style.RESET_ALL}')
def deleteProfile(self):
usersList = prettytable.PrettyTable(["Username"])
usersIDs = []
users = keycloakAdmin.get_users()
for user in users:
usersList.add_row([user["username"]])
usersIDs.append(user)
usersList.add_autoindex("ID")
usersList.title = "Users list"
print(usersList)
print("Enter user ID that you want to delete: ", end='',
flush=True) # use print instead of input to avoid blocking
id = ""
while True:
if msvcrt.kbhit():
key = ord(msvcrt.getch())
if key == 27: # escape key
print()
os.system('cls')
return # exit function
elif key == 13: # enter key
if id.isdigit():
print()
break # exit loop
else:
continue
elif key == 8: # backspace key
if len(id) > 0:
id = id[:-1]
print(f"\rEnter user ID that you want to delete: {id} {''}\b", end='', flush=True)
elif key == 224: # special keys (arrows, function keys, etc.)
key = ord(msvcrt.getch())
if key == 72: # up arrow key
continue
elif key == 80: # down arrow key
continue
elif key == 75: # left arrow key
continue
elif key == 77: # right arrow key
continue
else:
id += chr(key)
print(chr(key), end='', flush=True)
username = keycloakAdmin.get_user(usersIDs[int(id) - 1]['id'])
print(username)
keycloakAdmin.delete_user(usersIDs[int(id) - 1]['id'])
logging.info(f"Deleted profile: {username['username']}")
print(f'{Fore.LIGHTGREEN_EX}Deleted profile{Style.RESET_ALL}')
def modifyProfile(self):
usersList = prettytable.PrettyTable(["Username"])
usersIDs = []
users = keycloakAdmin.get_users()
for user in users:
usersList.add_row([user["username"]])
usersIDs.append(user)
usersList.add_autoindex("ID")
usersList.title = "Users list"
print(usersList)
print("Enter user ID that you want to delete: ", end='',
flush=True) # use print instead of input to avoid blocking
id = ""
while True:
if msvcrt.kbhit():
key = ord(msvcrt.getch())
if key == 27: # escape key
print()
os.system('cls')
return # exit function
elif key == 13: # enter key
if id.isdigit():
print()
break # exit loop
else:
continue
elif key == 8: # backspace key
if len(id) > 0:
id = id[:-1]
print(f"\rEnter user ID that you want to delete: {id} {''}\b", end='', flush=True)
elif key == 224: # special keys (arrows, function keys, etc.)
key = ord(msvcrt.getch())
if key == 72: # up arrow key
continue
elif key == 80: # down arrow key
continue
elif key == 75: # left arrow key
continue
elif key == 77: # right arrow key
continue
else:
id += chr(key)
print(chr(key), end='', flush=True)
chosenUser = usersIDs[int(id) - 1]
print("Enter username: ", end='', flush=True) # use print instead of input to avousername blocking
username = chosenUser["username"]
print(f"\rEnter username: {username} {''}\b", end='', flush=True)
while True:
if msvcrt.kbhit():
key = ord(msvcrt.getch())
if key == 27: # escape key
print()
os.system('cls')
return # exit function
elif key == 13: # enter key
print()
break # exit loop
elif key == 8: # backspace key
if len(username) > 0:
username = username[:-1]
print(f"\rEnter username: {username} {''}\b", end='', flush=True)
elif key == 224: # special keys (arrows, function keys, etc.)
key = ord(msvcrt.getch())
if key == 72: # up arrow key
continue
elif key == 80: # down arrow key
continue
elif key == 75: # left arrow key
continue
elif key == 77: # right arrow key
continue
else:
username += chr(key)
print(chr(key), end='', flush=True)
print("Enter email: ", end='', flush=True) # use print instead of input to avoemail blocking
email = ''
if 'email' in chosenUser:
email = chosenUser["email"]
print(f"\rEnter email: {email} {''}\b", end='', flush=True)
while True:
if msvcrt.kbhit():
key = ord(msvcrt.getch())
if key == 27: # escape key
print()
os.system('cls')
return # exit function
elif key == 13: # enter key
print()
break # exit loop
elif key == 8: # backspace key
if len(email) > 0:
email = email[:-1]
print(f"\rEnter email: {email} {''}\b", end='', flush=True)
elif key == 224: # special keys (arrows, function keys, etc.)
key = ord(msvcrt.getch())
if key == 72: # up arrow key
continue
elif key == 80: # down arrow key
continue
elif key == 75: # left arrow key
continue
elif key == 77: # right arrow key
continue
else:
email += chr(key)
print(chr(key), end='', flush=True)
print("Enter first name: ", end='', flush=True) # use print instead of input to avofirstName blocking
firstName = chosenUser["firstName"]
print(f"\rEnter first name: {firstName} {''}\b", end='', flush=True)
while True:
if msvcrt.kbhit():
key = ord(msvcrt.getch())
if key == 27: # escape key
print()
os.system('cls')
return # exit function
elif key == 13: # enter key
print()
break # exit loop
elif key == 8: # backspace key
if len(firstName) > 0:
firstName = firstName[:-1]
print(f"\rEnter first name: {firstName} {''}\b", end='', flush=True)
elif key == 224: # special keys (arrows, function keys, etc.)
key = ord(msvcrt.getch())
if key == 72: # up arrow key
continue
elif key == 80: # down arrow key
continue
elif key == 75: # left arrow key
continue
elif key == 77: # right arrow key
continue
else:
firstName += chr(key)
print(chr(key), end='', flush=True)
print("Enter last name: ", end='', flush=True) # use print instead of input to avolastName blocking
lastName = chosenUser["lastName"]
print(f"\rEnter last name: {lastName} {''}\b", end='', flush=True)
while True:
if msvcrt.kbhit():
key = ord(msvcrt.getch())
if key == 27: # escape key
print()
os.system('cls')
return # exit function
elif key == 13: # enter key
print()
break # exit loop
elif key == 8: # backspace key
if len(lastName) > 0:
lastName = lastName[:-1]
print(f"\rEnter last name: {lastName} {''}\b", end='', flush=True)
elif key == 224: # special keys (arrows, function keys, etc.)
key = ord(msvcrt.getch())
if key == 72: # up arrow key
continue
elif key == 80: # down arrow key
continue
elif key == 75: # left arrow key
continue
elif key == 77: # right arrow key
continue
else:
lastName += chr(key)
print(chr(key), end='', flush=True)
while True:
print(f'{Fore.LIGHTWHITE_EX}Roles{Style.RESET_ALL}\n'
'[1] - Viewer\n'
'[2] - Librarian\n'
'[3] - admin')
roles = int(input('Select from list above: '))
if roles in range(0, 4):
break
else:
print(f'{Fore.RED}Nie ma takiej opcji.{Style.RESET_ALL}')
print()
updatePayload = {"username": username,
"firstName": firstName,
"lastName": lastName
}
if email != '':
updatePayload["email"] = email
else:
updatePayload["email"] = ''
realm_roles = keycloakAdmin.get_realm_roles_of_user(user_id=chosenUser['id'])
for role in realm_roles:
keycloakAdmin.delete_realm_roles_of_user(user_id=chosenUser['id'], roles=[role])
keycloakAdmin.update_user(user_id=chosenUser['id'], payload=updatePayload)
if roles == 1:
keycloakAdmin.assign_realm_roles(user_id=chosenUser['id'], roles=[{'id': '52edcaf1-5c34-42dc-8cd0-168637c79da4', 'name': 'viewer', 'description': '', 'composite': False, 'clientRole': False, 'containerId': 'librarian-keycloak'}])
elif roles == 2:
keycloakAdmin.assign_realm_roles(user_id=chosenUser['id'], roles=[{'id': '093d1d40-60ef-4af4-8970-f2e0f4cfc053', 'name': 'librarian', 'description': '', 'composite': False, 'clientRole': False, 'containerId': 'librarian-keycloak'},
{'id': '52edcaf1-5c34-42dc-8cd0-168637c79da4', 'name': 'viewer', 'description': '', 'composite': False, 'clientRole': False, 'containerId': 'librarian-keycloak'}])
elif roles == 3:
keycloakAdmin.assign_realm_roles(user_id=chosenUser['id'], roles=[{'id': '093d1d40-60ef-4af4-8970-f2e0f4cfc053', 'name': 'librarian', 'description': '', 'composite': False, 'clientRole': False, 'containerId': 'librarian-keycloak'},
{'id': '8bfa8729-d769-4363-9243-6fee6d8f6282', 'name': 'admin', 'description': '', 'composite': False, 'clientRole': False, 'containerId': 'librarian-keycloak'},
{'id': '52edcaf1-5c34-42dc-8cd0-168637c79da4', 'name': 'viewer', 'description': '', 'composite': False, 'clientRole': False, 'containerId': 'librarian-keycloak'}])
logging.info(f"Modified profile: {username}")
print(f'{Fore.LIGHTGREEN_EX}Modified profile{Style.RESET_ALL}')
def changePassword(self, username):
try:
user_id = keycloakAdmin.get_user_id(username)
keycloakAdmin.send_update_account(user_id=user_id, payload=['UPDATE_PASSWORD'])
print(f'{Fore.GREEN}Udało się wysłać email.\n'
f'Zobacz swoją skrzynkę pocztową i postępuj zgodnie z instruckjami zawartymi w email-u{Style.RESET_ALL}')
except Exception:
print(f'{Fore.RED}Zmiana hasła niepowiodła się. Możliwe że nie masz przypisanego adresu email do profilu\n'
f'Poproś administratora o pomoc{Style.RESET_ALL}')
isEnd = False
while isEnd == False:
adminEmailChoice = input(f'Jeśli jest obok ciebie administrator wpisz? (y/n): ')
if adminEmailChoice == 'y':
if totp.verify(input("Wpisz kod OTP administratora: ")):
print()
while True:
newPassword = input('Wpisz nowe hasło: ')
repeatNewPassword = maskpass.askpass('Powtórz nowe hasło: ', '*')
if newPassword == repeatNewPassword:
keycloakAdmin.set_user_password(user_id=user_id, password=newPassword, temporary=False)
logging.info(f"{username} Changed profile password")
print(f'{Fore.GREEN}Pomyślnie zmieniono hasło{Style.RESET_ALL}')
isEnd = True
break
else:
print(f'{Fore.RED}Hasła się różnią.{Style.RESET_ALL}')
print()
break
else:
print(f'{Fore.RED}Zmiana hasła została anulowana.{Style.RESET_ALL}')
isEnd = True
elif adminEmailChoice == 'n':
print(f'{Fore.RED}Zmiana hasła została anulowana.{Style.RESET_ALL}')
break
else:
print(f'{Fore.RED}Niepoprawna komenda.{Style.RESET_ALL}')
def changeMode(self):
print(f'{Fore.GREEN}Auth confirmed{Style.RESET_ALL}')
if get_key(find_dotenv(), 'JSON') == 'True':
set_key(find_dotenv(), 'JSON', 'False')
elif get_key(find_dotenv(), 'JSON') == 'False':
set_key(find_dotenv(), 'JSON', 'True')
logging.info(f"Changed data mode")
print(f'{Fore.GREEN}Mode changed successfully{Style.RESET_ALL}')
print('Please restart program')
def resetActive(self):
if not isJson:
print(f'{Fore.GREEN}Auth confirmed{Style.RESET_ALL}')
activeCollection.delete_many({})
logging.info(f"Cleared rents list")
print(f'{Fore.GREEN}Active rents list is clear{Style.RESET_ALL}')
else:
print(f"{Fore.RED}You aren't in MongoDB mode{Style.RESET_ALL}")
def resetHistory(self):
if not isJson:
print(f'{Fore.GREEN}Auth confirmed{Style.RESET_ALL}')
historyCollection.delete_many({})
logging.info(f"Cleared history rents list")
print(f'{Fore.GREEN}History is clear{Style.RESET_ALL}')
else:
print(f"{Fore.RED}You aren't in MongoDB mode{Style.RESET_ALL}")
def resetAll(self):
if not isJson:
print(f'{Fore.GREEN}Auth confirmed{Style.RESET_ALL}')
activeCollection.delete_many({})
historyCollection.delete_many({})
logging.info(f"Cleared rents history and active rents list")
print(f'{Fore.GREEN}Database is fully reset{Style.RESET_ALL}')
else:
print(f"{Fore.RED}You aren't in MongoDB mode{Style.RESET_ALL}")
def addBook(self):
print()
print(f'{Fore.LIGHTWHITE_EX}Adding book{Style.RESET_ALL}')
while True:
bookCode = input("Enter book's code: ")
booksList = booksListCollection.find_one({"code": bookCode})
if booksList != None:
print(f'{Fore.LIGHTRED_EX}Another book already has this code{Style.RESET_ALL}')
continue
else:
break
bookTitle = interactiveInput("Enter book's title: ")
bookAmount = interactiveInput("Enter amount of books: ")
data = {
"code": bookCode,
"title": bookTitle,
"onStock": int(bookAmount),
"rented": 0
}
booksListCollection.insert_one(data)
logging.info(f"Created book: {bookTitle}")
print(f'{Fore.LIGHTGREEN_EX}Added book{Style.RESET_ALL}')
def deleteBook(self):
table = prettytable.PrettyTable(["Code", "Title", "onStock", "rented"])
table.title = "Books list"
if not isJson:
documents = booksListCollection.find()
for document in documents:
if int(document["onStock"]) <= 0:
onStock = f"""{Style.BRIGHT}{Fore.RED}{document["onStock"]}{Style.RESET_ALL}"""
else:
onStock = f"""{Style.BRIGHT}{Fore.GREEN}{document["onStock"]}{Style.RESET_ALL}"""
table.add_row([document['code'], document['title'], onStock, document['rented']])
if len(table.rows) == 0:
print()
print('Lista jest pusta')
return
else:
print(table)
else:
print(f"{Fore.RED}Books list doesn't work in local mode{Style.RESET_ALL}")
code = interactiveInput("Enter book's code that you want to delete: ")
bookTitle = booksListCollection.find_one({"code": code})
booksListCollection.delete_one({"code": code})
logging.info(f"""Deleted book: {bookTitle["title"]}""")
print(f'{Fore.LIGHTGREEN_EX}Deleted book{Style.RESET_ALL}')
def modifyBook(self):
table = prettytable.PrettyTable(["Code", "Title", "onStock", "rented"])
table.title = "Books list"
if not isJson:
documents = booksListCollection.find()
for document in documents:
if int(document["onStock"]) <= 0:
onStock = f"""{Style.BRIGHT}{Fore.RED}{document["onStock"]}{Style.RESET_ALL}"""
else:
onStock = f"""{Style.BRIGHT}{Fore.GREEN}{document["onStock"]}{Style.RESET_ALL}"""
table.add_row([document['code'], document['title'], onStock, document['rented']])
if len(table.rows) == 0:
print()
print('Lista jest pusta')
return
else:
print(table)
else:
print(f"{Fore.RED}Books list doesn't work in local mode{Style.RESET_ALL}")
code = interactiveInput("Enter book's code that you want to modify: ")
book = booksListCollection.find_one({"code": code})
newCode = interactiveInput("Enter new book code: ", book["code"])
title = interactiveInput("Enter book title: ", book["title"])
amount = interactiveInput("Enter how many books there are in total: ", str(int(book["onStock"] + book["rented"])))
updateData = {
"$set": {"code": newCode, "title": title, "onStock": (int(amount) - book["rented"])}
}
booksListCollection.update_one({"code": code}, update=updateData)
logging.info(f"""Modified book: {title}""")
print(f'{Fore.LIGHTGREEN_EX}Modified book{Style.RESET_ALL}')
def profiles():
# Konfiguracja klienta Keycloak
keycloak_url = keycloakServerUrl
realm_name = keycloakRealm
client_id = yamlFile['keycloak']['openID']['client_id']
client_secret = yamlFile['keycloak']['openID']['client_secret']
# Inicjalizacja obiektu
global keycloak_openid
keycloak_openid = KeycloakOpenID(server_url=keycloak_url, client_id=client_id, realm_name=realm_name,
client_secret_key=client_secret)
# Logowanie
def checkToken(username, password):
try:
global token
token = keycloak_openid.token(username, password)
return True
except Exception as error:
return False
while True:
print(f'{Fore.LIGHTWHITE_EX}Zaloguj się za pomocą twojego profilu. Jeśli nie pamiętasz hasła wpisz "cp":{Style.RESET_ALL}')
inputUsername = input('Wpisz login lub "cp" w celu zmiany hasła: ')
if inputUsername == 'cp':
usernmeForChangePassword = input('Wpisz login: ')
print()
adminTools.changePassword(usernmeForChangePassword)
print()
print(f'{Fore.LIGHTWHITE_EX}Jeśli zmieniłeś już hasło zaloguj się ponownie z nowym hasłem{Style.RESET_ALL}')
print()
if inputUsername != 'cp':
inputPassword = maskpass.askpass('Wpisz hasło: ', '*')
if checkToken(inputUsername, inputPassword):
global profileUsername
global profilePassword
userinfo = keycloak_openid.userinfo(token['access_token'])
profileUsername = userinfo['preferred_username']
profilePassword = inputPassword
os.system('cls')
break
else:
print(f'{Fore.RED}Niepoprawny login lub hasło.{Style.RESET_ALL}')
print()
continue
def mongoPreconfiguration():
connectionString = str
dotenv_path = find_dotenv()
global isJson
if get_key(dotenv_path, 'JSON') == 'True':
isJson = True
else:
isJson = False
if not isJson:
global passwordsDBconnection
global passwordsDBcursor
passwordsDBcursor.execute("""select * from pwds where type='mongo'""")
mongoUserData = passwordsDBcursor.fetchone()
encryptedUserInput = mongoUserData[0]
encryptedPasswordInputwordInput = mongoUserData[1]
userInput = cipher.decrypt(encryptedUserInput).decode()
passwordInput = cipher.decrypt(encryptedPasswordInputwordInput).decode()
if userInput == 'None' and passwordInput == 'None':
while True:
print(f'{Fore.LIGHTWHITE_EX}Konfiguracja dostępu do bazy danych{Style.RESET_ALL}')
userInput = input("Podaj nazwę użytkownika: ")
passwordInput = maskpass.askpass(prompt='Podaj hasło do bazy danych MongoDB: ', mask='*')
connectionString = yamlFile['mongodb_connection_string'].replace('<username>', 'default').replace('<password>', 'default')
usersClient = pymongo.MongoClient(connectionString)
usersDb = usersClient.Users
usersCollection = usersDb.users
usersDict = usersCollection.find_one({"username": str(userInput), "password": str(passwordInput)})
if usersDict != None:
encryptedUserInput = cipher.encrypt(userInput.encode())
encryptedPasswordInputwordInput = cipher.encrypt(passwordInput.encode())
passwordsDBcursor.execute(
"UPDATE pwds SET username=?, password=? WHERE type='mongo'", (encryptedUserInput, encryptedPasswordInputwordInput,))
passwordsDBconnection.commit()
logging.warning(f"Changed MongoDB credentials to {userInput}")
break
else:
print()
print(f"{Fore.RED}Nazwa użytkownika lub hasło jest niepoprawne{Style.RESET_ALL}")
print("----------------------------------------------------------------------------")
continue
try:
connectionString = yamlFile['mongodb_connection_string'].replace('<username>', userInput).replace('<password>', passwordInput)
global client
global db
global activeCollection
global historyCollection
global mongoUsersCollection
global booksListCollection
client = pymongo.MongoClient(connectionString)
db = client[yamlFile['mongo_rents_db_name']]
activeCollection = db[yamlFile['active_rents_collection_name']]
historyCollection = db[yamlFile['history_rents_collection_name']]
booksListCollection = db[yamlFile['books_list_collection_name']]
mongoUsersCollection = client[yamlFile['mongo_users_db']][yamlFile['mongo_users_collection']]
except Exception as error:
logging.error(f"mongoPreconfiguration: {error}")
print(Fore.RED + str(error) + Style.RESET_ALL)
def interactiveInput(message: str, startValue = "") -> str:
"""
This function can detect ESCAPE and ENTER key while writing. When ENTER pressed function returns the value.
When ESCAPE pressed function doesn't return anything and clear the screen. Function ignores arrows.
:param message: This is the prompt for input
:param startValue: This is useful when you want to start with some value (Useful for editing already existing data)
"""
print(f"{message}", end='', flush=True) # use print instead of input to avoid blocking
var = startValue
print(f"\r{message}{var} {''}\b", end='', flush=True)
while True:
if msvcrt.kbhit():
key = ord(msvcrt.getch())
if key == 27: # escape key
print()
os.system('cls')
return # exit function
elif key == 13: # enter key
print()
break # exit loop
elif key == 8: # backspace key
if len(var) > 0:
var = var[:-1]
print(f"\r{message}{var} {''}\b", end='', flush=True)
elif key == 224: # special keys (arrows, function keys, etc.)
key = ord(msvcrt.getch())
if key == 72: # up arrow key
continue
elif key == 80: # down arrow key
continue
elif key == 75: # left arrow key
continue
elif key == 77: # right arrow key
continue
else:
var += chr(key)
print(chr(key), end='', flush=True)
return str(var)
def qrScan():
cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)
isQRcode = False
while cap.isOpened():
success, img = cap.read()
if keyboard.is_pressed("esc"):
cap.release()
cv2.destroyAllWindows()
return False
for barcode in decode(img, symbols=[ZBarSymbol.QRCODE]):
isQRcode = True
decodedCode = barcode.data.decode('utf-8')
pts = np.array([barcode.polygon], np.int32)
pts = pts.reshape((-1,1,2))
cv2.polylines(img, [pts], True, (3, 252, 227), 5)
if isQRcode:
cap.release()
cv2.destroyAllWindows()
return decodedCode
cv2.imshow('Kamera', img)
cv2.waitKey(1)
def addHire():
"""Zapisywane dane to: imię, nazwisko, klasa, tytuł książki, data wypożyczenia, kaucja"""
sure = 0
hireData = {}
hireData["name"] = interactiveInput("Wpisz imię: ")
hireData["lastName"] = interactiveInput("Wpisz nazwisko: ")
hireData["schoolClass"] = interactiveInput("Podaj klasę czytelnika (np. 2a): ")
while True:
while True:
try:
print("[0] - Zeskanuj kod QR")
print("[1] - Wpisz kod ręcznie")
bookChoiceWay = int(input("Wybierz sposób wybrania książki: "))
if bookChoiceWay != 1 and bookChoiceWay != 0:
raise Exception
break
except Exception:
print(f"{Fore.RED}Nie znaleziono takiej komendy. Spróbuj ponownie.{Style.RESET_ALL}")
continue
if bookChoiceWay == 0:
bookCode = qrScan()
if bookCode != False:
bookDocument = booksListCollection.find_one({"code": bookCode})
if bookDocument == None:
print(f"{Fore.RED}Nie ma takiego kodu{Style.RESET_ALL}")
print()
continue
else:
hireData["bookTitle"] = bookDocument["title"]
print(f'Tytuł książki to: {bookDocument["title"]}')
break
else:
print(f"{Fore.RED}Anulowano skanowanie kodu{Style.RESET_ALL}")
print()
elif bookChoiceWay == 1:
while True:
viewBooksList()
bookCode = interactiveInput("Wpisz kod wypożyczonej książki: ")
bookDocument = booksListCollection.find_one({"code": bookCode})
if bookDocument != None:
if int(bookDocument["onStock"]) > 0:
hireData["bookTitle"] = bookDocument["title"]
break
else:
print(f"{Fore.RED}Nie ma tych książek na stanie{Style.RESET_ALL}")
print()
else:
print(f"{Fore.RED}Nie ma takiego kodu{Style.RESET_ALL}")
print()
break
print("Wpisz wartość kaucji (jeśli nie wpłacił kaucji kliknij ENTER): ", end='',
flush=True) # use print instead of input to avoid blocking
deposit = ""
while True:
if msvcrt.kbhit():
key = ord(msvcrt.getch())
if key == 27: # escape key
print()
os.system('cls')
return # exit function
elif key == 13: # enter key
if deposit == '' or deposit.isdigit() == True:
print()
break # exit loop
elif key == 8: # backspace key
if len(deposit) > 0:
deposit = deposit[:-1]
print(f"\rWpisz wartość kaucji (jeśli nie wpłacił kaucji kliknij ENTER): {deposit} {''}\b", end='',
flush=True)
elif key == 224: # special keys (arrows, function keys, etc.)
key = ord(msvcrt.getch())
if key == 72: # up arrow key
continue
elif key == 80: # down arrow key
continue
elif key == 75: # left arrow key