Exemplo n.º 1
0
    def __init__(self, db='mongodb'):
        """
        Initiates the current game mode.

        Args:
            db: The database to run the game with. One of Mode.possible_dbs
        """
        self.ui = ConsoleUI()
        self.db = self.possible_dbs[db]()
Exemplo n.º 2
0
class Mode(ABC):
    """
    Abstract class representing an activation mode of the trivia game.
    Some mode examples are administrative menu, predefined game setups and more.
    """

    possible_dbs = {'mongodb': DbMongodb, 'sql_server': DbSqlServer}

    def __init__(self, db='mongodb'):
        """
        Initiates the current game mode.

        Args:
            db: The database to run the game with. One of Mode.possible_dbs
        """
        self.ui = ConsoleUI()
        self.db = self.possible_dbs[db]()

    @abstractmethod
    def start(self):
        """
        Starts a new session.

        """
        pass

    @abstractmethod
    def restart(self):
        """
        Asks the user if he/she wants to restart the current session.

        Returns:
             bool: True if the user chose yes, False otherwise.

        """
        pass

    @staticmethod
    def _validate_pos_num(val):
        # a validation method to use with the ui.get_user_input method
        if val == "":  # empty string is allowed. default value will be used.
            return
        try:
            if int(val) <= 0:
                return "Invalid input. Must be positive."
        except ValueError:
            return "Invalid input. Must be a positive number."

    def _choose_category(self, message):
        categories = self.db.get_categories()
        if len(categories) == 0:
            self.ui.alert("There are currently no categories in the database.")
        else:
            return self.ui.get_user_choice(sorted(categories), message)
Exemplo n.º 3
0
def ui():
    updating_libs()
    console_ui = ConsoleUI()
    default_msg = "Comment posted by AutolikeBot\n======CODED BY PFUB======="
    returned = console_ui.main_menu()
    message = input("Input message (if not, bot will use default message): ")
    group = int(input("Input group id: "))
    if not group:
        while not group:
            group = int(input("Input group id: "))
    data = returned
    if message:
        main(data, message, group)
    else:
        main(data, default_msg, group)
Exemplo n.º 4
0
    def __init__(self, configuration_files = None, configuration_values = None):
        super(Controller, self).__init__()

        db_conf = DbConfiguration(configuration_files, configuration_values)
        self.db_host   = db_conf.db_host
        self.db_port   = db_conf.db_port
        self.db_engine = db_conf.db_engine
        self.db_name   = db_conf.db_name
        self.db_user   = db_conf.db_user
        self.db_pass   = db_conf.db_pass

        self.smtp_host         = globals().get(configuration_doc.MAIL_SERVER_HOST)
        self.smtp_helo         = globals().get(configuration_doc.MAIL_SERVER_HELO)

        self.default_db_name   = self.db_name
        self.default_db_user   = self.db_user
        self.default_db_pass   = self.db_pass

        self.default_ldap_users_file   = 'USERS'
        self.default_openid_users_file = 'USERSOID'
        self.default_db_users_file     = 'USERSDB'

        self.default_notification_from    = globals().get(configuration_doc.MAIL_NOTIFICATION_SENDER)
        self.default_notification_bcc     = globals().get(configuration_doc.SERVER_ADMIN)
        self.default_notification_subject = 'WebLab-Deusto notification'

        self.default_notification_text_file = 'NOTIFICATION'
        self.default_notification_with_password_text_file = 'NOTIFICATION_WITH_PASSWORD'

        self.ui = ConsoleUI()
        self.init()
        self.menu()
Exemplo n.º 5
0
    def __init__(self, configuration_files=None):
        super(Controller, self).__init__()

        for configuration_file in configuration_files:
            if not os.path.exists(configuration_file):
                print >> sys.stderr, "Could not file configuration file", configuration_file
                sys.exit(1)

            execfile(configuration_file, globals(), globals())

        global_vars = globals()

        self.db_host = get_variable(global_vars, configuration_doc.DB_HOST)
        self.db_engine = get_variable(global_vars, configuration_doc.DB_ENGINE)
        self.db_name = get_variable(global_vars, configuration_doc.DB_DATABASE)
        self.db_user = get_variable(global_vars,
                                    configuration_doc.WEBLAB_DB_USERNAME)
        self.db_pass = get_variable(global_vars,
                                    configuration_doc.WEBLAB_DB_PASSWORD)

        self.smtp_host = globals().get(configuration_doc.MAIL_SERVER_HOST)
        self.smtp_helo = globals().get(configuration_doc.MAIL_SERVER_HELO)

        self.default_db_name = self.db_name
        self.default_db_user = self.db_user
        self.default_db_pass = self.db_pass

        self.default_ldap_users_file = 'USERS'
        self.default_openid_users_file = 'USERSOID'
        self.default_db_users_file = 'USERSDB'

        self.default_notification_from = globals().get(
            configuration_doc.MAIL_NOTIFICATION_SENDER)
        self.default_notification_bcc = globals().get(
            configuration_doc.SERVER_ADMIN)
        self.default_notification_subject = 'WebLab-Deusto notification'

        self.default_notification_text_file = 'NOTIFICATION'
        self.default_notification_with_password_text_file = 'NOTIFICATION_WITH_PASSWORD'

        self.ui = ConsoleUI()
        self.init()
        self.menu()
Exemplo n.º 6
0
    def __init__(self, configuration_files = None):
        super(Controller, self).__init__()

        for configuration_file in configuration_files:
            if not os.path.exists(configuration_file):
                print >> sys.stderr, "Could not file configuration file", configuration_file
                sys.exit(1)

            globals()['CURRENT_PATH'] = configuration_file
            execfile(configuration_file, globals(), globals())

        global_vars = globals()

        self.db_host           = get_variable(global_vars, configuration_doc.DB_HOST)
        self.db_port           = get_variable(global_vars, configuration_doc.DB_PORT)
        self.db_engine         = get_variable(global_vars, configuration_doc.DB_ENGINE)
        self.db_name           = get_variable(global_vars, configuration_doc.DB_DATABASE)
        self.db_user           = get_variable(global_vars, configuration_doc.WEBLAB_DB_USERNAME)
        self.db_pass           = get_variable(global_vars, configuration_doc.WEBLAB_DB_PASSWORD)

        self.smtp_host         = globals().get(configuration_doc.MAIL_SERVER_HOST)
        self.smtp_helo         = globals().get(configuration_doc.MAIL_SERVER_HELO)

        self.default_db_name   = self.db_name
        self.default_db_user   = self.db_user
        self.default_db_pass   = self.db_pass

        self.default_ldap_users_file   = 'USERS'
        self.default_openid_users_file = 'USERSOID'
        self.default_db_users_file     = 'USERSDB'

        self.default_notification_from    = globals().get(configuration_doc.MAIL_NOTIFICATION_SENDER)
        self.default_notification_bcc     = globals().get(configuration_doc.SERVER_ADMIN)
        self.default_notification_subject = 'WebLab-Deusto notification'

        self.default_notification_text_file = 'NOTIFICATION'
        self.default_notification_with_password_text_file = 'NOTIFICATION_WITH_PASSWORD'

        self.ui = ConsoleUI()
        self.init()
        self.menu()
Exemplo n.º 7
0
class Controller(object):

    def __init__(self, configuration_files = None):
        super(Controller, self).__init__()

        for configuration_file in configuration_files:
            if not os.path.exists(configuration_file):
                print >> sys.stderr, "Could not file configuration file", configuration_file
                sys.exit(1)

            execfile(configuration_file, globals(), globals())

        global_vars = globals()

        self.db_host           = get_variable(global_vars, configuration_doc.DB_HOST)
        self.db_engine         = get_variable(global_vars, configuration_doc.DB_ENGINE)
        self.db_name           = get_variable(global_vars, configuration_doc.DB_DATABASE)
        self.db_user           = get_variable(global_vars, configuration_doc.WEBLAB_DB_USERNAME)
        self.db_pass           = get_variable(global_vars, configuration_doc.WEBLAB_DB_PASSWORD)

        self.smtp_host         = globals().get(configuration_doc.MAIL_SERVER_HOST)
        self.smtp_helo         = globals().get(configuration_doc.MAIL_SERVER_HELO)

        self.default_db_name   = self.db_name
        self.default_db_user   = self.db_user
        self.default_db_pass   = self.db_pass

        self.default_ldap_users_file   = 'USERS'
        self.default_openid_users_file = 'USERSOID'
        self.default_db_users_file     = 'USERSDB'

        self.default_notification_from    = globals().get(configuration_doc.MAIL_NOTIFICATION_SENDER)
        self.default_notification_bcc     = globals().get(configuration_doc.SERVER_ADMIN)
        self.default_notification_subject = 'WebLab-Deusto notification'

        self.default_notification_text_file = 'NOTIFICATION'
        self.default_notification_with_password_text_file = 'NOTIFICATION_WITH_PASSWORD'

        self.ui = ConsoleUI()
        self.init()
        self.menu()

    def init(self):
        if self.db_name is not None and self.db_user is not None and self.db_pass is not None:
            self.db = DbGateway(self.db_engine, self.db_host, self.db_name, self.db_user, self.db_pass)
        else:
            db_name, db_user, db_pass = self.ui.dialog_init(self.default_db_name, self.default_db_user, self.default_db_pass)
            self.db = DbGateway(self.db_engine, self.db_host, db_name, db_user, db_pass)

    def menu(self):
        option = None
        while option != 0:
            option = self.ui.dialog_menu()
            if option == 1:
                self.add_group()
            elif option == 2:
                self.add_experiment_category()
            elif option == 3:
                self.add_experiment()
            elif option == 4:
                self.add_users_to_group_file()
            elif option == 5:
                self.add_users_to_group()
            elif option == 6:
                self.add_user_with_db_authtype()
            elif option == 7:
                self.add_users_with_ldap_authtype()
            elif option == 8:
                self.add_users_with_openid_authtype()
            elif option == 9:
                self.add_users_batch_with_db_authtype()
            elif option == 10:
                self.grant_on_experiment_to_group()
            elif option == 11:
                self.grant_on_experiment_to_user()
            elif option == 12:
                self.grant_on_admin_panel_to_group()
            elif option == 13:
                self.grant_on_admin_panel_to_user()
            elif option == 14:
                self.grant_on_access_forward_to_group()
            elif option == 15:
                self.grant_on_access_forward_to_user()
            elif option == 16:
                self.list_users()
            elif option == 17:
                self.notify_users()
            elif option == 18:
                self.notify_users_with_passwords()
        self.ui.dialog_exit()
        sys.exit(0)

    def add_group(self):
        groups = self.db.get_groups()
        group_names = [ (group.id, group.name) for group in groups ]
        try:
            group_name, parent_group_id = self.ui.dialog_add_group(group_names)
            parent_group = [ group for group in groups if group.id == parent_group_id ][0] if parent_group_id is not None else None
            group = self.db.insert_group(group_name, parent_group)
            if group is not None:
                self.ui.notify("Group created:\n%r" % group)
            else:
                self.ui.error("The Group '%s' already exists." % group_name)
            self.ui.wait()
        except GoBackError:
            return


    def add_experiment_category(self):
        try:
            category_name = self.ui.dialog_add_experiment_category()
            category = self.db.insert_experiment_category(category_name)
            if category is not None:
                self.ui.notify("ExperimentCategory created:\n%r" % category)
            else:
                self.ui.error("The ExperimentCategory '%s' already exists." % category_name)
            self.ui.wait()
        except GoBackError:
            return

    def add_experiment(self):
        categories = self.db.get_experiment_categories()
        category_names = [ (category.id, category.name) for category in categories ]
        try:
            experiment_name, category_id = self.ui.dialog_add_experiment(category_names)
            category = [ category for category in categories if category.id == category_id ][0]
            start_date = datetime.datetime.utcnow()
            end_date = start_date.replace(year=start_date.year+12)
            experiment = self.db.insert_experiment(experiment_name, category, start_date, end_date)
            if experiment is not None:
                self.ui.notify("Experiment created:\n%r" % experiment)
            else:
                self.ui.error("The Experiment '%s' already exists." % experiment_name)
            self.ui.wait()
        except GoBackError:
            return

    def add_users_to_group_file(self):
        groups = self.db.get_groups()
        group_names = [ (group.id, group.name) for group in groups ]
        try:
            group_id, user_logins = self.ui.dialog_add_users_to_group_file(group_names, self.default_ldap_users_file)
            group = [ group for group in groups if group.id == group_id ][0]
            users = self.db.get_users(user_logins)
            if len(user_logins) > 0:
                self.ui.notify("The following Users have been added to the Group:\n%r" % group)
                error_users = []
                for user in users:
                    u, g = self.db.add_user_to_group(user, group)
                    if (u, g) is not (None, None):
                        self.ui.notify("%r" % u)
                    else:
                        error_users.append(user)
                self.ui.notify("Total added Users: %i" % (len(users)-len(error_users)))
                if len(error_users) > 0:
                    self.ui.error("Warning! The following Users could not be added to the Group: %r" % error_users)
                if len(user_logins) > len(users):
                    self.ui.notify("Warning! %i Users did not exist in the database." % (len(user_logins) - len(users)))
            else:
                self.ui.error("There are no Users to be added to the Group.")
            self.ui.wait()
        except GoBackError:
            return
       

    def add_users_to_group(self):
        groups = self.db.get_groups()
        users  = self.db.get_users()
        group_names = [ (group.id, group.name) for group in groups ]
        user_logins = [ (user.id, user.login) for user in users]
        user_logins_dict = dict(user_logins)
        try:
            group_id, user_id = self.ui.dialog_add_users_to_group(group_names, user_logins)
            user_logins = [user_logins_dict[user_id]]
            group = [ group for group in groups if group.id == group_id ][0]
            users = self.db.get_users(user_logins)
            if len(user_logins) > 0:
                self.ui.notify("The following Users have been added to the Group:\n%r" % group)
                error_users = []
                for user in users:
                    u, g = self.db.add_user_to_group(user, group)
                    if (u, g) is not (None, None):
                        self.ui.notify("%r" % u)
                    else:
                        error_users.append(user)
                self.ui.notify("Total added Users: %i" % (len(users)-len(error_users)))
                if len(error_users) > 0:
                    self.ui.error("Warning! The following Users could not be added to the Group: %r" % error_users)
                if len(user_logins) > len(users):
                    self.ui.notify("Warning! %i Users did not exist in the database." % (len(user_logins) - len(users)))
            else:
                self.ui.error("There are no Users to be added to the Group.")
            self.ui.wait()
        except GoBackError:
            return

    def add_user_with_db_authtype(self):
        roles = self.db.get_roles()
        role_names = [ (role.id, role.name) for role in roles ]
        auths = self.db.get_auths("DB")
        auth_names = [ (auth.id, auth.name) for auth in auths ]
        try:
            # Note: The following user_auth_config is the password
            login, full_name, email, avatar, role_id, auth_id, user_auth_config = self.ui.dialog_add_user_with_db_authtype(role_names, auth_names)
            role = [ role for role in roles if role.id == role_id ][0] if role_id is not None else None
            auth = [ auth for auth in auths if auth.id == auth_id ][0]
            user = self.db.insert_user(login, full_name, email, avatar, role)
            if user is not None:
                self.ui.notify("User created:\n%r" % user)
                user_auth = self.db.insert_user_auth(user, auth, self._password2sha(user_auth_config))
                assert user_auth is not None
                self.ui.notify("UserAuth created:\n%r" % user_auth)
            else:
                self.ui.error("The User '%s' already exists." % login)
            self.ui.wait()
        except GoBackError:
            return

    def add_users_batch_with_db_authtype(self):
        # Retrieve every role from the database
        roles = self.db.get_roles()
        role_names = [ (role.id, role.name) for role in roles ]

        # Retrieve every DB auth
        auths = self.db.get_auths("DB")
        auth_names = [ (auth.id, auth.name) for auth in auths ]

        try:

            # Get the data (asking the user if needed) about the users to add and the
            # role to assign them.
            user_logins, role_id = self.ui.dialog_add_users_batch_with_db_authtype(
                                                            role_names,
                                                            auth_names,
                                                            self.default_db_users_file
                                                        )

            # Get the actual role object through the role id we obtained before.
            role = [ role for role in roles if role.id == role_id ][0] if role_id is not None else None

            # Get the first DB auth. We will assume that there is one at most.
            if len(auths) < 1:
                self.ui.error("There is no auth available of the type DB")
            auth = auths[0]

            for user_data in user_logins:
                # create the user object using the login, full name, email and password we have
                # retrieved from the provided DB USERS file.
                user = self.db.insert_user(user_data[0], user_data[1], user_data[2], None, role)
                if user is not None:
                    self.ui.notify("User created:\n%r" % user)
                    user_auth = self.db.insert_user_auth(user, auth, self._password2sha(user_data[3]))
                    assert user_auth is not None
                    self.ui.notify("UserAuth created:\n%r" % user_auth)
                else:
                    self.ui.error("The User '%s' already exists." % str(user_data) )
            self.ui.wait()

        except GoBackError:
            return

    def add_users_with_ldap_authtype(self):
        if LdapGatewayClass is None:
            self.ui.error("LDAP is not available. Is python-ldap installed?")
            self.ui.wait()
            return
        roles = self.db.get_roles()
        role_names = [ (role.id, role.name) for role in roles ]
        auths = self.db.get_auths("LDAP")
        auth_names = [ (auth.id, auth.name) for auth in auths ]
        try:
            user_logins, role_id, auth_id = self.ui.dialog_add_users_with_ldap_authtype(
                                                            role_names,
                                                            auth_names,
                                                            self.default_ldap_users_file
                                                  )
            role = [ role for role in roles if role.id == role_id ][0] if role_id is not None else None
            auth = [ auth for auth in auths if auth.id == auth_id ][0]
            auth_username, auth_password, auth_domain = self.ui.dialog_authenticate_on_ldap()
            ldap = LdapGatewayClass(auth.get_config_value("ldap_uri"),
                               auth_domain,
                               auth.get_config_value("base"),
                               auth_username, auth_password)

            users_created_successfully = 0
            num_users = len(user_logins)
            for user_data in ldap.get_users(user_logins):
                try:
                    user = self.db.insert_user(user_data["login"], user_data["full_name"], user_data["email"], None, role)
                    if user is not None:
                        self.ui.notify("User created:\n%r" % user)
                        user_auth = self.db.insert_user_auth(user, auth, None)
                        assert user_auth is not None
                        self.ui.notify("UserAuth created:\n%r" % user_auth)
                        users_created_successfully += 1
                    else:
                        self.ui.error("The User '%s' already exists." % user_data["login"])
                        self.db.session.rollback()
                except Exception, ex:
                    self.ui.error("The User '%s' could not be created. Ignoring him/her. Reason: " % (user_data["login"], ex.__repr__))
            self.ui.notify("Created %d users out of %d." % (users_created_successfully, num_users))
            self.ui.wait()
        except GoBackError:
            return
Exemplo n.º 8
0
# from test import test_service, test_service2
# test_service2()
from console_ui import ConsoleUI
from service import Service

if __name__ == '__main__':
    service = Service()
    console_ui = ConsoleUI(service)
    console_ui.run()
Exemplo n.º 9
0
from admin_menu import AdminMenu
from game import Game
from console_ui import ConsoleUI as UI
import sys

# choose the game mode according to the command-line parameter or use default mode
modes = {'normal', 'admin'}
mode = 'normal'
if len(sys.argv) > 1:
    mode = sys.argv[1]
    if mode not in modes:
        UI.alert(
            f"Invalid argument {mode}. mode parameter should be one of [{modes}] or left empty. "
            f" The default mode is {default_mode}")
        exit(1)

if mode and mode == 'admin':
    session = AdminMenu()
else:
    session = Game()

# Start the game

UI.welcome("!! WELCOME TO THE AMAZING TRIVIA GAME !!")
finished = False
while not finished:
    session.start()
    if not session.restart():
        finished = True
    else:
        UI.restart()
Exemplo n.º 10
0
def encode_data(file_name, new_file_name):
    coords = []
    with open('tests/' + file_name, 'r') as file:
        for line in file.readlines():
            _, lat, lon = line.split(' ')
            lat = float(lat)
            lon = float(lon)
            coords.append([lat, lon])
    distance_matrix = []

    def euclidean(A, B):
        return math.sqrt((A[0] - B[0]) ** 2 + (A[1] - B[1]) ** 2)

    for i in range(len(coords)):
        row = []
        for j in range(len(coords)):
            row.append(round(euclidean(coords[i], coords[j])))
        distance_matrix.append(row)

    with open('tests/' + new_file_name, "w") as file:
        file.write(str(len(distance_matrix)) + '\n')
        for row in distance_matrix:
            file.write(','.join(map(lambda x: str(x), row)) + '\n')

    print("Finished encoding", file_name, '....')

from timeit import default_timer as timer

if __name__ == '__main__':
   ui = ConsoleUI()
   ui.run()
Exemplo n.º 11
0
class Controller(object):
    def __init__(self, configuration_files=None):
        super(Controller, self).__init__()

        for configuration_file in configuration_files:
            if not os.path.exists(configuration_file):
                print >> sys.stderr, "Could not file configuration file", configuration_file
                sys.exit(1)

            execfile(configuration_file, globals(), globals())

        global_vars = globals()

        self.db_host = get_variable(global_vars, configuration_doc.DB_HOST)
        self.db_engine = get_variable(global_vars, configuration_doc.DB_ENGINE)
        self.db_name = get_variable(global_vars, configuration_doc.DB_DATABASE)
        self.db_user = get_variable(global_vars,
                                    configuration_doc.WEBLAB_DB_USERNAME)
        self.db_pass = get_variable(global_vars,
                                    configuration_doc.WEBLAB_DB_PASSWORD)

        self.smtp_host = globals().get(configuration_doc.MAIL_SERVER_HOST)
        self.smtp_helo = globals().get(configuration_doc.MAIL_SERVER_HELO)

        self.default_db_name = self.db_name
        self.default_db_user = self.db_user
        self.default_db_pass = self.db_pass

        self.default_ldap_users_file = 'USERS'
        self.default_openid_users_file = 'USERSOID'
        self.default_db_users_file = 'USERSDB'

        self.default_notification_from = globals().get(
            configuration_doc.MAIL_NOTIFICATION_SENDER)
        self.default_notification_bcc = globals().get(
            configuration_doc.SERVER_ADMIN)
        self.default_notification_subject = 'WebLab-Deusto notification'

        self.default_notification_text_file = 'NOTIFICATION'
        self.default_notification_with_password_text_file = 'NOTIFICATION_WITH_PASSWORD'

        self.ui = ConsoleUI()
        self.init()
        self.menu()

    def init(self):
        if self.db_name is not None and self.db_user is not None and self.db_pass is not None:
            self.db = DbGateway(self.db_engine, self.db_host, self.db_name,
                                self.db_user, self.db_pass)
        else:
            db_name, db_user, db_pass = self.ui.dialog_init(
                self.default_db_name, self.default_db_user,
                self.default_db_pass)
            self.db = DbGateway(self.db_engine, self.db_host, db_name, db_user,
                                db_pass)

    def menu(self):
        option = None
        while option != 0:
            option = self.ui.dialog_menu()
            if option == 1:
                self.add_group()
            elif option == 2:
                self.add_experiment_category()
            elif option == 3:
                self.add_experiment()
            elif option == 4:
                self.add_users_to_group_file()
            elif option == 5:
                self.add_users_to_group()
            elif option == 6:
                self.add_user_with_db_authtype()
            elif option == 7:
                self.add_users_with_ldap_authtype()
            elif option == 8:
                self.add_users_with_openid_authtype()
            elif option == 9:
                self.add_users_batch_with_db_authtype()
            elif option == 10:
                self.grant_on_experiment_to_group()
            elif option == 11:
                self.grant_on_experiment_to_user()
            elif option == 12:
                self.grant_on_admin_panel_to_group()
            elif option == 13:
                self.grant_on_admin_panel_to_user()
            elif option == 14:
                self.grant_on_access_forward_to_group()
            elif option == 15:
                self.grant_on_access_forward_to_user()
            elif option == 16:
                self.list_users()
            elif option == 17:
                self.notify_users()
            elif option == 18:
                self.notify_users_with_passwords()
        self.ui.dialog_exit()
        sys.exit(0)

    def add_group(self):
        groups = self.db.get_groups()
        group_names = [(group.id, group.name) for group in groups]
        try:
            group_name, parent_group_id = self.ui.dialog_add_group(group_names)
            parent_group = [
                group for group in groups if group.id == parent_group_id
            ][0] if parent_group_id is not None else None
            group = self.db.insert_group(group_name, parent_group)
            if group is not None:
                self.ui.notify("Group created:\n%r" % group)
            else:
                self.ui.error("The Group '%s' already exists." % group_name)
            self.ui.wait()
        except GoBackError:
            return

    def add_experiment_category(self):
        try:
            category_name = self.ui.dialog_add_experiment_category()
            category = self.db.insert_experiment_category(category_name)
            if category is not None:
                self.ui.notify("ExperimentCategory created:\n%r" % category)
            else:
                self.ui.error("The ExperimentCategory '%s' already exists." %
                              category_name)
            self.ui.wait()
        except GoBackError:
            return

    def add_experiment(self):
        categories = self.db.get_experiment_categories()
        category_names = [(category.id, category.name)
                          for category in categories]
        try:
            experiment_name, category_id = self.ui.dialog_add_experiment(
                category_names)
            category = [
                category for category in categories
                if category.id == category_id
            ][0]
            start_date = datetime.datetime.utcnow()
            end_date = start_date.replace(year=start_date.year + 12)
            experiment = self.db.insert_experiment(experiment_name, category,
                                                   start_date, end_date)
            if experiment is not None:
                self.ui.notify("Experiment created:\n%r" % experiment)
            else:
                self.ui.error("The Experiment '%s' already exists." %
                              experiment_name)
            self.ui.wait()
        except GoBackError:
            return

    def add_users_to_group_file(self):
        groups = self.db.get_groups()
        group_names = [(group.id, group.name) for group in groups]
        try:
            group_id, user_logins = self.ui.dialog_add_users_to_group_file(
                group_names, self.default_ldap_users_file)
            group = [group for group in groups if group.id == group_id][0]
            users = self.db.get_users(user_logins)
            if len(user_logins) > 0:
                self.ui.notify(
                    "The following Users have been added to the Group:\n%r" %
                    group)
                error_users = []
                for user in users:
                    u, g = self.db.add_user_to_group(user, group)
                    if (u, g) is not (None, None):
                        self.ui.notify("%r" % u)
                    else:
                        error_users.append(user)
                self.ui.notify("Total added Users: %i" %
                               (len(users) - len(error_users)))
                if len(error_users) > 0:
                    self.ui.error(
                        "Warning! The following Users could not be added to the Group: %r"
                        % error_users)
                if len(user_logins) > len(users):
                    self.ui.notify(
                        "Warning! %i Users did not exist in the database." %
                        (len(user_logins) - len(users)))
            else:
                self.ui.error("There are no Users to be added to the Group.")
            self.ui.wait()
        except GoBackError:
            return

    def add_users_to_group(self):
        groups = self.db.get_groups()
        users = self.db.get_users()
        group_names = [(group.id, group.name) for group in groups]
        user_logins = [(user.id, user.login) for user in users]
        user_logins_dict = dict(user_logins)
        try:
            group_id, user_id = self.ui.dialog_add_users_to_group(
                group_names, user_logins)
            user_logins = [user_logins_dict[user_id]]
            group = [group for group in groups if group.id == group_id][0]
            users = self.db.get_users(user_logins)
            if len(user_logins) > 0:
                self.ui.notify(
                    "The following Users have been added to the Group:\n%r" %
                    group)
                error_users = []
                for user in users:
                    u, g = self.db.add_user_to_group(user, group)
                    if (u, g) is not (None, None):
                        self.ui.notify("%r" % u)
                    else:
                        error_users.append(user)
                self.ui.notify("Total added Users: %i" %
                               (len(users) - len(error_users)))
                if len(error_users) > 0:
                    self.ui.error(
                        "Warning! The following Users could not be added to the Group: %r"
                        % error_users)
                if len(user_logins) > len(users):
                    self.ui.notify(
                        "Warning! %i Users did not exist in the database." %
                        (len(user_logins) - len(users)))
            else:
                self.ui.error("There are no Users to be added to the Group.")
            self.ui.wait()
        except GoBackError:
            return

    def add_user_with_db_authtype(self):
        roles = self.db.get_roles()
        role_names = [(role.id, role.name) for role in roles]
        auths = self.db.get_auths("DB")
        auth_names = [(auth.id, auth.name) for auth in auths]
        try:
            # Note: The following user_auth_config is the password
            login, full_name, email, avatar, role_id, auth_id, user_auth_config = self.ui.dialog_add_user_with_db_authtype(
                role_names, auth_names)
            role = [role for role in roles
                    if role.id == role_id][0] if role_id is not None else None
            auth = [auth for auth in auths if auth.id == auth_id][0]
            user = self.db.insert_user(login, full_name, email, avatar, role)
            if user is not None:
                self.ui.notify("User created:\n%r" % user)
                user_auth = self.db.insert_user_auth(
                    user, auth, self._password2sha(user_auth_config))
                assert user_auth is not None
                self.ui.notify("UserAuth created:\n%r" % user_auth)
            else:
                self.ui.error("The User '%s' already exists." % login)
            self.ui.wait()
        except GoBackError:
            return

    def add_users_batch_with_db_authtype(self):
        # Retrieve every role from the database
        roles = self.db.get_roles()
        role_names = [(role.id, role.name) for role in roles]

        # Retrieve every DB auth
        auths = self.db.get_auths("DB")
        auth_names = [(auth.id, auth.name) for auth in auths]

        try:

            # Get the data (asking the user if needed) about the users to add and the
            # role to assign them.
            user_logins, role_id = self.ui.dialog_add_users_batch_with_db_authtype(
                role_names, auth_names, self.default_db_users_file)

            # Get the actual role object through the role id we obtained before.
            role = [role for role in roles
                    if role.id == role_id][0] if role_id is not None else None

            # Get the first DB auth. We will assume that there is one at most.
            if len(auths) < 1:
                self.ui.error("There is no auth available of the type DB")
            auth = auths[0]

            for user_data in user_logins:
                # create the user object using the login, full name, email and password we have
                # retrieved from the provided DB USERS file.
                user = self.db.insert_user(user_data[0], user_data[1],
                                           user_data[2], None, role)
                if user is not None:
                    self.ui.notify("User created:\n%r" % user)
                    user_auth = self.db.insert_user_auth(
                        user, auth, self._password2sha(user_data[3]))
                    assert user_auth is not None
                    self.ui.notify("UserAuth created:\n%r" % user_auth)
                else:
                    self.ui.error("The User '%s' already exists." %
                                  str(user_data))
            self.ui.wait()

        except GoBackError:
            return

    def add_users_with_ldap_authtype(self):
        if LdapGatewayClass is None:
            self.ui.error("LDAP is not available. Is python-ldap installed?")
            self.ui.wait()
            return
        roles = self.db.get_roles()
        role_names = [(role.id, role.name) for role in roles]
        auths = self.db.get_auths("LDAP")
        auth_names = [(auth.id, auth.name) for auth in auths]
        try:
            user_logins, role_id, auth_id = self.ui.dialog_add_users_with_ldap_authtype(
                role_names, auth_names, self.default_ldap_users_file)
            role = [role for role in roles
                    if role.id == role_id][0] if role_id is not None else None
            auth = [auth for auth in auths if auth.id == auth_id][0]
            auth_username, auth_password, auth_domain = self.ui.dialog_authenticate_on_ldap(
            )
            ldap = LdapGatewayClass(auth.get_config_value("ldap_uri"),
                                    auth_domain, auth.get_config_value("base"),
                                    auth_username, auth_password)

            users_created_successfully = 0
            num_users = len(user_logins)
            for user_data in ldap.get_users(user_logins):
                try:
                    user = self.db.insert_user(user_data["login"],
                                               user_data["full_name"],
                                               user_data["email"], None, role)
                    if user is not None:
                        self.ui.notify("User created:\n%r" % user)
                        user_auth = self.db.insert_user_auth(user, auth, None)
                        assert user_auth is not None
                        self.ui.notify("UserAuth created:\n%r" % user_auth)
                        users_created_successfully += 1
                    else:
                        self.ui.error("The User '%s' already exists." %
                                      user_data["login"])
                        self.db.session.rollback()
                except Exception, ex:
                    self.ui.error(
                        "The User '%s' could not be created. Ignoring him/her. Reason: "
                        % (user_data["login"], ex.__repr__))
            self.ui.notify("Created %d users out of %d." %
                           (users_created_successfully, num_users))
            self.ui.wait()
        except GoBackError:
            return
Exemplo n.º 12
0
from console_ui import ConsoleUI
import platform
import sys

if __name__ == "__main__":
    ui = ConsoleUI(platform.system())
    ui.run()
    sys.exit()