Skip to content
Snippets Groups Projects
Commit 5157056f authored by Pál Boldizsár's avatar Pál Boldizsár
Browse files

By all that is holy

parent b7748d15
Branches
No related tags found
No related merge requests found
Pipeline #3020 failed
......@@ -2,50 +2,37 @@
ez file lenne ami osszekoti a db-t a programunkal. hogy egyszerubb legyen
az eletunk, ezert most csak egyszeru dictekbe, meg setekbe tarolunk mindent
"""
# import pprint
import pprint
import re
fake_db = {}
# ez garantalja hogy egy username csak egyszer lehet benne
fake_db['u_names'] = set()
# ezek objektumok nev-jelszo paros listaja lesz, tehat csak sima array
fake_db['users'] = []
import time
# fake_db = {}
# # ez garantalja hogy egy username csak egyszer lehet benne
# fake_db['u_names'] = set()
# # ezek objektumok nev-jelszo paros listaja lesz, tehat csak sima array
# fake_db['users'] = []
def load_db():
try:
with open('db.txt', 'r') as f:
data = f.readline()
print(data)
m = re.search('username (.*) - password (.*)', data)
while data != '':
print()
m = re.search('username (.*) - password (.*)', data)
assert m.group()
if m.group(1) in fake_db['u_names']:
data = f.readline()
continue
fake_db['users'].append({'Username': m.group(1), 'Password': m.group(2)})
fake_db['u_names'].add(m.group(1))
data = f.readline()
except OSError as e:
return 'Succes'
return 'Succes'
class Database:
def __init__(self):
db, error = load_db()
self.db = db
load_secrets(self)
def check_user_name(username=None):
def __del__(self):
pprint.pprint(self.db)
valid_db(self.db)
save_db(self.db)
def check_user_name(self, username=None):
if not username:
return 'No name given'
if username in fake_db['u_names']: # legyen u_names a usernevek setje
if username in self.db['u_names']: # legyen u_names a usernevek setje
return 'Username taken'
else:
return ''
def hasNumbers(inputString):
return any(char.isdigit() for char in inputString)
def validate_password(password=None):
def validate_password(self, password=None):
if isinstance(password, str) is False:
return 'Bad password'
elif len(password) < 8 or 'dick' in password:
......@@ -55,42 +42,115 @@ def validate_password(password=None):
else:
return ''
def create_user(username, password):
def get_user_data(self, username):
for user in self.db['users']:
if user['username'] == username:
return user
return 'user not found'
def get_encryption_key(self, username):
if self.get_user_data(username) == 'user not found':
return False
encryption_key = self.get_user_data(username).get('encryption_key', None)
return encryption_key
def put_encryption_key(self, username, encryption_key=None):
if encryption_key is None:
encryption_key = self.get_user_data(username)['password']
self.get_user_data(username)['encryption_key'] = encryption_key
return
def create_user(self, username, password):
try:
fake_db['u_names'].add(username)
fake_db['users'].append({'Username': username, 'Password': password})
self.db['u_names'].add(username)
self.db['users'].append({'username': username, 'password': password})
except Exception as e:
return 'oopsie', e
# pprint.pprint(fake_db)
print('Welcome new user: ', username)
return True
def login_user(username, password):
def login_user(self, username, password):
if username is None or password is None:
return 'No Way'
if (username, password) in [(u['Username'], u['Password'])
for u in fake_db['users']]:
return 'Succes', username
return False, ''
if (username, password) in [(u['username'], u['password'])
for u in self.db['users']]:
return True, username
else:
return 'Nein'
return False, ''
def save_db():
def hasNumbers(inputString):
return any(char.isdigit() for char in inputString)
def save_db(db):
with open('db.txt', 'w') as f:
for user in fake_db['users']:
f.write('username {} - password {}\n'.format(user['Username'],
user['Password']))
for user in db['users']:
f.write('username {} - password {}\n'.format(user['username'],
user['password']))
with open('secrets.txt', 'w') as f:
for user in db['users']:
if 'encryption_key' in user:
f.write('username {} - key {}\n'.format(user['username'], user['encryption_key']))
return 'Succes'
def valid_db():
if len(fake_db['users']) != len(set([u['Username'] for u in fake_db['users']])):
return ['Error', len(fake_db['users']) != len(set([u['Username'] for u in fake_db['users']]))]
elif set([u['Username'] for u in fake_db['users']]) - fake_db['u_names'] == set():
def valid_db(db):
if len(db['users']) != len(set([u['username'] for u in db['users']])):
return ['Error', len(db['users']) != len(set([u['username'] for u in db['users']]))]
elif set([u['username'] for u in db['users']]) - db['u_names'] == set():
return 'Succes'
return ['error', set([u['Username'] for u in fake_db['users']]) - fake_db['u_names']]
return ['error', set([u['username'] for u in db['users']]) - db['u_names']]
def load_db():
fake_db = {}
fake_db['u_names'] = set()
fake_db['users'] = []
error_msgs = []
try:
with open('db.txt', 'r') as f:
data = f.readline()
m = re.search('username (.*) - password (.*)', data)
while data != '':
m = re.search('username (.*) - password (.*)', data)
assert m.group()
if m.group(1) in fake_db['u_names']:
error_msgs += ['Duplicate error on loading {} user | name already in db at {}'.format(m.group(1),
time.time())]
data = f.readline()
continue
fake_db['users'].append({'username': m.group(1), 'password': m.group(2)})
fake_db['u_names'].add(m.group(1))
data = f.readline()
except OSError as e:
error_msgs += ['No db file found']
return fake_db, error_msgs
return fake_db, error_msgs
def load_secrets(db):
error_msgs = []
try:
with open('secrets.txt', 'r') as f:
data = f.readline()
print(data)
m = re.search('username (.*) - key (.*)', data)
if data == '':
return
while data != '':
m = re.search('username (.*) - key (.*)', data)
assert m.group()
if db.get_user_data(m.group(1)) == 'user not found':
error_msgs += ['{} user not found at loading secrets | name not in db at {}'.format(m.group(1),
time.time())]
db.put_encryption_key(m.group(1), m.group(2))
data = f.readline()
except OSError as e:
error_msgs += ['No db file found']
return error_msgs
if __name__ != "__main__":
......
import DB.Database as db
from DB.Database import Database
import pyAesCrypt
# List of Messages
WELCOME_MESSAGE = 'WELCOME TO THE MATRIX\n'
MENU_SELECTION = ' PLease press R/r to register, L/l to log in, E/e to encrypt, Q/q to quit the program\n'
REGISTRATION_MESSAGE = 'WELCOME TO THE REGISTRATION STATION!\n If you wish to continue, press Y/y and enter!\n'
NAME_SELECTION = 'Please select a username!\n'
PASSWORD_SELECTION = 'Please select a password!\n'
FAILED_LOGGING_ATTEMPT = 'Username and password combination is not found\n'
BAD_INPUT = 'Please only use one character to select\n!'
LOGGING_MESSAGE = 'WELCOME TO THE LOGIN MENU, PRESS Y TO CONTINUE\n'
NAME_LOGGING = 'Username!\n'
PASSWORD_LOGGING = 'Password!\n'
SUCCESFULLY_LOGGED = 'Succes! Welcome: '
ENCRYPTION_MENU = '\n\n\n WELCOME TO THE ENCRYPTION MENU!'
ENCRYPTION_SELECTION = '\n TO ENCRYPT A FILE PRESS E/e TO DECRYPT A FILE PRESS D/d! Press Q/q to quit!'
bufferSize = 64 * 1024
def Register(username=None, password=None):
def Register(db):
user_interaction_input = input(REGISTRATION_MESSAGE)
if user_interaction_input not in ['y', 'Y']:
return False, 'Aborted'
username = input(NAME_SELECTION)
password = input(PASSWORD_SELECTION)
if db.check_user_name(username) != '':
return db.check_user_name(username)
return False, db.check_user_name(username)
if db.validate_password(password) != '':
return db.validate_password(password)
return False, db.validate_password(password)
else:
error_msgs = db.create_user(username, password)
return [False, error_msgs] if error_msgs is not True else [True, '']
def login_user(db):
user_interaction_input = input(LOGGING_MESSAGE)
if user_interaction_input not in ['y', 'Y']:
return False, 'Aborted'
username = input(NAME_LOGGING)
password = input(PASSWORD_LOGGING)
state, logged_username = db.login_user(username, password)
if state is True:
print(SUCCESFULLY_LOGGED, logged_username, '\n')
return state, logged_username
else:
db.create_user(username, password)
return 'Succes'
print(FAILED_LOGGING_ATTEMPT)
return state, None
def file_encryption(user, encryption_key, filename):
try:
pyAesCrypt.encryptFile(filename, filename + '.aes', encryption_key, bufferSize)
except OSError as e:
return e
return 'succes'
def login_user(username=None, password=None):
return db.login_user(username, password)
def file_decryption(user, encryption_key, filename):
try:
pyAesCrypt.decryptFile(filename + ".aes", filename, encryption_key, bufferSize)
except OSError as e:
return e
return 'succes'
def file_encryption_menu(db, username=None):
if username is None or username == '':
print('You need to log in first!')
return 'Not logged in'
print(ENCRYPTION_MENU)
encryption_key = db.get_encryption_key(username)
if encryption_key is False:
print('internal error at {}'.format(username))
return
while encryption_key is None:
print(' You need to set up your encryption key!!!\n')
user_interaction_input = input(' If you wish to set up an ecryption key, press Y/y and enter!\n')
user_interaction_input = user_interaction_input.upper()
if user_interaction_input != 'Y':
return 'Aborted'
user_interaction_input = input('If you want to use your password as encryption key, press Y!\n')
user_interaction_input = user_interaction_input.upper()
if user_interaction_input == 'Y':
db.put_encryption_key(username)
encryption_key = db.get_encryption_key(username)
break
password = input('Please submit your encryption key!\n')
if db.validate_password(password) != '':
print('!!!!ERROR!!!! ->', db.validate_password(password))
encryption_key = db.get_encryption_key(username)
continue
db.put_encryption_key(username, password)
encryption_key = db.get_encryption_key(username)
while 1:
user_interaction_input = input(ENCRYPTION_SELECTION)
user_interaction_input = user_interaction_input.upper()
if len(user_interaction_input) > 1:
print(BAD_INPUT)
continue
elif user_interaction_input == 'E':
filename = input('Give Us The File Name!')
state = file_encryption(db, username, filename)
print(state)
elif user_interaction_input == 'D':
filename = input('Give Us The File Name!')
state = file_decryption(db, username, filename)
print(state)
elif user_interaction_input == 'Q':
return
if __name__ == "__main__":
print(db.load_db())
print(WELCOME_MESSAGE)
db = Database()
username = ''
while 1:
text_input = input("Press enter to start registration, anything else \
+ enter if login")
if text_input == '':
name = input("Give us a Username ")
psw = input("Give us a Password ")
state = Register(name, psw)
if state != 'Succes':
while state != 'Succes':
print('Let\'s Try again because:' + state, '\n')
name = input("Give us a Username ")
psw = input("Give us a Password ")
state = Register(name, psw)
db.save_db()
# print('Noice')
elif text_input != '0':
name = input("Give us a Username ")
psw = input("Give us a Password ")
state = login_user(name, psw)
if state[0] != 'Succes':
while state[0] != 'Succes':
print('Let\'s Try again because:' + state, '\n')
name = input("Give us a Username ")
psw = input("Give us a Password ")
state = login_user(name, psw)
else:
print('Db validation: ', db.valid_db())
db.save_db()
user_interaction_input = input(MENU_SELECTION)
user_interaction_input = user_interaction_input.upper()
if len(user_interaction_input) > 1:
print(BAD_INPUT)
continue
elif user_interaction_input == 'R':
[state, error] = Register(db)
while error not in [None, 'Aborted']:
print('!!!!ERROR!!!! ->', error)
state, error = Register(db)
elif user_interaction_input == 'L':
state, username = login_user(db)
print(username)
while state is False and username != 'Aborted':
state, username = login_user(db)
if state is True:
MENU_SELECTION += 'Logged in as ' + str(username) + '\n'
elif user_interaction_input == 'E':
file_encryption_menu(db, username)
elif user_interaction_input == 'Q':
del db
exit()
# print('Noice: ', state[1])
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment