diff --git a/delivery1/client/bin/rep_activate_subject b/delivery1/client/bin/rep_activate_subject index 20fcb7a..388a764 100755 --- a/delivery1/client/bin/rep_activate_subject +++ b/delivery1/client/bin/rep_activate_subject @@ -6,7 +6,6 @@ import requests import json import argparse -sys.path.append(os.path.abspath("../")) from subject import main logging.basicConfig(format='%(levelname)s\t- %(message)s') @@ -15,6 +14,8 @@ logger.setLevel(logging.INFO) state = main(sys.argv) +BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/') + #session file - username def activateSubject(args): parser = argparse.ArgumentParser() @@ -32,13 +33,16 @@ def activateSubject(args): logger.error("Need session file and username.") sys.exit(-1) - if (not os.path.isfile(args.session)): + if (not os.path.isfile(BASE_DIR + args.session)): logger.error("File '" + args.session + "' not found.") sys.exit(-1) - subject = {'session_file' : args.session, 'username' : args.username} + # Get session file content + with open(BASE_DIR + args.session, 'r') as f: + args.session = json.load(f) + try: - req = requests.post(f'http://{state['REP_ADDRESS']}/user/activate', json=json.dumps(subject)) + req = requests.post(f'http://{state['REP_ADDRESS']}/user/' + args.username + '/activate', headers={'Authorization': args.session['token']}) req.raise_for_status() except requests.exceptions.RequestException as errex: logger.error("Failed to obtain response from server.") diff --git a/delivery1/client/bin/rep_add_doc b/delivery1/client/bin/rep_add_doc index 8ecf0a6..1fe73b6 100755 --- a/delivery1/client/bin/rep_add_doc +++ b/delivery1/client/bin/rep_add_doc @@ -6,10 +6,11 @@ import requests import json import argparse -sys.path.append(os.path.abspath("../")) from subject import main -from lib import encryption_functs +sys.path.append(os.path.abspath("../../")) +from lib.symmetric_encryption import * +from lib import digest logging.basicConfig(format='%(levelname)s\t- %(message)s') logger = logging.getLogger() @@ -17,6 +18,8 @@ logger.setLevel(logging.INFO) state = main(sys.argv) +BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/') + # session file - document name - file def addDoc(args): parser = argparse.ArgumentParser() @@ -35,33 +38,55 @@ def addDoc(args): logger.error("Need session file, document's name and file to upload.") sys.exit(-1) - if (not os.path.isfile(args.session)): + if (not os.path.isfile(os.path.join(BASE_DIR, args.session))): logger.error("File '" + args.session + "' not found.") sys.exit(-1) - if (not os.path.isfile(args.file)): + if (not os.path.isfile(os.path.join(BASE_DIR, args.file))): logger.error("File '" + args.file + "' not found") sys.exit(-1) - # Get pub key - pubkey = encryption_functs.load_public_key(state['PUB_KEY']) - - #encrypt content - with open(args.file, 'rb') as f: - content = f.read() + #Get session file content + with open(os.path.join(BASE_DIR, args.session), 'r') as f: + args.session = json.load(f) - content = encryption_functs.encrypt_file(pubkey, content) + # Get hash of document's name for doc handle + doc_name = digest.get_hash(bytes(args.name, encoding='utf-8')) - doc = {'session_file' : args.session, 'document_name' : args.name, 'content' : content} + + #Upload document metadata + doc = {'document_name' : doc_name} try: - req = requests.post(f'http://{state['REP_ADDRESS']}/file/upload', json=json.dumps(doc)) + req = requests.post(f'http://{state['REP_ADDRESS']}/file/upload', json=json.dumps(doc), headers={'Authorization': args.session['token']}) req.raise_for_status() except requests.exceptions.RequestException as errex: logger.error("Failed to obtain response from server.") sys.exit(1) + #Upload Document content + #Create salt + salt = os.urandom(16) + + #Encrypt content + encrypt_file(salt, BASE_DIR + args.file, BASE_DIR + 'encryptedText') + + with open(BASE_DIR + 'encryptedText', 'rb') as f: + content = f.read() + + try: + req = requests.post(f'http://{state['REP_ADDRESS']}/file/upload', json=json.dumps({'dw' : content.hex()}), headers={'Authorization': args.session['token']}) + req.raise_for_status() + + except requests.exceptions.RequestException as errex: + logger.error("Failed to obtain response from server.") + os.remove(BASE_DIR + 'encryptedText') + sys.exit(1) + + #Delete temporary file + os.remove(BASE_DIR + 'encryptedText') + sys.exit(0) if __name__ == '__main__': diff --git a/delivery1/client/bin/rep_add_subject b/delivery1/client/bin/rep_add_subject index 82ab8f1..412c945 100755 --- a/delivery1/client/bin/rep_add_subject +++ b/delivery1/client/bin/rep_add_subject @@ -6,7 +6,6 @@ import requests import json import argparse -sys.path.append(os.path.abspath("../")) from subject import main from lib import encryption_functs @@ -17,6 +16,8 @@ logger.setLevel(logging.INFO) state = main(sys.argv) +BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/') + # session file - username - name - email - credentials file def addSubject(args): parser = argparse.ArgumentParser() @@ -33,22 +34,26 @@ def addSubject(args): args = parser.parse_args() - if len(args) != 5: + if not args.session or not args.username or not args.name or not args.email or not args.credentials: logger.error("Need session file, username, name, email and credentials file.") sys.exit(-1) - if (not os.path.isfile(args.session)): + if (not os.path.isfile(BASE_DIR + args.session)): logger.error("File '" + args.session + "' not found.") sys.exit(-1) - if (not os.path.isfile(args.credentials)): + # Get session file content + with open(BASE_DIR + args.session, 'r') as f: + args.session = json.load(f) + + if (not os.path.isfile(BASE_DIR + args.credentials)): logger.error("File '" + args.file + "' not found") sys.exit(-1) - subject = {'session_file' : args.session, 'username' : args.username, 'name' : args.name, 'email' : args.email, 'credentials_file' : args.credentials} + subject = {'username' : args.username, 'name' : args.name, 'email' : args.email, 'credentials_file' : args.credentials} try: - req = requests.post(f'http://{state['REP_ADDRESS']}/user/create', json=json.dumps(subject)) + req = requests.post(f'http://{state['REP_ADDRESS']}/user/create', json=json.dumps(subject), headers={'Authorization': args.session['token']}) req.raise_for_status() except requests.exceptions.RequestException as errex: diff --git a/delivery1/client/bin/rep_create_org b/delivery1/client/bin/rep_create_org index 35d6ffd..9fd4831 100755 --- a/delivery1/client/bin/rep_create_org +++ b/delivery1/client/bin/rep_create_org @@ -10,9 +10,8 @@ import argparse sys.path.append(os.path.abspath("../")) from subject import main -from lib import encryption_functs - - +sys.path.append(os.path.abspath('../../')) +from lib import asymmetric_functs logging.basicConfig(format='%(levelname)s\t- %(message)s') logger = logging.getLogger() @@ -20,6 +19,8 @@ logger.setLevel(logging.INFO) state = main(sys.argv) +BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/') + # Create organization # organization - username - name - email - public key file def createOrganization(args): @@ -34,12 +35,11 @@ def createOrganization(args): parser.add_argument('username', nargs='?', default=None) parser.add_argument('name', nargs='?', default=None) parser.add_argument('email', nargs='?', default=None) - parser.add_argument('key', nargs='?', default=None) + parser.add_argument('pubkey', nargs='?', default=None) args = parser.parse_args() - #Validate num of arguments - if len(args) != 5: + if not args.org or not args.username or not args.name or not args.email or not args.pubkey: logger.error("Need organization, username, name, email and key file.") sys.exit(-1) @@ -49,21 +49,21 @@ def createOrganization(args): sys.exit(-1) # Validate key file - if (not os.path.isfile(args.key)): - logger.error("File '" + args.key + "' not found.") + if (not os.path.isfile(BASE_DIR + args.pubkey)): + logger.error("File '" + args.pubkey + "' not found.") sys.exit(-1) # load public key from file - pubKey = encryption_functs.load_public_key(args.key) + pubKey = asymmetric_functs.load_public_key(BASE_DIR + args.pubkey) input = {'name' : args.org, 'username' : args.username, 'full_name' : args.name, 'email' : args.email, 'public_key' : pubKey} try: - req = requests.post(f'http://{state['REP_ADDRESS']}/org/create', json=json.dumps(input)) + req = requests.post(f'https://{state['REP_ADDRESS']}/org/create', json=json.dumps(input)) req.raise_for_status() except requests.exceptions.RequestException as errex: - logger.error("Failed to obtain response from server.") - sys.exit(1) + logger.error("Failed to obtain response from server.") + sys.exit(1) if __name__ == '__main__': createOrganization(sys.argv[1:]) diff --git a/delivery1/client/bin/rep_create_session b/delivery1/client/bin/rep_create_session index 7e4ef0b..9ad9f24 100755 --- a/delivery1/client/bin/rep_create_session +++ b/delivery1/client/bin/rep_create_session @@ -6,7 +6,6 @@ import logging import json import requests -sys.path.append(os.path.abspath("../")) from subject import main # Identity attributes @@ -18,6 +17,8 @@ logger.setLevel(logging.INFO) state = main(sys.argv) +BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/') + # org - username - password - credentials file - session file def createSession(args): @@ -35,25 +36,27 @@ def createSession(args): args = parser.parse_args() - if len(args != 5): + if not args.org or not args.username or not args.password or not args.credentials or not args.session: logger.error("Need organization, username, password, credentials and session file") sys.exit(-1) - if (not os.path.isfile(args.credentials)): + if (not os.path.isfile(BASE_DIR + args.credentials)): logger.error("File '" + args.credentials + "' not found.") sys.exit(-1) session = {'org' : args.org, 'username' : args.username, 'password' : args.password, 'credentials_file' : args.credentials} + #print( type(json.dumps(session))) + try: - req = requests.post(f'http://{state['REP_ADDRESS']}/user/login', json=json.dumps(session)) + req = requests.post(f'https://{state['REP_ADDRESS']}/user/login', json=json.dumps(session)) req.raise_for_status() except requests.exceptions.RequestException as errex: logger.error("Failed to obtain response from server") sys.exit(1) - with open(args.session, 'w') as f: - f.write(json.dumps(req)) + with open(BASE_DIR + args.session, 'w') as f: + f.write(req.json()) if __name__ == '__main__': createSession(sys.argv[1:]) \ No newline at end of file diff --git a/delivery1/client/bin/rep_decrypt_file b/delivery1/client/bin/rep_decrypt_file index 6df535e..8ebf6d2 100755 --- a/delivery1/client/bin/rep_decrypt_file +++ b/delivery1/client/bin/rep_decrypt_file @@ -3,13 +3,16 @@ import os import sys import logging import argparse +import json -from lib import decryption_functs +from lib import symmetric_encryption logging.basicConfig(format='%(levelname)s\t- %(message)s') logger = logging.getLogger() logger.setLevel(logging.INFO) +BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/') + #send to stdout contents of decrypted file # encrypted file - encryption metadata def decryptFile(args): @@ -26,19 +29,19 @@ def decryptFile(args): sys.exit(-1) # If first argument is not a file or not found - if (not os.path.isfile(args.encrypted)): + if (not os.path.isfile(BASE_DIR + args.encrypted)): logger.error("File '" + args.encrypted + "' not found.") sys.exit(-1) - if (not os.path.isfile(args.metadata)): + if (not os.path.isfile(BASE_DIR + args.metadata)): logger.error("File '" + args.metadata + "' not found.") sys.exit(-1) #Decrypt file - with open(args.encrypted, 'rb') as f: - content = f.read() + metadata = json.loads(BASE_DIR + args.metadata) + salt = metadata['salt'] - content = decryption_functs.decrypt_file('privateKey', content) + content = symmetric_encryption.decrypt_file(metadata['password'], args.encrypted) # Send decrypted content to stdout sys.stdout.write(content) diff --git a/delivery1/client/bin/rep_delete_doc b/delivery1/client/bin/rep_delete_doc index 28702d3..4926e93 100755 --- a/delivery1/client/bin/rep_delete_doc +++ b/delivery1/client/bin/rep_delete_doc @@ -5,8 +5,8 @@ import logging import requests import json import argparse +from lib import digest -sys.path.append(os.path.abspath("../")) from subject import main logging.basicConfig(format='%(levelname)s\t- %(message)s') @@ -15,6 +15,8 @@ logger.setLevel(logging.INFO) state = main(sys.argv) +BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/') + # session file - document name def delDoc(args): parser = argparse.ArgumentParser() @@ -32,13 +34,19 @@ def delDoc(args): logger.error("Need session file and document's name.") sys.exit(-1) - if (not os.path.isfile(args.session)): + if (not os.path.isfile(BASE_DIR + args.session)): logger.error("File '" + args.session + "' not found.") sys.exit(-1) - doc = {'session_file' : args.session, 'document_name' : args.name} + # Get session file content + with open(BASE_DIR + args.session, 'r') as f: + args.session = json.load(f) + + doc_name = digest.get_hash(bytes(args.name, encoding='utf-8')) + doc = {'document_name' : doc_name} + try: - req = requests.post(f'http://{state['REP_ADDRESS']}/file/delete', json=json.dumps(doc)) + req = requests.post(f'http://{state['REP_ADDRESS']}/file/delete/' + doc_name, headers={'Authorization': args.session['token']}) req.raise_for_status() except requests.exceptions.RequestException as errex: diff --git a/delivery1/client/bin/rep_get_doc_file b/delivery1/client/bin/rep_get_doc_file index 7933e20..67db4a8 100755 --- a/delivery1/client/bin/rep_get_doc_file +++ b/delivery1/client/bin/rep_get_doc_file @@ -6,15 +6,18 @@ import requests import json import argparse -sys.path.append(os.path.abspath("../")) from subject import main +from lib import digest + logging.basicConfig(format='%(levelname)s\t- %(message)s') logger = logging.getLogger() logger.setLevel(logging.INFO) state = main(sys.argv) +BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/') + # session file - document name - output file(optional) def getDoc(args): parser = argparse.ArgumentParser() @@ -33,25 +36,55 @@ def getDoc(args): logger.error("Need session file and document's name.") sys.exit(-1) - if (not os.path.isfile(args.session)): + if (not os.path.isfile(BASE_DIR + args.session)): logger.error("File '" + args.session + "' not found.") sys.exit(-1) - doc = {'session_file' : args.session, 'document_name' : args.name} + # Get session file content + with open(BASE_DIR + args.session, 'r') as f: + args.session = json.load(f) + + # Get Document metadata + + doc_name = digest.get_hash(args.name) try: - req = requests.post(f'http://{state['REP_ADDRESS']}/file/get', json=json.dumps(doc)) - req.raise_for_status() + metadata = requests.post(f'http://{state['REP_ADDRESS']}/file/' + doc_name, headers={'Authorization': args.session['token']}) + metadata.raise_for_status() + except requests.exceptions.RequestException as errex: logger.error("Failed to obtain response from server.") sys.exit(1) + metadata = metadata.json() + + #Get file with file_handle provided by metadata + + try: + file = requests.get(f'http://{state['REP_ADDRESS']}/get/' + metadata['file_handle'] + '/content') + file.raise_for_status() + except requests.exceptions.RequestException as errex: + logger.error("Failed to obtain response from server.") + sys.exit(1) + + file = file.json() + + if not digest.get_hash(file) == metadata['file_handle']: + logger.error("Files integrity is lost.") + sys.exit(1) + + key, alg = metadata['key'], metadata['alg'] + salt, passwd = alg['salt'], alg['password'] + + if args.output: - with open(args.output, 'w') as f: - f.write(req) + with open(BASE_DIR + args.output, 'w') as f: + f.write(file) else: - sys.stdout.write(req) + sys.stdout.write(file) + + sys.exit(0) diff --git a/delivery1/client/bin/rep_get_doc_metadata b/delivery1/client/bin/rep_get_doc_metadata index 8eb2fd0..d84b10e 100755 --- a/delivery1/client/bin/rep_get_doc_metadata +++ b/delivery1/client/bin/rep_get_doc_metadata @@ -5,8 +5,8 @@ import logging import requests import json import argparse +from lib import digest -sys.path.append(os.path.abspath("../")) from subject import main logging.basicConfig(format='%(levelname)s\t- %(message)s') @@ -15,7 +15,7 @@ logger.setLevel(logging.INFO) state = main(sys.argv) -print(state) +BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/') # session file - document name def getDocMetadata(args): @@ -35,21 +35,27 @@ def getDocMetadata(args): logger.error("Need session file and document's name.") sys.exit(-1) - if (not os.path.isfile(args.session)): + if (not os.path.isfile(BASE_DIR + args.session)): logger.error("File '" + args.session + "' not found.") sys.exit(-1) - doc = {'session_file' : args.session, 'document_name' : args.name} + # Get session file content + with open(BASE_DIR + args.session, 'r') as f: + args.session = json.load(f) + + doc_name = digest.get_hash(bytes(args.name, encoding='utf-8')) try: - req = requests.post(f'http://{state['REP_ADDRESS']}/file/metadata', json=json.dumps(doc)) - req.raise_for_status() + metadata = requests.post(f'http://{state['REP_ADDRESS']}/file/' + doc_name + '/metadata', headers={'Authorization': args.session['token']}) + metadata.raise_for_status() except requests.exceptions.RequestException as errex: logger.error("Failed to obtain response from server.") sys.exit(1) - sys.stdout.write(req) + metadata = metadata.json() + + sys.stdout.write(metadata) if __name__ == '__main__': getDocMetadata(sys.argv[1:]) \ No newline at end of file diff --git a/delivery1/client/bin/rep_get_file b/delivery1/client/bin/rep_get_file index 3eb6df2..1b0e573 100755 --- a/delivery1/client/bin/rep_get_file +++ b/delivery1/client/bin/rep_get_file @@ -6,7 +6,6 @@ import json import requests import argparse -sys.path.append(os.path.abspath("../")) from subject import main # Identity attributes @@ -18,6 +17,8 @@ logger.setLevel(logging.INFO) state = main(sys.argv) +BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/') + #get file #file handle - file(optonal) def getFile(args): @@ -37,26 +38,24 @@ def getFile(args): logger.error("Need a file handle.") sys.exit(-1) else: - if not os.path.isfile(args.filehandle): + if not os.path.isfile(BASE_DIR + args.filehandle): logger.error("File '" + args.filehandle + "' not found" ) + #Get file try: - file = requests.get(f'http://{state['REP_ADDRESS']}/file', json=json.dumps({"file_handle" : args.filehandle})) + file = requests.get(f'http://{state['REP_ADDRESS']}/get/' + args.file_handle + '/content') file.raise_for_status() except requests.exceptions.RequestException as errex: logger.error("Failed to obtain response from server.") sys.exit(1) - file = json.loads(file) - - # decrypt file - content = '' #decrypt(file.encode('utf-8')) + file = file.json() if not args.file: - sys.stdout.write(content) + sys.stdout.write(file) else: - with open(args.file, "wb") as f: - f.write(content) + with open(BASE_DIR + args.file, "wb") as f: + f.write(file) if __name__ == '__main__': getFile(sys.argv[1:]) \ No newline at end of file diff --git a/delivery1/client/bin/rep_list_docs b/delivery1/client/bin/rep_list_docs index 3a8981b..a675d00 100755 --- a/delivery1/client/bin/rep_list_docs +++ b/delivery1/client/bin/rep_list_docs @@ -7,7 +7,6 @@ import json import argparse import datetime -sys.path.append(os.path.abspath("../")) from subject import main logging.basicConfig(format='%(levelname)s\t- %(message)s') @@ -16,13 +15,17 @@ logger.setLevel(logging.INFO) state = main(sys.argv) -def validDate(date): +BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/') + +def validDate(input): try: - datetime.datetime.strptime(input,"%d/%m/%Y") + date = datetime.datetime.strptime(input,"%d/%m/%Y") except ValueError as err: logger.error("Date is invalid. Input format: DD/MM/YYYY") sys.exit(-1) + return date + #session file - [-s username] [-d nt/ot/et date] def list_docs(args): parser = argparse.ArgumentParser() @@ -41,71 +44,80 @@ def list_docs(args): # Check if session file is valid if args.session: - if (not os.path.isfile(args.session)): + if (not os.path.isfile(BASE_DIR + args.session)): logger.error("File '" + args.session + "' not found.") sys.exit(-1) else: logger.error("Need session file.") sys.exit(-1) + # Get session file content + with open(BASE_DIR + args.session, 'r') as f: + args.session = json.load(f) + if args.newerThan: - validDate(args.newerThan) + #Convert date str to datetime in seconds + args.newerThan = validDate(args.newerThan) + args.newerThan = int(args.newerThan.timestamp()) try: subjects = requests.get(f'http://{state['REP_ADDRESS']}/file/list', - json=json.dumps({'session_file' : args.session, 'username' : args.username, - 'datetime' : {'value' : args.newerThan, 'relation' : 'nt'} - })) + json=json.dumps({'username' : args.username,'datetime' : {'value' : args.newerThan, 'relation' : 'nt'}}), + headers={'Authorization': args.session['token']}) subjects.raise_for_status() except requests.exceptions.RequestException as errex: logger.error("Failed to obtain response from server.") sys.exit(1) - subjects = json.loads(subjects) + subjects = subjects.json() elif args.equalTo: - validDate(args.equalTo) + #Convert date str to datetime in seconds + args.equalTo = validDate(args.equalTo) + args.equalTo = int(args.equalTo.timestamp()) try: subjects = requests.get(f'http://{state['REP_ADDRESS']}/file/list', - json=json.dumps({'session_file' : args.session, 'username' : args.username, - 'datetime' : {'value' : args.equalTo, 'relation' : 'eq'} - })) + json=json.dumps({'username' : args.username, + 'datetime' : {'value' : args.equalTo, 'relation' : 'eq'}}), + headers={'Authorization': args.session['token']}) subjects.raise_for_status() except requests.exceptions.RequestException as errex: logger.error("Failed to obtain response from server.") sys.exit(1) - subjects = json.loads(subjects) + subjects = subjects.json() elif args.olderThan: - validDate(args.olderThan) + #Convert date str to datetime in seconds + args.olderThan = validDate(args.olderThan) + args.olderThan = int(args.olderThan.timestamp()) try: subjects = requests.get(f'http://{state['REP_ADDRESS']}/file/list', - json=json.dumps({'session_file' : args.session, 'username' : args.username, - 'datetime' : {'value' : args.olderThan, 'relation' : 'ot'} - })) + json=json.dumps({'username' : args.username, + 'datetime' : {'value' : args.olderThan, 'relation' : 'ot'}}), + headers={'Authorization': args.session['token']}) subjects.raise_for_status() except requests.exceptions.RequestException as errex: logger.error("Failed to obtain response from server.") sys.exit(1) - subjects = json.loads(subjects) + subjects = subjects.json() else: try: - subjects = requests.get(f'http://{state['REP_ADDRESS']}/file/list', json=json.dumps({'session_file' : args.session})) + subjects = requests.get(f'http://{state['REP_ADDRESS']}/file/list', headers={'Authorization': args.session['token']}) subjects.raise_for_status() except requests.exceptions.RequestException as errex: logger.error("Failed to obtain response from server.") sys.exit(1) - subjects = json.loads(subjects) + subjects = subjects.json() for s in subjects: sys.stdout.write(s['id'] + " - " + s['username']) diff --git a/delivery1/client/bin/rep_list_orgs b/delivery1/client/bin/rep_list_orgs index 13b1b97..13f268d 100755 --- a/delivery1/client/bin/rep_list_orgs +++ b/delivery1/client/bin/rep_list_orgs @@ -5,7 +5,6 @@ import logging import json import requests -sys.path.append(os.path.abspath("../")) from subject import main # Identity attributes @@ -19,15 +18,15 @@ state = main(sys.argv) def listOrganizations(): try: - orgs = json.loads(requests.get(f'http://{state['REP_ADDRESS']}/org/list')) + orgs = requests.get(f'https://{state['REP_ADDRESS']}/org/list') orgs.raise_for_status() except requests.exceptions.RequestException as errex: logger.error("Failed to obtain response from server.") sys.exit(1) - for org in orgs: - sys.stdout.write(org['id'] + " - " + org['name']) + for org in orgs.json(): + sys.stdout.write(str(org['id']) + " - " + org['name']) if __name__ == '__main__': - listOrganizations(sys.argv[1:]) \ No newline at end of file + listOrganizations() \ No newline at end of file diff --git a/delivery1/client/bin/rep_list_subjects b/delivery1/client/bin/rep_list_subjects index 57336be..1d2734d 100755 --- a/delivery1/client/bin/rep_list_subjects +++ b/delivery1/client/bin/rep_list_subjects @@ -6,7 +6,6 @@ import requests import json import argparse -sys.path.append(os.path.abspath("../")) from subject import main logging.basicConfig(format='%(levelname)s\t- %(message)s') @@ -15,6 +14,8 @@ logger.setLevel(logging.INFO) state = main(sys.argv) +BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/') + # session file - username(optional) def list_subjects(args): @@ -30,14 +31,23 @@ def list_subjects(args): args = parser.parse_args() # Check if session file is valid - if (not os.path.isfile(args.session)): - logger.error("File '" + args.session + "' not found.") + if args.session: + if (not os.path.isfile(BASE_DIR + args.session)): + logger.error("File '" + args.session + "' not found.") + sys.exit(-1) + else: + logger.error("Need session file.") sys.exit(-1) + # Get session file content + with open(BASE_DIR + args.session, 'r') as f: + args.session = json.load(f) + if args.username: try: - subjects = json.loads(requests.get(f'http://{state['REP_ADDRESS']}/user/list', - json=json.dumps({'session_file' : args.session, 'username' : args.username}))) + subjects = requests.get(f'http://{state['REP_ADDRESS']}/user/list', + json=json.dumps({'username' : args.username}), + headers={'Authorization': args.session['token']}) subjects.raise_for_status() except requests.exceptions.RequestException as errex: @@ -46,15 +56,15 @@ def list_subjects(args): else: try: - subjects = json.loads(requests.get(f'http://{state['REP_ADDRESS']}/user/list'), - json=json.dumps({'session_file' : args.session})) + subjects = requests.get(f'https://{state['REP_ADDRESS']}/user/list', + headers={'Authorization': args.session['token']}) subjects.raise_for_status() except requests.exceptions.RequestException as errex: logger.error("Failed to obtain response from server.") sys.exit(1) - for s in subjects: + for s in subjects.json(): sys.stdout.write(s['id'] + " - " + s['username']) diff --git a/delivery1/client/bin/rep_subject_credentials b/delivery1/client/bin/rep_subject_credentials index 94cb4a8..a446031 100755 --- a/delivery1/client/bin/rep_subject_credentials +++ b/delivery1/client/bin/rep_subject_credentials @@ -4,12 +4,15 @@ import sys import logging import argparse +sys.path.append(os.path.abspath("../../")) from lib import key_pair logging.basicConfig(format='%(levelname)s\t- %(message)s') logger = logging.getLogger() logger.setLevel(logging.INFO) +BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/') + # Generate a key pair for a subject # password - file for public key, file for private key def generateKeyPair(args): @@ -22,17 +25,13 @@ def generateKeyPair(args): args = parser.parse_args() - if len(args) != 3: + if not args.password or not args.pubfile or not args.privfile: logger.error("Need password and file to store keys") sys.exit(-1) #Generate the key pair - key_pair.generate_key_pair(args.pubfile, args.privfile, 2048, args.password) - - #Save key files in environment - os.environ['PRIV_KEY'] = args.privfile - os.environ['PUB_KEY'] = args.pubfile + key_pair.generate_key_pair(BASE_DIR + args.pubfile, BASE_DIR + args.privfile, 2048, args.password) return 0 diff --git a/delivery1/client/bin/rep_suspend_subject b/delivery1/client/bin/rep_suspend_subject index 6d14865..003e4ce 100755 --- a/delivery1/client/bin/rep_suspend_subject +++ b/delivery1/client/bin/rep_suspend_subject @@ -15,6 +15,8 @@ logger.setLevel(logging.INFO) state = main(sys.argv) +BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/') + # session file - username def suspendSubject(args): parser = argparse.ArgumentParser() @@ -32,12 +34,20 @@ def suspendSubject(args): logger.error("Need session file and username.") sys.exit(-1) - if (not os.path.isfile(args.session)): + if (not os.path.isfile(BASE_DIR + args.session)): logger.error("File '" + args.session + "' not found.") sys.exit(-1) - subject = {'session_file' : args.session, 'username' : args.username} - req = requests.post(f'http://{state['REP_ADDRESS']}/user/suspend', json=json.dumps(subject)) + # Get session file content + with open(BASE_DIR + args.session, 'r') as f: + args.session = json.load(f) + try: + req = requests.post(f'http://{state['REP_ADDRESS']}/user/' + args.username + '/suspend', headers={'Authorization': args.session['token']}) + req.raise_for_status() + except requests.exceptions.RequestException as errex: + logger.error("Failed to obtain response from server.") + sys.exit(1) + if __name__ == '__main__': suspendSubject(sys.argv[1:]) \ No newline at end of file diff --git a/delivery1/client/bin/subject.py b/delivery1/client/bin/subject.py new file mode 100644 index 0000000..fc4e915 --- /dev/null +++ b/delivery1/client/bin/subject.py @@ -0,0 +1,116 @@ +import os +import sys +import argparse +import logging +import json +import requests + +# Identity attributes +# {'username' : '', 'full_name' : '', 'email' : '', public_key : '' } + +logging.basicConfig(format='%(levelname)s\t- %(message)s') +logger = logging.getLogger() +logger.setLevel(logging.INFO) + +def load_state(): + state = {} + state_dir = os.path.join(os.path.expanduser('~'), '.sio') + state_file = os.path.join(state_dir, 'state.json') + + logger.debug('State folder: ' + state_dir) + logger.debug('State file: ' + state_file) + + if os.path.exists(state_file): + logger.debug('Loading state') + with open(state_file,'r') as f: + state = json.loads(f.read()) + + if state is None: + state = {} + + return state + +def parse_env(state): + if 'REP_ADDRESS' in os.environ: + state['REP_ADDRESS'] = os.getenv('REP_ADDRESS') + logger.debug('Setting REP_ADDRESS from Environment to: ' + state['REP_ADDRESS']) + + if 'REP_PUB_KEY' in os.environ: + rep_pub_key = os.getenv('REP_PUB_KEY') + logger.debug('Loading REP_PUB_KEY fron: ' + state['REP_PUB_KEY']) + if os.path.exists(rep_pub_key): + with open(rep_pub_key, 'r') as f: + state['REP_PUB_KEY'] = f.read() + logger.debug('Loaded REP_PUB_KEY from Environment') + return state + +def parse_args(state): + parser = argparse.ArgumentParser() + + parser.add_argument("-k", '--key', nargs=1, help="Path to the key file") + parser.add_argument("-r", '--repo', nargs=1, help="Address:Port of the repository") + parser.add_argument("-v", '--verbose', help="Increase verbosity", action="store_true") + parser.add_argument("-c", "--command", help="Command to execute") + parser.add_argument('arg0', nargs='?', default=None) + parser.add_argument('arg1', nargs='?', default=None) + parser.add_argument('arg2', nargs='?', default=None) + parser.add_argument('arg3', nargs='?', default=None) + parser.add_argument('arg4', nargs='?', default=None) + parser.add_argument('arg5', nargs='?', default=None) + + args = parser.parse_args() + if args.verbose: + logger.setLevel(logging.DEBUG) + logger.info('Setting log level to DEBUG') + + if args.key: + if not os.path.exists(args.key[0]) or not os.path.isfile(args.key[0]): + logger.error(f'Key file not found or invalid: {args.key[0]}') + sys.exit(-1) + + with open(args.key[0], 'r') as f: + state['REP_PUB_KEY'] = f.read() + logger.info('Overriding REP_PUB_KEY from command line') + + if args.repo: + state['REP_ADDRESS'] = args.repo[0] + logger.info('Overriding REP_ADDRESS from command line') + + #if args.command: + # logger.info("Command: " + args.command) + + return state#, {'command': args.command, 'arg0': args.arg0, 'arg1': args.arg1, 'arg2': args.arg2, 'arg3': args.arg3, 'arg4': args.arg4, 'arg5': args.arg5} + +def save(state): + state_dir = os.path.join(os.path.expanduser('~'), '.sio') + state_file = os.path.join(state_dir, 'state.json') + + if not os.path.exists(state_dir): + logger.debug('Creating state folder') + os.mkdir(state_dir) + + with open(state_file, 'w') as f: + f.write(json.dumps(state, indent=4)) + +#Main function for checking commands +def main(args): + + state = load_state() + state = parse_env(state) + #state, args = parse_args(state) + state = parse_args(state) + + if 'REP_ADDRESS' not in state: + logger.error("Must define Repository Address") + sys.exit(-1) + + # if 'REP_PUB_KEY' not in state: + # logger.error("Must set the Repository Public Key") + # sys.exit(-1) + + save(state) + + return state + +if __name__ == '__main__': + main(sys.argv)