Esempio n. 1
0
    def test_40_load(self):
        """HistoriaUser: load()"""
        self.database_setup(withTables=True)
        hu1 = user.HistoriaUser(self.db)
        current_stamp = datetime.datetime.now()
        test_pass = "******"
        hu1.name = "Eric"
        hu1.password = test_pass
        hu1.email = "*****@*****.**"
        hu1.created = current_stamp
        hu1.last_access = current_stamp
        hu1.enabled = True
        hu1.admin = False
        hu1.save()

        hu2 = user.HistoriaUser(self.db)
        hu2.load(hu1.id)

        self.assertEqual(hu1.id, hu2.id, "IDs on original and loaded object don't match")
        self.assertFalse(hu2._dirty, "The dirty bit is wrong after load.")
        self.assertEqual(hu2, hu1, "The two copies of the record should consider themselves equal.")
        self.assertEqual(hu2.name, hu1.name, "name in the table should match the name on the record.")
        self.assertEqual(hu2.password, hu1.password, "password in the table should match the one on the record.")        
        self.assertEqual(hu2.email, hu1.email, "email in the table should match the one on the record.")        
        self.assertAlmostEqual(hu2.created, hu1.created, delta=datetime.timedelta(seconds=1), msg="created in the table should match the one on the record.")        
        self.assertAlmostEqual(hu2.last_access, hu1.last_access,  delta=datetime.timedelta(seconds=1), msg="last_access in the table should match the one on the record.")        
        self.assertEqual(hu2.enabled, hu1.enabled, "enabled in the table should match the one on the record.")        
        self.assertEqual(hu2.admin, hu1.admin, "admin in the table should match the one on the record.")        
        self.assertNotEqual(hu2.modified, hu1.modified, "modified in the table should not match the one on the record since that was setup by MySQL.")
Esempio n. 2
0
    def user_create(self, session, parameters, bypass=False):
        """Used for creating new users."""

        # this should only be used during install.
        if not bypass:
            # Check for user
            if not hasattr(session, '_user'):
                self.logger.error(
                    'Current session has no assicated user: {0}'.format(
                        session.id))
                raise InvalidSessionError(
                    "Current session has no assicated user: {0}".format(
                        session.id))

            # Verify the user is an admin
            if not session._user.admin:
                self.logger.notice(
                    'User {0} [{1}], attempted to create a new user.'.format(
                        session._user.name, session._user.id))
                raise InvalidPermissionsError(
                    "Must have admin rights to create users.")

        # Verify required parameters were provided
        for param in self.routers['system']['user']['create']['parameters']:
            if param not in parameters:
                self.logger.info(
                    "Attempt to create user without setting {0}".format(param))
                raise InvalidParametersError(
                    "No {0} provided when creating new user".format(param))

        new_user = user.HistoriaUser(self.database)

        return self._mod_user(new_user, parameters)
Esempio n. 3
0
    def authenticate_user(self, user_name, password):
        """Check the user_name and password. If it is a validate user, return
        user object."""
        if self.database is None:
            raise ControllerNotReady(
                "The controller is not fully configured, not database object.")

        if not self.database.connected:
            self.database.connect()
            if not self.database.connected:
                raise DatabaseNotReady('Cannot connect to database')

        search = core_data_objects.HistoriaDatabaseSearch(
            self.database, user.HistoriaUser.machine_type)

        search.add_field('id')
        search.add_condition('name', user_name)
        search.add_condition('email', user_name, '=', 'OR')
        search.add_limit(1)
        test_user = user.HistoriaUser(self.database)
        try:
            results = search.execute_search()
            test_user.load(results[0]['id'])
            if (test_user.checkPassword(password)):
                return test_user
            else:
                return False
        except:
            return False
Esempio n. 4
0
    def test_33_save(self):
        """HistoriaUser: save() with only the minimum required settings"""
        hu = user.HistoriaUser(self.db)

        self.assertRaises(exceptions.DataConnectionError, hu.save)

        # Setup the database and try again.
        self.database_setup(withTables=True)

        self.assertRaises(exceptions.DataSaveError, hu.save)

        current_stamp = datetime.datetime.now()
        hu.name = "Eric"
        hu.password = "******"
        hu.email = "*****@*****.**"
        hu.save()

        self.assertFalse(hu._dirty, "Dirty bit active after save")
        self.assertNotEqual(hu.id, -1, "Record ID still -1 after save.")

        # Now let's go see if it's really there
        select = ("SELECT * FROM `historia_user`",{})
        result = self.db.execute_select(select)

        self.assertEqual(len(result), 1, "There should be 1 and only 1 entry in the table.")
        self.assertEqual(result[0]['name'], hu.name, "name in the table should match the name on the record.")
        self.assertEqual(result[0]['password'], hu.password, "password in the table should match the one on the record.")        
        self.assertEqual(result[0]['email'], hu.email, "email in the table should match the one on the record.")        
        self.assertEqual(result[0]['enabled'], 1, "enabled in the table should match the one on the record.")        
        self.assertEqual(result[0]['admin'], 0, "admin in the table should match the one on the record.")        
Esempio n. 5
0
 def test_20_password(self):
     """HistoriaUser: Test password comparison"""
     hu = user.HistoriaUser(self.db)
     
     sample_pass = "******"
     
     hu.password = sample_pass
     
     self.assertNotEqual(hu.password, sample_pass, "Password failed to hash")
     self.assertTrue(hu.checkPassword(sample_pass), "Password checking failed")
Esempio n. 6
0
 def test_60_to_dict(self):
     """HistoriaUser: make sure password is not provided by to_dict()"""
     
     hu = user.HistoriaUser(self.db)
     
     sample_pass = "******"
     
     hu.password = sample_pass
     
     my_dict = hu.to_dict()
     
     self.assertFalse('password' in my_dict, "Password present in user dictionary.")
Esempio n. 7
0
    def test_10_internals(self):
        """HistoriaUser: __setattr__"""
        hu = user.HistoriaUser(self.db)

        with self.assertRaises(AttributeError):
            hu.bogus_field = "Junk Data"
        
        attrs = ['email', 'name', 'created', 'last_access', 'password']
        
        # All of the listed fields on a User should raise a ValueError when they are fed an integer
        for attr in attrs:
            with self.assertRaises(ValueError):
                setattr(hu, attr, 123243)
            
        
        hu._anything = "ok"
        self.assertEqual(hu._anything, "ok", "Assignment of _ variables works fine...except that they fail all the time")
        
        current_stamp = datetime.datetime.now()
        hu.name = "Eric"
        hu.password = "******"
        hu.email = "*****@*****.**"
        hu.created = current_stamp
        hu.last_access = current_stamp
        hu.enabled = True
        hu.admin = False
        self.assertEqual(-1, hu.id, "ID is still -1")
        self.assertEqual(hu.name, "Eric", "Assignment of setting name failed.")
        self.assertNotEqual(hu.password, "Super Secret", "Plain text passwords are evil.")
        self.assertEqual(hu.email, "*****@*****.**", "Assignment of setting email failed.")
        self.assertEqual(hu.created, current_stamp, "Assignment of setting created timestamp failed.")
        self.assertEqual(hu.last_access, current_stamp, "Assignment of setting access timestamp failed.")
        self.assertEqual(hu.enabled, True, "Assignment of setting enabled failed.")
        self.assertEqual(hu.admin, False, "Assignment of setting admin failed.")
        
        # check password encryption bypass
        hu._password = "******"
        self.assertEqual(hu.password, "my weak password",  "Password encryption bypass failed")
        self.assertFalse(hasattr(hu, '_password'), "Password bypass still created an _password attribute")
        
        # Check that @ is banned from the name column
        with self.assertRaises(ValueError):
            setattr(hu, 'name', "*****@*****.**")
        
        # Check that admin and enabled throw value errors for non-bools
        with self.assertRaises(ValueError):
            setattr(hu, 'enabled', 'ABC')
            setattr(hu, 'admin', 'ABC')
Esempio n. 8
0
    def test_30_authenticate_user(self):
        """HistoriaCoreController: authenticate_user()"""
        # def authenticate_user(self, user_name, password):
        obj = controllers.HistoriaCoreController(
            config_location='tests/test_config')
        db = obj.create_database(self.testDBName,
                                 self.default_settings,
                                 db_type="system")

        obj.database = db

        name = "Sir Robin of Camelot"
        password = "******"
        email = "*****@*****.**"

        u1 = user.HistoriaUser(db)
        u1.name = name
        u1.password = password
        u1.email = email
        u1.save()

        response = obj.authenticate_user(name, password)
        self.assertIsInstance(response, user.HistoriaUser,
                              "Valid user not returned with valid creds.")
        self.assertEqual(
            u1, response,
            "Returned user isn't the user that created the record.")

        response = obj.authenticate_user(email, password)
        self.assertIsInstance(response, user.HistoriaUser,
                              "Valid user not returned with valid creds.")
        self.assertEqual(
            u1, response,
            "Returned user isn't the user that created the record.")

        response = obj.authenticate_user(email, "I don't know that")
        self.assertFalse(response, "False not returned with invalid creds.")

        response = obj.authenticate_user("Nothing to see here",
                                         "I don't know that")
        self.assertFalse(response, "False not returned with invalid creds.")

        obj.database.disconnect()
Esempio n. 9
0
 def test_10_construct(self):
     """HistoriaUser: Constructor"""
     
     hu = user.HistoriaUser(self.db)
     
     self.assertIsInstance(hu, user.HistoriaUser, "Umm, yeah, that's a problem...")
     self.assertEqual(hu.id,-1, "ID not -1")
     self.assertIsNone(hu.name, "Name attribute missing from new object")
     self.assertIsNone(hu.email, "email attribute missing from new object")
     self.assertIsNone(hu.password, "password attribute missing from new object")
     self.assertIsNone(hu.modified, "modified attribute missing from new object")
     self.assertIsNone(hu.created, "created attribute missing from new object")
     self.assertIsNone(hu.last_access, "last_access attribute missing from new object")
     self.assertIsNone(hu.enabled, "enabled attribute missing from new object")
     self.assertIsNone(hu.admin, "admin attribute missing from new object")
     self.assertIsInstance(hu._logger, logging.Logger, "Default logger isn't a logger")
     self.assertFalse(hu._dirty, "Dirty bit is be clean to start")
     self.assertIs(hu.database, self.db, "Database isn't the one we sent over")
     self.assertIsInstance(hu.database, core_data_objects.HistoriaDatabase, "Database object isn't the right type (oops)")
Esempio n. 10
0
    def user_delete(self, session, parameters):
        """Used for deleting users."""

        # Check for user
        if not hasattr(session, '_user'):
            self.logger.error(
                'Current session has no assicated user: {0}'.format(
                    session.id))
            raise InvalidSessionError(
                "Current session has no assicated user: {0}".format(
                    session.id))

        # Verify the user is an admin
        if not session._user.admin:
            self.logger.notice(
                'User {0} [{1}], attempted to create a new user.'.format(
                    session._user.name, session._user.id))
            raise InvalidPermissionsError(
                "Must have admin rights to create users.")

        # Verify required parameters were provided
        for param in self.routers['system']['user']['delete']['parameters']:
            if param not in parameters:
                self.logger.info(
                    "Attempt to delete user without required value: {0}".
                    format(param))
                raise InvalidParametersError(
                    "No {0} provided when deleting user".format(param))

        del_user = user.HistoriaUser(self.database)

        try:
            del_user.load(parameters['id'])
        except database.exceptions.DataLoadError as err:
            self.logger.error('Unable to find user {0} for delete'.format(
                parameters['id']))
            raise InvalidParametersError(
                'Unable to find user {0} for delete'.format(parameters['id']))

        del_user.delete()

        return del_user.id == -1
Esempio n. 11
0
    def user_info(self, session, parameters):
        """Used for getting user info."""

        # Check for user
        if not hasattr(session, '_user'):
            self.logger.error(
                'Current session has no assicated user: {0}'.format(
                    session.id))
            raise InvalidSessionError(
                "Current session has no assicated user: {0}".format(
                    session.id))

        # Check for an ID to test
        if 'id' not in parameters:
            self.logger.error(
                'No ID provided when requesting user information')
            raise InvalidParametersError(
                "No ID provided when requesting user information")

        users = []
        for uid in parameters['id']:
            if uid == session._user.id:
                users.append(session._user)
            elif session._user.admin:
                try:
                    test_user = user.HistoriaUser(self.database)
                    test_user.load(uid)
                    users.append(test_user)
                except Exception as err:
                    return None
            else:
                self.logger.notice(
                    'User {0} [{1}], attempted to get info about another user ({2}).'
                    .format(session._user.name, session._user.id,
                            parameters['id']))
                raise InvalidPermissionsError(
                    "User {0} cannot get information about user with ID {1}".
                    format(session._user.name, parameters['id']))

        return users
Esempio n. 12
0
    def user_edit(self, session, parameters):
        """Used for editing users."""

        # Check for current user
        if not hasattr(session, '_user'):
            self.logger.error(
                'Current session has no assicated user: {0}'.format(
                    session.id))
            raise InvalidSessionError(
                "Current session has no assicated user: {0}".format(
                    session.id))

        for param in self.routers['system']['user']['edit']['parameters']:
            if param not in parameters:
                self.logger.info(
                    "Attempt to create user without setting {0}".format(param))
                raise InvalidParametersError(
                    "No {0} provided when creating new user".format(param))

        # Verify current user is admin or editing self
        if not session._user.admin and session._user.id != parameters['id']:
            self.logger.notice(
                'User {0} [{1}], attempted to edit another user ({2}).'.format(
                    session._user.name, session._user.id, parameters['id']))
            raise InvalidPermissionsError(
                "User {0} attempted to edit user with ID {1}".format(
                    session._user.name, parameters['id']))

        edit_user = user.HistoriaUser(self.database)

        try:
            edit_user.load(parameters['id'])
        except database.exceptions.DataLoadError as err:
            self.logger.error('Unable to load user {0}'.format(
                parameters['id']))
            raise InvalidParametersError('Unable to load user {0}'.format(
                parameters['id']))

        return self._mod_user(edit_user, parameters)
Esempio n. 13
0
    def test_30_save(self):
        """HistoriaUser: save()"""
        hu = user.HistoriaUser(self.db)

        self.assertRaises(exceptions.DataConnectionError, hu.save)

        # Setup the database and try again.
        self.database_setup(withTables=True)
        
        self.assertRaises(exceptions.DataSaveError, hu.save)
        
        current_stamp = datetime.datetime.now()
        hu.name = "Eric"
        hu.password = "******"
        hu.email = "*****@*****.**"
        hu.created = current_stamp
        hu.last_access = current_stamp
        hu.enabled = True
        hu.admin = False
        self.assertTrue(hu._dirty, "Dirty bit not active but data changed")
        hu.save()
        
        self.assertFalse(hu._dirty, "Dirty bit active after save")
        self.assertNotEqual(hu.id, -1, "Record ID still -1 after save.")

        # Now let's go see if it's really there
        select = ("SELECT * FROM `historia_user`",{})
        result = self.db.execute_select(select)

        self.assertEqual(len(result), 1, "There should be 1 and only 1 entry in the table.")
        self.assertEqual(result[0]['name'], hu.name, "name in the table should match the name on the record.")
        self.assertEqual(result[0]['password'], hu.password, "password in the table should match the one on the record.")        
        self.assertEqual(result[0]['email'], hu.email, "email in the table should match the one on the record.")        
        self.assertAlmostEqual(result[0]['created'], hu.created, delta=datetime.timedelta(seconds=1), msg="created in the table should match the one on the record.")        
        self.assertAlmostEqual(result[0]['last_access'], hu.last_access,  delta=datetime.timedelta(seconds=1), msg="last_access in the table should match the one on the record.")        
        self.assertEqual(result[0]['enabled'], hu.enabled, "enabled in the table should match the one on the record.")        
        self.assertEqual(result[0]['admin'], hu.admin, "admin in the table should match the one on the record.")        
        self.assertNotEqual(result[0]['modified'], hu.modified, "modified in the table should not match the one on the record since that was setup by MySQL.")
Esempio n. 14
0
    def test_50_delete(self):
        """HistoriaUser: delete()"""
        self.database_setup(withTables=True)
        hu1 = user.HistoriaUser(self.db)
        current_stamp = datetime.datetime.now()
        test_pass = "******"
        hu1.name = "Eric"
        hu1.password = test_pass
        hu1.email = "*****@*****.**"
        hu1.created = current_stamp
        hu1.last_access = current_stamp
        hu1.enabled = True
        hu1.admin = False
        hu1.save()

        hu1.delete()

        # Now let's go see if it's really there
        select = ("SELECT * FROM `historia_user`",{})
        result = self.db.execute_select(select)

        self.assertEqual(len(result), 0, "There should nothing in the table now.")
        self.assertEqual(-1, hu1.id, "The ID should reset to -1")
Esempio n. 15
0
    def reload_session(self, session_id, ip):
        """Return a new session object"""
        sess = session.HistoriaSession(self.database)
        try:
            sess.load(session_id)
            if sess.ip != ip:
                sess.ip = ip
            sess.save()  # reset the last_seen value in the database

            self.logger.info("Loaded session with ID: {0}".format(session_id))

            if sess.userid > 0:
                try:
                    active_user = user.HistoriaUser(self.database)
                    active_user.load(sess.userid)
                    sess._user = active_user
                except database.exceptions.DataLoadError as err:
                    # If there is an error loading the user for this session
                    # then the session is corrupt and should be destoryed and a
                    # new one created.
                    self.logger.notice(
                        'Invalid user associated with session. Destorying session: {0}'
                        .format(session_id))
                    self.end_session(session_id)
                    sess = session.HistoriaSession(self.database)
        except database.exceptions.DataLoadError as err:
            self.logger.error('Unable to load session: {0}'.format(session_id))
            raise InvalidSessionError(
                "Invalid Session ID: {0}".format(session_id))
        except database.exceptions.DataConnectionError as err:
            self.logger.error(
                'Unable to connect to database to load session: {0}'.format(
                    session_id))
            raise err
        else:
            return sess