class TestuserData(unittest.TestCase):
    def setUp(self):
        """
        set up method
        """
        self.new_user = UserData("cliff", "kasera", "*****@*****.**",
                                 "Blankphrase", "lololo")

    def test_init(self):
        """
        testing initialization of class
        """
        self.assertEqual(self.new_user.firstName, "cliff")
        self.assertEqual(self.new_user.lastName, "kasera")
        self.assertEqual(self.new_user.email, "*****@*****.**")
        self.assertEqual(self.new_user.username, "Blankphrase")
        self.assertEqual(self.new_user.password, "lololo")

    def tearDown(self):
        """
        restart
        """
        UserData.create_account = []

    def test_save_account(self):
        """
        testing save account method
        """
        self.new_user.save_account()
        self.assertEqual(len(UserData.create_account), 1)
Пример #2
0
class TestuserData(unittest.TestCase):
    def setUp(self):
        """
        set up method
        """
        self.new_user = UserData("Teresa", "Wanjiku", "*****@*****.**", "Terry", "rosa2d") 

    def test_init(self):
        """
        testing initialization of class
        """
        self.assertEqual(self.new_user.firstName, "Teresa")
        self.assertEqual(self.new_user.lastName, "Wanjiku")
        self.assertEqual(self.new_user.email, "*****@*****.**")
        self.assertEqual(self.new_user.username, "Terry")
        self.assertEqual(self.new_user.password, "rosa2d")

    def tearDown(self):
        """
        restart
        """
        UserData.create_account = []

    def test_save_account(self):
        """
        testing save account method
        """
        self.new_user.save_account() 
        self.assertEqual(len(UserData.create_account), 1)
Пример #3
0
 def setUp(self):
     """
     set up method
     """
     self.new_user = UserData("clifford", "ochieng",
                              "*****@*****.**",
                              "cliffochieng", "yoloyolo")
Пример #4
0
def check_user(used_name, used_password):
    """
    checks if user exists
    """
    user_exists = UserData.user_login(used_name, used_password)

    return user_exists
Пример #5
0
class MainStartWin(QtGui.QMainWindow, Ui_StartWindow):
    def __init__(self, parent=None):
        super(MainStartWin, self).__init__(parent)
        self.setupUi(self)
        self.eventHandlerSetup()
        self.userData = UserData()
        #self.localZot = LocalZot()
        
        if (self.userData.getValue('GENERAL', 'apikey') == ''):
            QtGui.QMessageBox.warning(self, "Missing API Key", "Please enter your API/Library key under preferences")
            #self.btn_OpenBatchEditor.setEnabled(False)
            #self.btn_OpenCitationEditor.setEnabled(False)
            #self.btn_OpenCoupleDocuments.setEnabled(False)

    def eventHandlerSetup(self):
        self.btn_OpenBatchEditor.clicked.connect(lambda: self.openWindow(BatchEditorWin(self)))
        self.btn_OpenCitationEditor.clicked.connect(lambda: self.openWindow(CitationEditorWin(self)))
        self.btn_OpenCoupleDocuments.clicked.connect(lambda: self.openWindow(CoupleDocumentsWin(self)))
        #self.btn_OpenCoupleDocuments.clicked.connect(lambda: self.testuserdata())
        self.actionPreferences.triggered.connect(lambda: self.openWindow(PreferencesWin(self)))
        self.btn_Prefs.clicked.connect(lambda: self.openWindow(PreferencesWin(self)))
        self.btn_Quit.clicked.connect(lambda: sys.exit(0))

    def openWindow(self, window):
        window.show()
Пример #6
0
class BEditor:
    """ class used for batch editing"""

    def __init__(self, user_id='', user_type='user', api_key=''):
        ''' intialize a new batch editor '''
        #this is the file used to save user data
        self._pickle_save = 'user_data'
        self.userData = UserData()
        #data for accessing zotero library
        #self._userData = {"user_id": user_id, "user_type": user_type, "api_key": api_key}

        #check if we have a pickle that already contains user info
        #if so load that data from pickle
        #if (self.chksave()):
        #   self._pickle = Pickler(self._pickle_save)
        #   self._userData = pickle.load()
        #print(self.userData.getValue('GENERAL', 'libraryid'))
        #initialize a connection to library and validate connection
        try:
            self._zot = zotero.Zotero(self.userData.getValue('GENERAL', 'libraryid'), 'user', self.userData.getValue('GENERAL', 'apikey'))
            # self._zot = zotero.Zotero('2710002', 'user', 'jxIEnHTfXW5guwz6X8q5upsv')

        except Exception, err:
            raise
        self.test_config()
Пример #7
0
 def __init__(self, parent=None):
     super(PreferencesWin, self).__init__(parent)
     self.setupUi(self)
     self.userData = UserData()
     self.txt_apiKey.setText(self.userData.getValue('GENERAL', 'apikey'))
     self.txt_LibraryID.setText(self.userData.getValue('GENERAL', 'libraryid'))
     self.eventHandlerSetup()
Пример #8
0
def new_users(name_one, name_two, email_address, user_name, pass_word):
    """
    creates new user 
    """
    new_user = UserData(name_one, name_two, email_address, user_name,
                        pass_word)

    return new_user
Пример #9
0
def new_users(name_first, name_two, email_adress, user_name, pass_word):
    """
    It creates a new user
    """
    new_user = UserData(name_first, name_two,
                        email_adress, user_name, pass_word)

    return new_user
Пример #10
0
 def __init__(self, parent=None):
     super(MainStartWin, self).__init__(parent)
     self.setupUi(self)
     self.eventHandlerSetup()
     self.userData = UserData()
     #self.localZot = LocalZot()
     
     if (self.userData.getValue('GENERAL', 'apikey') == ''):
         QtGui.QMessageBox.warning(self, "Missing API Key", "Please enter your API/Library key under preferences")
Пример #11
0
class PreferencesWin(QtGui.QMainWindow, Ui_PreferenceWindow):
    def __init__(self, parent=None):
        super(PreferencesWin, self).__init__(parent)
        self.setupUi(self)
        self.userData = UserData()
        self.txt_apiKey.setText(self.userData.getValue('GENERAL', 'apikey'))
        self.txt_LibraryID.setText(self.userData.getValue('GENERAL', 'libraryid'))
        self.eventHandlerSetup()

    def eventHandlerSetup(self):
        self.btn_cancel.clicked.connect(lambda: self.close())
        self.btn_ok.clicked.connect(lambda: self.saveData())
    
    def saveData(self):
        self.userData.setKeyValue('GENERAL', 'apikey', str(self.txt_apiKey.text()))
        self.userData.setKeyValue('GENERAL', 'libraryid', str(self.txt_LibraryID.text()))
        self.close()    
Пример #12
0
 def __init__(self):
     self.actions = {"register": self.request_register, "send": self.request_send_email, "login": self.request_login,
                     "get2": self.request_get_email, "get_key": self.request_get_key, "stop": self.request_stop,
                     "delete": self.request_delete}
     self.ud = UserData("user_data.csv")
     self.sm = SendMail()
Пример #13
0
class Requests:

    def __init__(self):
        self.actions = {"register": self.request_register, "send": self.request_send_email, "login": self.request_login,
                        "get2": self.request_get_email, "get_key": self.request_get_key, "stop": self.request_stop,
                        "delete": self.request_delete}
        self.ud = UserData("user_data.csv")
        self.sm = SendMail()

    def handle(self, req, token=None):
        request = req.split(",")
        action = request[0]
        params = request[1:]
        if token:
            params.append(token)
        return self.actions[action](params)

    # checks if a user already have a pair of keys
    @staticmethod
    def has_keys(user):
        path_to_private = "keys/%s/private.pem" % user
        path_to_public = "keys/%s/public.pem" % user
        return os.path.exists(path_to_private) and os.path.exists(path_to_public)

    # create a pair of RSA keys for a user
    @staticmethod
    def gen_keys(user):
        path_to_keys = "keys/%s" % user
        path_to_private = "keys/%s/private.pem" % user
        path_to_public = "keys/%s/public.pem" % user
        if not os.path.exists(path_to_keys):
            os.makedirs(path_to_keys)
        key = RSA.generate(2048)
        private_key = key.export_key()
        file_out = open(path_to_private, "wb")
        file_out.write(private_key)
        public_key = key.publickey().export_key()
        file_out = open(path_to_public, "wb")
        file_out.write(public_key)
        print("[INFO] RSA keys generated !")

    # Overwrites a file with an eencrypted version
    @staticmethod
    def encrypt_file(file_path, public_key_path):
        data = open(file_path).read().encode("utf-8")
        enc_file_path = file_path
        file_out = open(enc_file_path, "wb")
        recipient_key = RSA.import_key(open(public_key_path).read())
        session_key = get_random_bytes(16)

        # Encrypt the session key with the public RSA key
        cipher_rsa = PKCS1_OAEP.new(recipient_key)
        enc_session_key = cipher_rsa.encrypt(session_key)

        # Encrypt the data with the AES session key
        cipher_aes = AES.new(session_key, AES.MODE_EAX)
        ciphertext, tag = cipher_aes.encrypt_and_digest(data)
        [file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext)]
        file_out.close()
        return enc_file_path

    @staticmethod
    def request_stop(params):
        return {"success": True, "stop": True, "Reason": "stop requested"}

    # params[0] should be email address and params[1] should be pswd
    def request_register(self, params):
        res = {}
        token_length = 16
        if len(params) == 2:
            res = self.ud.appendfile(params[0], params[1])
            if not self.has_keys(params[0]):
                self.gen_keys(params[0])
            res["file_token"] = self.generate_token(token_length)
            # res["token_length"] = token_length
            res["user"] = params[0]
        else:
            res["success"] = False
            res["reason"] = "register request should have 2 arguments: email address and password"
        return res

    # Removes all data concerning an user
    def request_delete(self, params):
        res = {}
        if len(params) == 2:
            if self.ud.authorize(params[0], params[1]):
                print("[INFO] Deleting data of user %s ..." % params[0])
                for folder in ("fr_data", "keys", "mail"):
                    folder_to_remove = folder + "/" + params[0]
                    if os.path.exists(folder_to_remove):
                        shutil.rmtree(folder_to_remove)
                self.ud.remove_entry(params[0])
                print("[INFO] Done !")
                res["success"] = True
            else:
                res["success"] = False
                res["reason"] = "Invalid email address or password"
        else:
            res["success"] = False
            res["reason"] = "Invalid number of parameters, delete requires an email address and password"
        return res

    # params[0] should be recipient, params[1] subject and params[2] content
    def request_send_email(self, params):
        res = {}
        if len(params) == 3:
            recipient = params[0]
            recipient_hash = hashlib.sha256(recipient.encode()).hexdigest()
            subject = params[1]
            content = params[2]
            # TODO maybe put these in a file ...
            default_message = "You received a new secret message\nDownload the receiving app to see it"
            default_subject = "New secret message"
            path_to_mail = "mail/" + recipient_hash

            # Create mail folder if it does not already exists
            if not os.path.exists(path_to_mail):
                os.makedirs(path_to_mail)
            # Assign an id to the email
            mail_id = 0
            list_dir = os.listdir(path_to_mail)
            while str(mail_id) in list_dir:
                mail_id += 1
            mail_id = str(mail_id)

            path_to_mail_id = path_to_mail + "/" + mail_id
            with open(path_to_mail_id, 'wb') as f:
                file_content = subject + "\n" + content
                f.write(file_content.encode('utf-8'))

            # send notification to recipient TODO reactivate after testing
            raw_msg = self.sm.create_message(self.sm.SENDER, recipient, default_subject, default_message)
            message = self.sm.send_message(self.sm.service, "me", raw_msg)
            # message = {"labelIds": ["SENT"], "id": "Test mode, no message sent"}
            if message is not None:
                if message["labelIds"][0] == "SENT":
                    if not self.has_keys(recipient_hash):
                        self.gen_keys(recipient_hash)
                    path_to_key = "keys/%s/public.pem" % recipient_hash
                    # encrypt email with recipient's public key
                    self.encrypt_file(path_to_mail_id, path_to_key)
                    res["success"] = True
                    res["reason"] = "Message " + message["labelIds"][0] + " Id: " + message["id"]
                else:
                    res["success"] = False
                    res["reason"] = "Message " + message["labelIds"][0] + " Id: " + message["id"]
                    os.remove(path_to_mail_id)
            else:
                res["reason"] = "Message could not be sent"
                res["success"] = False
                os.remove(path_to_mail_id)
        else:
            res["success"] = False
            res["reason"] = "send request should have 3 arguments: recipient email address, subject and content"
        return res

    # this should be the "final" get email function (at least in the unencrypted version of the project)
    # params[0] should be recipient, params[1] pswd, params[2] received token, params[3] security token
    def request_get_email(self, params):
        res = {}
        if len(params) == 4:
            if params[2] == params[3]:
                pswd = params[1]
                recipient = params[0]
                if self.ud.authorize(recipient, pswd):
                    path_to_mail = "mail/" + recipient
                    path_to_face_model = "fr_data/" + recipient + "/" + recipient + ".zip"
                    if os.path.exists(path_to_face_model):
                        if os.path.exists(path_to_mail):
                            res["success"] = True
                            # zip all the mail and the face recognition data in the same archive
                            # this is not secure at all, in version 2 messages will be encrypted or sent separately
                            zipname = "%s_fr+mail.zip" % recipient
                            with zipfile.ZipFile(zipname, 'w') as output_zip:
                                for file in os.listdir(path_to_mail):
                                    file_path = os.path.join(path_to_mail, file)
                                    print("[DEBUG] ", file_path)
                                    output_zip.write(file_path, file)
                                    # TODO delete messages after they've been sent (after testing)
                                    # os.remove(file_path)
                                output_zip.write(path_to_face_model, "fr_data.zip")
                            res["zipfile"] = zipname
                        else:
                            res["success"] = False
                            res["reason"] = "No message folder"
                    else:
                        res["success"] = False
                        res["reason"] = "No face recognition data, registration might not be complete"
                else:
                    res["success"] = False
                    res["reason"] = "Invalid password or email"
            else:
                res["success"] = False
                res["reason"] = "Invalid security token"
        else:
            res["success"] = False
            res["reason"] = "Invalid number of parameters"
        return res

    # params[0] is email address and params[1] is password
    def request_login(self, params):
        res = {}
        if len(params) == 2:
            if self.ud.authorize(params[0], params[1]):
                recipient = params[0]
                res["success"] = True
                path_to_mail = "mail/" + recipient
                if not os.path.exists(path_to_mail):
                    nb_of_unread_message = 0
                else:
                    nb_of_unread_message = len(os.listdir(path_to_mail))
                if nb_of_unread_message != 0:
                    res["reason"] = "you have " + str(nb_of_unread_message) + " unread email(s)"
                    res["number"] = nb_of_unread_message
                    # res["token"] = str(get_random_bytes(16))
                    res["token"] = self.generate_token(16)
                    print("[INFO] token: ", res["token"])
                else:
                    res["reason"] = "You do not have any unread email"
                    res["number"] = 0
            else:
                res["success"] = False
                res["reason"] = "Wrong email or password"
        else:
            res["success"] = False
            res["reason"] = "login request should have 2 arguments: email address and password"
        return res

    # params[0] should be email address, params[1] should be user's password, params[2] should be received token
    # params[3] should be security token
    def request_get_key(self, params):
        res = {}
        if len(params) == 4:
            email = params[0]
            pswd = params[1]
            received_token = params[2]
            security_token = params[3]
            if received_token == security_token:
                if self.ud.authorize(email, pswd):
                    path_to_key = "keys/%s/private.pem" % email
                    res["success"] = True
                    res["private_key"] = open(path_to_key, "rb").read()
                    res["reason"] = ""
                    # TODO activate key changing after testing is over ...
                    # print("[INFO] changing keys for this user")
                    # self.gen_keys(email)
                else:
                    res["success"] = False
                    res["reason"] = "Wrong password or email address"
            else:
                res["success"] = False
                res["reason"] = "Wrong security token"
        return res

    @staticmethod
    def generate_token(length=16):
        # Generate a random string of letters, digits and special characters
        characters = string.ascii_letters + string.digits
        return ''.join(random.choice(characters) for i in range(length))
Пример #14
0
 def __init__(self):
     self.userData = UserData()
Пример #15
0
 def setUp(self):
     """
     set up method
     """
     self.new_user = UserData("Teresa", "Wanjiku", "*****@*****.**", "Terry", "rosa2d") 
 def setUp(self):
     """
     set up method
     """
     self.new_user = UserData("cliff", "kasera", "*****@*****.**",
                              "Blankphrase", "lololo")
Пример #17
0
from userData import UserData
from firebase_admin import db

user1 = UserData(name=input("Name: "), email=input("Email: "), phone=input("Phone: "), age=input("Age: "))
if db._http_client == 1:
    print("")

print(user1.get_name())
print(user1.get_email())
print(user1.get_phone())
print(user1.get_age())
Пример #18
0
class CoupleDocuments:

    def __init__(self):
        self.userData = UserData()


    def config(self):
        ''' sets the user_id, user_type, and API Key so that program can
            access the user's zotero library. Gives the groupid to access
            the different groupids this user bleongs to
        '''
        self.uid = self.userData.getValue('GENERAL', 'libraryid')
        self.key = self.userData.getValue('GENERAL', 'apikey')


        if not (os.path.isfile('keys.json')):
            jsonFile = open('keys.json', 'w')
            jsonFile.close()

        self.zot = zotero.Zotero(self.uid, utype, self.key)

    def getCollections(self, groupId=''):
        '''returns the collections of the user in a dictionary, or the group corresponding
           to the Id of given one.
        '''
        if  not (groupId == ''):
            accessKey = zotero.Zotero(groupId, 'group', self.key)
        else:
            accessKey = self.zot

        returnCollections = {}



        for collection in accessKey.collections():
            returnCollections[collection['key']] = collection['data']['name']

        return returnCollections

    def getRecords(self, key, groupId=''):
        ''' gets the records of a chosen collection, or the group corresponding
            to the Id of the given one.
        '''

        if not (groupId == ''):
            accessKey = zotero.Zotero(groupId, 'group', self.key)
        else:
            accessKey = self.zot

        namesofRecords = {}

        if key == 'n/a':
            listofRecords = accessKey.top()

            for record in listofRecords:

                if record['data']['collections'] == []:
                    namesofRecords[record['data']['key']] = record['data']['title']
        else:

            listofRecords = accessKey.collection_items(key)

            for record in listofRecords:
                namesofRecords[record['data']['key']] = record['data']['title']

        return namesofRecords

    def getGroups(self):
        '''gives all of groups associated with the user
        '''
        listofGroups = self.zot.groups()
        groupAccessName = {}

        for group in listofGroups:
            groupAccessName[group['data']['id']] = group['data']['name']

        return groupAccessName

    def jsonFileUpdater(self, key, documentList):
        '''takes in a key of an original document and a list of dictionaries groups
           and files to be coupled in those groups. Creates a json file if it doesn't exist
           otherwise, searches through json to find the key to grab the list.
           updates the list with new coupled documents. Returns
           a list with the key.
        '''

        if (os.path.isfile('keys.json')):
            json_file = open('keys.json', 'r')
            json_str = json_file.read()
            json_dic = json.loads(json_str)


            #look for the record to be copied, if it exits, then we
            #update the list of dictionaries for that record
            for itemkey, value in json_dic.iteritems():
                if itemkey == key:
                    value = documentList

            json_file = open('keys.json', 'w')
        else:
            json_file = json_file = open('keys.json', 'w')
            json_dic = {key: documentList}



        json.dump(json_dic, json_file)


        return json_dic

    def jsonKeyGetter(self, key):
        '''Given a key, goes through the json file to find the corresponding
            list of keys
        '''


        json_file = open('keys.json', 'r')

        json_str = json.read()
        json_dic = json.loads(json_str)[0]

        json_file.close()

        for itemkey, value in json_dic.iteritems():
            if itemkey == key:
                return value

    def updateCoupledDocuments(self, key, documentsToChange):
        '''Given a key, and a dictionary of changes accesses the json file and updates the
           coupled documents corresponding to the original in the zotero database. Returns
           list of documents that don't have the right itemType
        '''

        coupledDocuments = self.jsonKeyGetter(key)

        #find the original document
        original = self.zot.item(key)

        #go through every document in coupleDocuments
        for document in coupledDocuments:
        #check their type is equal to original
            groupId = document.keys()[0]
            copy = self.groupAccess().item(document[document[groupId]])
            if copy[0]['itemType'] == original[0]['itemType']:
                itemType = copy[0]['itemType']
                validFields = self.zot.item_type_fields(itemType)[0]
                #if so, change all the fields to be the same as the original
                for field in validFields:
                    copy[0][field] = original[0][field]
                #update the copy
                zotgroup.update_item(copy[0])
            else:
            #if type is not equal, add it to a list to be sent back
                rejects.append(copy[0]['title'])

        jsonFileUpdater( key, documentsToChange)
        rejects = []

        return rejects