Requests implemented (tests and revision needed)

This commit is contained in:
JoaoBastos023 2024-11-20 01:46:57 +00:00
parent b6c57ed294
commit 68e41e9ed2
16 changed files with 351 additions and 119 deletions

View File

@ -6,7 +6,6 @@ import requests
import json import json
import argparse import argparse
sys.path.append(os.path.abspath("../"))
from subject import main from subject import main
logging.basicConfig(format='%(levelname)s\t- %(message)s') logging.basicConfig(format='%(levelname)s\t- %(message)s')
@ -15,6 +14,8 @@ logger.setLevel(logging.INFO)
state = main(sys.argv) state = main(sys.argv)
BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/')
#session file - username #session file - username
def activateSubject(args): def activateSubject(args):
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
@ -32,13 +33,16 @@ def activateSubject(args):
logger.error("Need session file and username.") logger.error("Need session file and username.")
sys.exit(-1) 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.") logger.error("File '" + args.session + "' not found.")
sys.exit(-1) 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: 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() req.raise_for_status()
except requests.exceptions.RequestException as errex: except requests.exceptions.RequestException as errex:
logger.error("Failed to obtain response from server.") logger.error("Failed to obtain response from server.")

View File

@ -6,10 +6,11 @@ import requests
import json import json
import argparse import argparse
sys.path.append(os.path.abspath("../"))
from subject import main 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') logging.basicConfig(format='%(levelname)s\t- %(message)s')
logger = logging.getLogger() logger = logging.getLogger()
@ -17,6 +18,8 @@ logger.setLevel(logging.INFO)
state = main(sys.argv) state = main(sys.argv)
BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/')
# session file - document name - file # session file - document name - file
def addDoc(args): def addDoc(args):
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
@ -35,33 +38,55 @@ def addDoc(args):
logger.error("Need session file, document's name and file to upload.") logger.error("Need session file, document's name and file to upload.")
sys.exit(-1) 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.") logger.error("File '" + args.session + "' not found.")
sys.exit(-1) 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") logger.error("File '" + args.file + "' not found")
sys.exit(-1) sys.exit(-1)
# Get pub key #Get session file content
pubkey = encryption_functs.load_public_key(state['PUB_KEY']) with open(os.path.join(BASE_DIR, args.session), 'r') as f:
args.session = json.load(f)
#encrypt content
with open(args.file, 'rb') as f:
content = f.read()
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: 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() req.raise_for_status()
except requests.exceptions.RequestException as errex: except requests.exceptions.RequestException as errex:
logger.error("Failed to obtain response from server.") logger.error("Failed to obtain response from server.")
sys.exit(1) 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) sys.exit(0)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -6,7 +6,6 @@ import requests
import json import json
import argparse import argparse
sys.path.append(os.path.abspath("../"))
from subject import main from subject import main
from lib import encryption_functs from lib import encryption_functs
@ -17,6 +16,8 @@ logger.setLevel(logging.INFO)
state = main(sys.argv) state = main(sys.argv)
BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/')
# session file - username - name - email - credentials file # session file - username - name - email - credentials file
def addSubject(args): def addSubject(args):
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
@ -33,22 +34,26 @@ def addSubject(args):
args = parser.parse_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.") logger.error("Need session file, username, name, email and credentials file.")
sys.exit(-1) 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.") logger.error("File '" + args.session + "' not found.")
sys.exit(-1) 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") logger.error("File '" + args.file + "' not found")
sys.exit(-1) 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: 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() req.raise_for_status()
except requests.exceptions.RequestException as errex: except requests.exceptions.RequestException as errex:

View File

@ -10,9 +10,8 @@ import argparse
sys.path.append(os.path.abspath("../")) sys.path.append(os.path.abspath("../"))
from subject import main 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') logging.basicConfig(format='%(levelname)s\t- %(message)s')
logger = logging.getLogger() logger = logging.getLogger()
@ -20,6 +19,8 @@ logger.setLevel(logging.INFO)
state = main(sys.argv) state = main(sys.argv)
BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/')
# Create organization # Create organization
# organization - username - name - email - public key file # organization - username - name - email - public key file
def createOrganization(args): def createOrganization(args):
@ -34,12 +35,11 @@ def createOrganization(args):
parser.add_argument('username', nargs='?', default=None) parser.add_argument('username', nargs='?', default=None)
parser.add_argument('name', nargs='?', default=None) parser.add_argument('name', nargs='?', default=None)
parser.add_argument('email', 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() args = parser.parse_args()
#Validate num of arguments if not args.org or not args.username or not args.name or not args.email or not args.pubkey:
if len(args) != 5:
logger.error("Need organization, username, name, email and key file.") logger.error("Need organization, username, name, email and key file.")
sys.exit(-1) sys.exit(-1)
@ -49,21 +49,21 @@ def createOrganization(args):
sys.exit(-1) sys.exit(-1)
# Validate key file # Validate key file
if (not os.path.isfile(args.key)): if (not os.path.isfile(BASE_DIR + args.pubkey)):
logger.error("File '" + args.key + "' not found.") logger.error("File '" + args.pubkey + "' not found.")
sys.exit(-1) sys.exit(-1)
# load public key from file # 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} input = {'name' : args.org, 'username' : args.username, 'full_name' : args.name, 'email' : args.email, 'public_key' : pubKey}
try: 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() req.raise_for_status()
except requests.exceptions.RequestException as errex: except requests.exceptions.RequestException as errex:
logger.error("Failed to obtain response from server.") logger.error("Failed to obtain response from server.")
sys.exit(1) sys.exit(1)
if __name__ == '__main__': if __name__ == '__main__':
createOrganization(sys.argv[1:]) createOrganization(sys.argv[1:])

View File

@ -6,7 +6,6 @@ import logging
import json import json
import requests import requests
sys.path.append(os.path.abspath("../"))
from subject import main from subject import main
# Identity attributes # Identity attributes
@ -18,6 +17,8 @@ logger.setLevel(logging.INFO)
state = main(sys.argv) state = main(sys.argv)
BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/')
# org - username - password - credentials file - session file # org - username - password - credentials file - session file
def createSession(args): def createSession(args):
@ -35,25 +36,27 @@ def createSession(args):
args = parser.parse_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") logger.error("Need organization, username, password, credentials and session file")
sys.exit(-1) 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.") logger.error("File '" + args.credentials + "' not found.")
sys.exit(-1) sys.exit(-1)
session = {'org' : args.org, 'username' : args.username, 'password' : args.password, 'credentials_file' : args.credentials} session = {'org' : args.org, 'username' : args.username, 'password' : args.password, 'credentials_file' : args.credentials}
#print( type(json.dumps(session)))
try: 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() req.raise_for_status()
except requests.exceptions.RequestException as errex: except requests.exceptions.RequestException as errex:
logger.error("Failed to obtain response from server") logger.error("Failed to obtain response from server")
sys.exit(1) sys.exit(1)
with open(args.session, 'w') as f: with open(BASE_DIR + args.session, 'w') as f:
f.write(json.dumps(req)) f.write(req.json())
if __name__ == '__main__': if __name__ == '__main__':
createSession(sys.argv[1:]) createSession(sys.argv[1:])

View File

@ -3,13 +3,16 @@ import os
import sys import sys
import logging import logging
import argparse import argparse
import json
from lib import decryption_functs from lib import symmetric_encryption
logging.basicConfig(format='%(levelname)s\t- %(message)s') logging.basicConfig(format='%(levelname)s\t- %(message)s')
logger = logging.getLogger() logger = logging.getLogger()
logger.setLevel(logging.INFO) logger.setLevel(logging.INFO)
BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/')
#send to stdout contents of decrypted file #send to stdout contents of decrypted file
# encrypted file - encryption metadata # encrypted file - encryption metadata
def decryptFile(args): def decryptFile(args):
@ -26,19 +29,19 @@ def decryptFile(args):
sys.exit(-1) sys.exit(-1)
# If first argument is not a file or not found # 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.") logger.error("File '" + args.encrypted + "' not found.")
sys.exit(-1) 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.") logger.error("File '" + args.metadata + "' not found.")
sys.exit(-1) sys.exit(-1)
#Decrypt file #Decrypt file
with open(args.encrypted, 'rb') as f: metadata = json.loads(BASE_DIR + args.metadata)
content = f.read() salt = metadata['salt']
content = decryption_functs.decrypt_file('privateKey', content) content = symmetric_encryption.decrypt_file(metadata['password'], args.encrypted)
# Send decrypted content to stdout # Send decrypted content to stdout
sys.stdout.write(content) sys.stdout.write(content)

View File

@ -5,8 +5,8 @@ import logging
import requests import requests
import json import json
import argparse import argparse
from lib import digest
sys.path.append(os.path.abspath("../"))
from subject import main from subject import main
logging.basicConfig(format='%(levelname)s\t- %(message)s') logging.basicConfig(format='%(levelname)s\t- %(message)s')
@ -15,6 +15,8 @@ logger.setLevel(logging.INFO)
state = main(sys.argv) state = main(sys.argv)
BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/')
# session file - document name # session file - document name
def delDoc(args): def delDoc(args):
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
@ -32,13 +34,19 @@ def delDoc(args):
logger.error("Need session file and document's name.") logger.error("Need session file and document's name.")
sys.exit(-1) 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.") logger.error("File '" + args.session + "' not found.")
sys.exit(-1) 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: 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() req.raise_for_status()
except requests.exceptions.RequestException as errex: except requests.exceptions.RequestException as errex:

View File

@ -6,15 +6,18 @@ import requests
import json import json
import argparse import argparse
sys.path.append(os.path.abspath("../"))
from subject import main from subject import main
from lib import digest
logging.basicConfig(format='%(levelname)s\t- %(message)s') logging.basicConfig(format='%(levelname)s\t- %(message)s')
logger = logging.getLogger() logger = logging.getLogger()
logger.setLevel(logging.INFO) logger.setLevel(logging.INFO)
state = main(sys.argv) state = main(sys.argv)
BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/')
# session file - document name - output file(optional) # session file - document name - output file(optional)
def getDoc(args): def getDoc(args):
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
@ -33,25 +36,55 @@ def getDoc(args):
logger.error("Need session file and document's name.") logger.error("Need session file and document's name.")
sys.exit(-1) 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.") logger.error("File '" + args.session + "' not found.")
sys.exit(-1) 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: try:
req = requests.post(f'http://{state['REP_ADDRESS']}/file/get', json=json.dumps(doc)) metadata = requests.post(f'http://{state['REP_ADDRESS']}/file/' + doc_name, headers={'Authorization': args.session['token']})
req.raise_for_status() metadata.raise_for_status()
except requests.exceptions.RequestException as errex: except requests.exceptions.RequestException as errex:
logger.error("Failed to obtain response from server.") logger.error("Failed to obtain response from server.")
sys.exit(1) 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: if args.output:
with open(args.output, 'w') as f: with open(BASE_DIR + args.output, 'w') as f:
f.write(req) f.write(file)
else: else:
sys.stdout.write(req) sys.stdout.write(file)
sys.exit(0) sys.exit(0)

View File

@ -5,8 +5,8 @@ import logging
import requests import requests
import json import json
import argparse import argparse
from lib import digest
sys.path.append(os.path.abspath("../"))
from subject import main from subject import main
logging.basicConfig(format='%(levelname)s\t- %(message)s') logging.basicConfig(format='%(levelname)s\t- %(message)s')
@ -15,7 +15,7 @@ logger.setLevel(logging.INFO)
state = main(sys.argv) state = main(sys.argv)
print(state) BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/')
# session file - document name # session file - document name
def getDocMetadata(args): def getDocMetadata(args):
@ -35,21 +35,27 @@ def getDocMetadata(args):
logger.error("Need session file and document's name.") logger.error("Need session file and document's name.")
sys.exit(-1) 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.") logger.error("File '" + args.session + "' not found.")
sys.exit(-1) 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: try:
req = requests.post(f'http://{state['REP_ADDRESS']}/file/metadata', json=json.dumps(doc)) metadata = requests.post(f'http://{state['REP_ADDRESS']}/file/' + doc_name + '/metadata', headers={'Authorization': args.session['token']})
req.raise_for_status() metadata.raise_for_status()
except requests.exceptions.RequestException as errex: except requests.exceptions.RequestException as errex:
logger.error("Failed to obtain response from server.") logger.error("Failed to obtain response from server.")
sys.exit(1) sys.exit(1)
sys.stdout.write(req) metadata = metadata.json()
sys.stdout.write(metadata)
if __name__ == '__main__': if __name__ == '__main__':
getDocMetadata(sys.argv[1:]) getDocMetadata(sys.argv[1:])

View File

@ -6,7 +6,6 @@ import json
import requests import requests
import argparse import argparse
sys.path.append(os.path.abspath("../"))
from subject import main from subject import main
# Identity attributes # Identity attributes
@ -18,6 +17,8 @@ logger.setLevel(logging.INFO)
state = main(sys.argv) state = main(sys.argv)
BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/')
#get file #get file
#file handle - file(optonal) #file handle - file(optonal)
def getFile(args): def getFile(args):
@ -37,26 +38,24 @@ def getFile(args):
logger.error("Need a file handle.") logger.error("Need a file handle.")
sys.exit(-1) sys.exit(-1)
else: else:
if not os.path.isfile(args.filehandle): if not os.path.isfile(BASE_DIR + args.filehandle):
logger.error("File '" + args.filehandle + "' not found" ) logger.error("File '" + args.filehandle + "' not found" )
#Get file
try: 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() file.raise_for_status()
except requests.exceptions.RequestException as errex: except requests.exceptions.RequestException as errex:
logger.error("Failed to obtain response from server.") logger.error("Failed to obtain response from server.")
sys.exit(1) sys.exit(1)
file = json.loads(file) file = file.json()
# decrypt file
content = '' #decrypt(file.encode('utf-8'))
if not args.file: if not args.file:
sys.stdout.write(content) sys.stdout.write(file)
else: else:
with open(args.file, "wb") as f: with open(BASE_DIR + args.file, "wb") as f:
f.write(content) f.write(file)
if __name__ == '__main__': if __name__ == '__main__':
getFile(sys.argv[1:]) getFile(sys.argv[1:])

View File

@ -7,7 +7,6 @@ import json
import argparse import argparse
import datetime import datetime
sys.path.append(os.path.abspath("../"))
from subject import main from subject import main
logging.basicConfig(format='%(levelname)s\t- %(message)s') logging.basicConfig(format='%(levelname)s\t- %(message)s')
@ -16,13 +15,17 @@ logger.setLevel(logging.INFO)
state = main(sys.argv) state = main(sys.argv)
def validDate(date): BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/')
def validDate(input):
try: try:
datetime.datetime.strptime(input,"%d/%m/%Y") date = datetime.datetime.strptime(input,"%d/%m/%Y")
except ValueError as err: except ValueError as err:
logger.error("Date is invalid. Input format: DD/MM/YYYY") logger.error("Date is invalid. Input format: DD/MM/YYYY")
sys.exit(-1) sys.exit(-1)
return date
#session file - [-s username] [-d nt/ot/et date] #session file - [-s username] [-d nt/ot/et date]
def list_docs(args): def list_docs(args):
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
@ -41,71 +44,80 @@ def list_docs(args):
# Check if session file is valid # Check if session file is valid
if args.session: 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.") logger.error("File '" + args.session + "' not found.")
sys.exit(-1) sys.exit(-1)
else: else:
logger.error("Need session file.") logger.error("Need session file.")
sys.exit(-1) sys.exit(-1)
# Get session file content
with open(BASE_DIR + args.session, 'r') as f:
args.session = json.load(f)
if args.newerThan: 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: try:
subjects = requests.get(f'http://{state['REP_ADDRESS']}/file/list', subjects = requests.get(f'http://{state['REP_ADDRESS']}/file/list',
json=json.dumps({'session_file' : args.session, 'username' : args.username, json=json.dumps({'username' : args.username,'datetime' : {'value' : args.newerThan, 'relation' : 'nt'}}),
'datetime' : {'value' : args.newerThan, 'relation' : 'nt'} headers={'Authorization': args.session['token']})
}))
subjects.raise_for_status() subjects.raise_for_status()
except requests.exceptions.RequestException as errex: except requests.exceptions.RequestException as errex:
logger.error("Failed to obtain response from server.") logger.error("Failed to obtain response from server.")
sys.exit(1) sys.exit(1)
subjects = json.loads(subjects) subjects = subjects.json()
elif args.equalTo: 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: try:
subjects = requests.get(f'http://{state['REP_ADDRESS']}/file/list', subjects = requests.get(f'http://{state['REP_ADDRESS']}/file/list',
json=json.dumps({'session_file' : args.session, 'username' : args.username, json=json.dumps({'username' : args.username,
'datetime' : {'value' : args.equalTo, 'relation' : 'eq'} 'datetime' : {'value' : args.equalTo, 'relation' : 'eq'}}),
})) headers={'Authorization': args.session['token']})
subjects.raise_for_status() subjects.raise_for_status()
except requests.exceptions.RequestException as errex: except requests.exceptions.RequestException as errex:
logger.error("Failed to obtain response from server.") logger.error("Failed to obtain response from server.")
sys.exit(1) sys.exit(1)
subjects = json.loads(subjects) subjects = subjects.json()
elif args.olderThan: 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: try:
subjects = requests.get(f'http://{state['REP_ADDRESS']}/file/list', subjects = requests.get(f'http://{state['REP_ADDRESS']}/file/list',
json=json.dumps({'session_file' : args.session, 'username' : args.username, json=json.dumps({'username' : args.username,
'datetime' : {'value' : args.olderThan, 'relation' : 'ot'} 'datetime' : {'value' : args.olderThan, 'relation' : 'ot'}}),
})) headers={'Authorization': args.session['token']})
subjects.raise_for_status() subjects.raise_for_status()
except requests.exceptions.RequestException as errex: except requests.exceptions.RequestException as errex:
logger.error("Failed to obtain response from server.") logger.error("Failed to obtain response from server.")
sys.exit(1) sys.exit(1)
subjects = json.loads(subjects) subjects = subjects.json()
else: else:
try: 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() subjects.raise_for_status()
except requests.exceptions.RequestException as errex: except requests.exceptions.RequestException as errex:
logger.error("Failed to obtain response from server.") logger.error("Failed to obtain response from server.")
sys.exit(1) sys.exit(1)
subjects = json.loads(subjects) subjects = subjects.json()
for s in subjects: for s in subjects:
sys.stdout.write(s['id'] + " - " + s['username']) sys.stdout.write(s['id'] + " - " + s['username'])

View File

@ -5,7 +5,6 @@ import logging
import json import json
import requests import requests
sys.path.append(os.path.abspath("../"))
from subject import main from subject import main
# Identity attributes # Identity attributes
@ -19,15 +18,15 @@ state = main(sys.argv)
def listOrganizations(): def listOrganizations():
try: 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() orgs.raise_for_status()
except requests.exceptions.RequestException as errex: except requests.exceptions.RequestException as errex:
logger.error("Failed to obtain response from server.") logger.error("Failed to obtain response from server.")
sys.exit(1) sys.exit(1)
for org in orgs: for org in orgs.json():
sys.stdout.write(org['id'] + " - " + org['name']) sys.stdout.write(str(org['id']) + " - " + org['name'])
if __name__ == '__main__': if __name__ == '__main__':
listOrganizations(sys.argv[1:]) listOrganizations()

View File

@ -6,7 +6,6 @@ import requests
import json import json
import argparse import argparse
sys.path.append(os.path.abspath("../"))
from subject import main from subject import main
logging.basicConfig(format='%(levelname)s\t- %(message)s') logging.basicConfig(format='%(levelname)s\t- %(message)s')
@ -15,6 +14,8 @@ logger.setLevel(logging.INFO)
state = main(sys.argv) state = main(sys.argv)
BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/')
# session file - username(optional) # session file - username(optional)
def list_subjects(args): def list_subjects(args):
@ -30,14 +31,23 @@ def list_subjects(args):
args = parser.parse_args() args = parser.parse_args()
# Check if session file is valid # Check if session file is valid
if (not os.path.isfile(args.session)): if args.session:
logger.error("File '" + args.session + "' not found.") 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) sys.exit(-1)
# Get session file content
with open(BASE_DIR + args.session, 'r') as f:
args.session = json.load(f)
if args.username: if args.username:
try: try:
subjects = json.loads(requests.get(f'http://{state['REP_ADDRESS']}/user/list', subjects = requests.get(f'http://{state['REP_ADDRESS']}/user/list',
json=json.dumps({'session_file' : args.session, 'username' : args.username}))) json=json.dumps({'username' : args.username}),
headers={'Authorization': args.session['token']})
subjects.raise_for_status() subjects.raise_for_status()
except requests.exceptions.RequestException as errex: except requests.exceptions.RequestException as errex:
@ -46,15 +56,15 @@ def list_subjects(args):
else: else:
try: try:
subjects = json.loads(requests.get(f'http://{state['REP_ADDRESS']}/user/list'), subjects = requests.get(f'https://{state['REP_ADDRESS']}/user/list',
json=json.dumps({'session_file' : args.session})) headers={'Authorization': args.session['token']})
subjects.raise_for_status() subjects.raise_for_status()
except requests.exceptions.RequestException as errex: except requests.exceptions.RequestException as errex:
logger.error("Failed to obtain response from server.") logger.error("Failed to obtain response from server.")
sys.exit(1) sys.exit(1)
for s in subjects: for s in subjects.json():
sys.stdout.write(s['id'] + " - " + s['username']) sys.stdout.write(s['id'] + " - " + s['username'])

View File

@ -4,12 +4,15 @@ import sys
import logging import logging
import argparse import argparse
sys.path.append(os.path.abspath("../../"))
from lib import key_pair from lib import key_pair
logging.basicConfig(format='%(levelname)s\t- %(message)s') logging.basicConfig(format='%(levelname)s\t- %(message)s')
logger = logging.getLogger() logger = logging.getLogger()
logger.setLevel(logging.INFO) logger.setLevel(logging.INFO)
BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/')
# Generate a key pair for a subject # Generate a key pair for a subject
# password - file for public key, file for private key # password - file for public key, file for private key
def generateKeyPair(args): def generateKeyPair(args):
@ -22,17 +25,13 @@ def generateKeyPair(args):
args = parser.parse_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") logger.error("Need password and file to store keys")
sys.exit(-1) sys.exit(-1)
#Generate the key pair #Generate the key pair
key_pair.generate_key_pair(args.pubfile, args.privfile, 2048, args.password) key_pair.generate_key_pair(BASE_DIR + args.pubfile, BASE_DIR + args.privfile, 2048, args.password)
#Save key files in environment
os.environ['PRIV_KEY'] = args.privfile
os.environ['PUB_KEY'] = args.pubfile
return 0 return 0

View File

@ -15,6 +15,8 @@ logger.setLevel(logging.INFO)
state = main(sys.argv) state = main(sys.argv)
BASE_DIR= os.path.join(os.path.expanduser('~'), '.sio/')
# session file - username # session file - username
def suspendSubject(args): def suspendSubject(args):
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
@ -32,12 +34,20 @@ def suspendSubject(args):
logger.error("Need session file and username.") logger.error("Need session file and username.")
sys.exit(-1) 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.") logger.error("File '" + args.session + "' not found.")
sys.exit(-1) sys.exit(-1)
subject = {'session_file' : args.session, 'username' : args.username} # Get session file content
req = requests.post(f'http://{state['REP_ADDRESS']}/user/suspend', json=json.dumps(subject)) 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__': if __name__ == '__main__':
suspendSubject(sys.argv[1:]) suspendSubject(sys.argv[1:])

View File

@ -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)