def get_or_create_group_id(name, user):
    group = ServerGroup.query.filter_by(user_id=user.id, name=name).first()
    if group is None:
        group = ServerGroup()
        group.name = name
        group.user_id = user.id
        print("Created server group %r for user %r" % (name, user.email))
        db.session.add(group)

        commit("Error creating server group {}".format(name), "Successfully saved.")

    return group.id
Exemplo n.º 2
0
    def create(self):
        data = request.form if request.form else json.loads(
            request.data.decode())
        if data[u'name'] != '':
            try:
                sg = ServerGroup(user_id=current_user.id, name=data[u'name'])
                db.session.add(sg)
                db.session.commit()

                data[u'id'] = sg.id
                data[u'name'] = sg.name

                return jsonify(node=self.blueprint.generate_browser_node(
                    "%d" % (sg.id), None, sg.name, "icon-%s" %
                    self.node_type, True, self.node_type))
            except Exception as e:
                return make_json_response(status=410,
                                          success=0,
                                          errormsg=e.message)

        else:
            return make_json_response(
                status=417,
                success=0,
                errormsg=gettext('No server group name was specified'))
Exemplo n.º 3
0
def _create_new_user(new_data):
    """
    Create new user.
    :param new_data: Data from user creation.
    :return: Return new created user.
    """
    auth_source = new_data['auth_source'] if 'auth_source' in new_data \
        else current_app.PGADMIN_DEFAULT_AUTH_SOURCE
    username = new_data['username'] if \
        'username' in new_data and auth_source != \
        current_app.PGADMIN_DEFAULT_AUTH_SOURCE else new_data['email']
    email = new_data['email'] if 'email' in new_data else None
    password = new_data['password'] if 'password' in new_data else None

    usr = User(username=username,
               email=email,
               roles=new_data['roles'],
               active=new_data['active'],
               password=password,
               auth_source=auth_source)
    db.session.add(usr)
    db.session.commit()
    # Add default server group for new user.
    server_group = ServerGroup(user_id=usr.id, name="Servers")
    db.session.add(server_group)
    db.session.commit()

    return usr
Exemplo n.º 4
0
def do_setup(app):
    """Create a new settings database from scratch"""
    if config.SERVER_MODE is False:
        print("NOTE: Configuring authentication for DESKTOP mode.")
        email = config.DESKTOP_USER
        p1 = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(32)
        ])

    else:
        print("NOTE: Configuring authentication for SERVER mode.\n")

        # Prompt the user for their default username and password.
        print("""
Enter the email address and password to use for the initial pgAdmin user \
account:\n""")
        email = ''
        while email == '':
            email = input("Email address: ")

        def pprompt():
            return getpass.getpass(), getpass.getpass('Retype password:'******'Passwords do not match. Try again')
            p1, p2 = pprompt()

    # Setup Flask-Security
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)

    with app.app_context():
        password = encrypt_password(p1)

        db.create_all()
        user_datastore.create_role(name='Administrators',
                                   description='pgAdmin Administrators Role')
        user_datastore.create_user(email=email, password=password)
        db.session.flush()
        user_datastore.add_role_to_user(email, 'Administrators')

        # Get the user's ID and create the default server group
        user = User.query.filter_by(email=email).first()
        server_group = ServerGroup(user_id=user.id, name="Servers")
        db.session.merge(server_group)

        # Set the schema version
        version = Version(name='ConfigDB',
                          value=config.SETTINGS_SCHEMA_VERSION)
        db.session.merge(version)

        db.session.commit()

    # Done!
    print("")
    print("The configuration database has been created at {0}".format(
        config.SQLITE_PATH))
Exemplo n.º 5
0
def create_user(data):
    if 'auth_source' in data and data['auth_source'] != \
            current_app.PGADMIN_DEFAULT_AUTH_SOURCE:
        req_params = ('username', 'role', 'active', 'auth_source')
    else:
        req_params = ('email', 'role', 'active', 'newPassword',
                      'confirmPassword')

    for f in req_params:
        if f in data and data[f] != '':
            continue
        else:
            return False, _("Missing field: '{0}'").format(f)

    try:
        new_data = validate_user(data)

        if 'roles' in new_data:
            new_data['roles'] = [Role.query.get(new_data['roles'])]

    except Exception as e:
        return False, str(e)

    try:

        auth_source = new_data['auth_source'] if 'auth_source' in new_data \
            else current_app.PGADMIN_DEFAULT_AUTH_SOURCE
        username = new_data['username'] if \
            'username' in new_data and auth_source !=\
            current_app.PGADMIN_DEFAULT_AUTH_SOURCE else new_data['email']
        email = new_data['email'] if 'email' in new_data else None
        password = new_data['password'] if 'password' in new_data else None

        usr = User(username=username,
                   email=email,
                   roles=new_data['roles'],
                   active=new_data['active'],
                   password=password,
                   auth_source=auth_source)
        db.session.add(usr)
        db.session.commit()
        # Add default server group for new user.
        server_group = ServerGroup(user_id=usr.id, name="Servers")
        db.session.add(server_group)
        db.session.commit()
    except Exception as e:
        return False, str(e)

    return True, {
        'id': usr.id,
        'username': usr.username,
        'email': usr.email,
        'active': usr.active,
        'role': usr.roles[0].id
    }
Exemplo n.º 6
0
def create():
    """

    Returns:

    """
    data = request.form if request.form else json.loads(
        request.data, encoding='utf-8'
    )

    for f in ('email', 'role', 'active', 'newPassword', 'confirmPassword'):
        if f in data and data[f] != '':
            continue
        else:
            return bad_request(errormsg=_("Missing field: '{0}'".format(f)))

    try:
        new_data = validate_user(data)

        if 'roles' in new_data:
            new_data['roles'] = [Role.query.get(new_data['roles'])]

    except Exception as e:
        return bad_request(errormsg=_(str(e)))

    try:
        usr = User(email=new_data['email'],
                   roles=new_data['roles'],
                   active=new_data['active'],
                   password=new_data['password'])
        db.session.add(usr)
        db.session.commit()
        # Add default server group for new user.
        server_group = ServerGroup(user_id=usr.id, name="Servers")
        db.session.add(server_group)
        db.session.commit()
    except Exception as e:
        return internal_server_error(errormsg=str(e))

    res = {'id': usr.id,
           'email': usr.email,
           'active': usr.active,
           'role': usr.roles[0].id
           }

    return ajax_response(
        response=res,
        status=200
    )
Exemplo n.º 7
0
def create():
    """

    Returns:

    """
    data = request.form if request.form else json.loads(request.data,
                                                        encoding='utf-8')
    for f in ('email', 'role', 'active', 'newPassword', 'confirmPassword'):
        if f in data and data[f] != '':
            continue
        else:
            return InvalidParameterResult(
                errors=["Missing field: '{0}'".format(f)]).http_response()

    try:
        new_data = validate_user(data)
        if 'roles' in new_data:
            roles_obj = []
            for r in new_data['roles']:
                roles_obj.append(Role.query.get(r))
            new_data['roles'] = roles_obj

    except Exception as e:
        return InvalidParameterResult(errors=[str(e)]).http_response()

    try:
        usr = User(email=new_data['email'],
                   roles=new_data['roles'],
                   active=new_data['active'],
                   password=new_data['password'])
        db.session.add(usr)
        db.session.commit()
        # Add default server group for new user.
        server_group = ServerGroup(user_id=usr.id, name="Servers")
        db.session.add(server_group)
        db.session.commit()
    except Exception as e:
        return ServerErrorResult(message=str(e)).http_response()

    res = {
        'id': usr.id,
        'email': usr.email,
        'active': usr.active,
        'role': get_detailed_roles(usr.roles)
    }

    result = Result(200, "SUCCESS", "SUCCESS", extra_fields={"results": [res]})
    return result.http_response()
Exemplo n.º 8
0
def on_user_registerd(app, user, confirm_token):
    sg = ServerGroup(user_id=user.id, name="Servers")
    db.session.add(sg)
    if is_ami.get('rc') != 2:
        session['initial-logged-in'] = True
    db.session.commit()
    default_user = user_datastore.get_user('*****@*****.**')
    if not len(
            User.query.filter(User.roles.any(name='Administrator'), User.active
                              == True).all()) > 0:
        if default_user is not None and default_user.has_role(
                'Administrator') and not default_user.active:
            db.session.delete(default_user)
            db.session.commit()
        user_datastore.add_role_to_user(user.email, 'Administrator')
        return
    user_datastore.add_role_to_user(user.email, 'User')
Exemplo n.º 9
0
    def create(self):
        data = request.form if request.form else json.loads(request.data.decode())
        if data[u'name'] != '':
            try:
                check_sg = ServerGroup.query.filter_by(
                    user_id=current_user.id,
                    name=data[u'name']).first()

                # Throw error if server group already exists...
                if check_sg is not None:
                    return make_json_response(
                        status=409,
                        success=0,
                        errormsg=gettext('Server group already exists')
                    )

                sg = ServerGroup(
                    user_id=current_user.id,
                    name=data[u'name'])
                db.session.add(sg)
                db.session.commit()

                data[u'id'] = sg.id
                data[u'name'] = sg.name

                return jsonify(
                    node=self.blueprint.generate_browser_node(
                        "%d" % (sg.id), None,
                        sg.name,
                        "icon-%s" % self.node_type,
                        True,
                        self.node_type,
                        can_delete=True  # This is user created hence can deleted
                    )
                )
            except Exception as e:
                return make_json_response(
                    status=410,
                    success=0,
                    errormsg=e.message)

        else:
            return make_json_response(
                status=417,
                success=0,
                errormsg=gettext('No server group name was specified'))
Exemplo n.º 10
0
    def create(self):
        """Creates new server-group """
        data = request.form if request.form else json.loads(
            request.data, encoding='utf-8'
        )
        if data['name'] != '':
            try:
                sg = ServerGroup(
                    user_id=current_user.id,
                    name=data['name'])
                db.session.add(sg)
                db.session.commit()

                data['id'] = sg.id
                data['name'] = sg.name

                return jsonify(
                    node=self.blueprint.generate_browser_node(
                        "%d" % sg.id,
                        None,
                        sg.name,
                        get_icon_css_class(sg.id, sg.user_id),
                        True,
                        self.node_type,
                        # This is user created hence can deleted
                        can_delete=True
                    )
                )
            except exc.IntegrityError:
                db.session.rollback()
                return bad_request(gettext(
                    "The specified server group already exists."
                ))

            except Exception as e:
                db.session.rollback()
                return make_json_response(
                    status=410,
                    success=0,
                    errormsg=e.message)

        else:
            return make_json_response(
                status=417,
                success=0,
                errormsg=gettext('No server group name was specified'))
Exemplo n.º 11
0
def load_database_servers(input_file, selected_servers,
                          load_user=current_user, from_setup=False):
    """Load server groups and servers.
    """
    user = _does_user_exist(load_user, from_setup)
    if user is None:
        return False, USER_NOT_FOUND % load_user

    # retrieve storage directory path
    storage_manager_path = None
    if not from_setup:
        storage_manager_path = get_storage_directory(user)

    # generate full path of file
    file_path = unquote(input_file)
    if storage_manager_path:
        # generate full path of file
        file_path = os.path.join(
            storage_manager_path,
            file_path.lstrip('/').lstrip('\\')
        )

    try:
        with open(file_path) as f:
            data = json.load(f)
    except json.decoder.JSONDecodeError as e:
        return _handle_error(gettext("Error parsing input file %s: %s" %
                             (file_path, e)), from_setup)
    except Exception as e:
        return _handle_error(gettext("Error reading input file %s: [%d] %s" %
                             (file_path, e.errno, e.strerror)), from_setup)

    f.close()

    user_id = user.id
    # Counters
    groups_added = 0
    servers_added = 0

    # Get the server groups
    groups = ServerGroup.query.filter_by(user_id=user_id)

    # Validate server data
    error_msg = validate_json_data(data, user.has_role("Administrator"))
    if error_msg is not None and from_setup:
        print(ADD_SERVERS_MSG % (groups_added, servers_added))
        return _handle_error(error_msg, from_setup)

    for server in data["Servers"]:
        if selected_servers is None or str(server) in selected_servers:
            obj = data["Servers"][server]

            # Get the group. Create if necessary
            group_id = next(
                (g.id for g in groups if g.name == obj["Group"]), -1)

            if group_id == -1:
                new_group = ServerGroup()
                new_group.name = obj["Group"]
                new_group.user_id = user_id
                db.session.add(new_group)

                try:
                    db.session.commit()
                except Exception as e:
                    if from_setup:
                        print(ADD_SERVERS_MSG % (groups_added, servers_added))
                    return _handle_error(
                        gettext("Error creating server group '%s': %s" %
                                (new_group.name, e)), from_setup)

                group_id = new_group.id
                groups_added = groups_added + 1
                groups = ServerGroup.query.filter_by(user_id=user_id)

            # Create the server
            new_server = Server()
            new_server.name = obj["Name"]
            new_server.servergroup_id = group_id
            new_server.user_id = user_id
            new_server.ssl_mode = obj["SSLMode"]
            new_server.maintenance_db = obj["MaintenanceDB"]

            new_server.host = obj.get("Host", None)

            new_server.hostaddr = obj.get("HostAddr", None)

            new_server.port = obj.get("Port", None)

            new_server.username = obj.get("Username", None)

            new_server.role = obj.get("Role", None)

            new_server.ssl_mode = obj["SSLMode"]

            new_server.comment = obj.get("Comment", None)

            new_server.db_res = obj.get("DBRestriction", None)

            new_server.passfile = obj.get("PassFile", None)

            new_server.sslcert = obj.get("SSLCert", None)

            new_server.sslkey = obj.get("SSLKey", None)

            new_server.sslrootcert = obj.get("SSLRootCert", None)

            new_server.sslcrl = obj.get("SSLCrl", None)

            new_server.sslcompression = obj.get("SSLCompression", None)

            new_server.bgcolor = obj.get("BGColor", None)

            new_server.fgcolor = obj.get("FGColor", None)

            new_server.service = obj.get("Service", None)

            new_server.connect_timeout = obj.get("Timeout", None)

            new_server.use_ssh_tunnel = obj.get("UseSSHTunnel", None)

            new_server.tunnel_host = obj.get("TunnelHost", None)

            new_server.tunnel_port = obj.get("TunnelPort", None)

            new_server.tunnel_username = obj.get("TunnelUsername", None)

            new_server.tunnel_authentication = \
                obj.get("TunnelAuthentication", None)

            new_server.shared = \
                obj.get("Shared", None)

            db.session.add(new_server)

            try:
                db.session.commit()
            except Exception as e:
                if from_setup:
                    print(ADD_SERVERS_MSG % (groups_added, servers_added))
                return _handle_error(gettext("Error creating server '%s': %s" %
                                             (new_server.name, e)), from_setup)

            servers_added = servers_added + 1

    msg = ADD_SERVERS_MSG % (groups_added, servers_added)
    print(msg)

    return True, msg
Exemplo n.º 12
0
        def add_to_pginstances(pg_arg):
            server_id = None
            try:
                component_name = pg_arg.get("component")
                component_port = pg_arg.get("port", 5432)
                component_host = pg_arg.get("host", "localhost")
                component_proj = pg_arg.get("project")
                component_db = pg_arg.get("db", "postgres")
                component_user = pg_arg.get("user", "postgres")
                gid = pg_arg.get("gid")
                sid = pg_arg.get("sid")
                servergroup_id = 1
                is_rds = pg_arg.get("rds")
                is_new = True
                discovery_id = "BigSQL PostgreSQL"
                if is_rds:
                    discovery_id = "RDS"
                    servername = component_name
                    server_group_name = pg_arg.get("region", "AWS RDS")
                    rds_serverGroup = ServerGroup.query.filter_by(
                        user_id=current_user.id,
                        name=server_group_name).order_by("id")
                    if rds_serverGroup.count() > 0:
                        servergroup = rds_serverGroup.first()
                        servergroup_id = servergroup.id
                    else:
                        try:
                            sg = ServerGroup(user_id=current_user.id,
                                             name=server_group_name)
                            db.session.add(sg)
                            db.session.commit()
                            servergroup_id = sg.id
                        except sqlite3.IntegrityError as e:
                            err_msg = str(e)
                            if err_msg.find("UNIQUE constraint failed") >= 0:
                                rds_serverGroup = ServerGroup.query.filter_by(
                                    user_id=current_user.id,
                                    name=server_group_name).order_by("id")
                                if rds_serverGroup.count() > 0:
                                    servergroup = rds_serverGroup.first()
                                    servergroup_id = servergroup.id
                            else:
                                print(err_msg)
                                result = {}
                                result['error'] = 1
                                result['msg'] = err_msg
                                return result
                else:
                    if gid:
                        servername = component_name
                        servergroup_id = gid
                        if sid:
                            component_server = Server.query.filter_by(
                                id=sid,
                                user_id=current_user.id,
                            ).first()
                            is_new = False

                    else:
                        servername = "{0}({1})".format(component_name,
                                                       component_host)

                        if component_host in ("localhost", ""):
                            component_host = "localhost"
                            servername = "{0}({1})".format(
                                component_name, component_host)
                        else:
                            import util
                            host_info = util.get_pgc_host(component_host)
                            component_host = host_info.get('host')
                        if component_host == '':
                            component_host = pg_arg.get("host", "localhost")
                        user_id = current_user.id
                        servergroups = ServerGroup.query.filter_by(
                            user_id=user_id).order_by("id")

                        if servergroups.count() > 0:
                            servergroup = servergroups.first()
                            servergroup_id = servergroup.id
                        else:
                            sg = ServerGroup(user_id=current_user.id,
                                             name="Servers")
                            db.session.add(sg)
                            db.session.commit()
                            servergroup_id = sg.id

                component_server = Server.query.filter_by(
                    name=servername,
                    host=component_host,
                    servergroup_id=servergroup_id,
                    port=component_port).first()
                if component_server:
                    is_new = False
                else:
                    is_new = True

                if is_new:
                    svr = Server(user_id=current_user.id,
                                 servergroup_id=servergroup_id,
                                 name=servername,
                                 host=component_host,
                                 port=component_port,
                                 maintenance_db=component_db,
                                 username=component_user,
                                 ssl_mode='prefer',
                                 comment=component_proj,
                                 discovery_id=discovery_id)

                    db_session.add(svr)
                    db_session.commit()
                    server_id = svr.id
                else:
                    component_server.servergroup_id = servergroup_id
                    component_server.name = servername
                    component_server.host = component_host
                    component_server.port = component_port
                    component_server.maintenance_db = component_db
                    component_server.username = component_user
                    db_session.commit()

            except Exception as e:
                print("Failed while adding/updating pg instance in metadata :")
                print(str(e))
                pass
            return server_id
Exemplo n.º 13
0
def load_servers(args):
    """Load server groups and servers.

    Args:
        args (ArgParser): The parsed command line options
    """

    # What user?
    load_user = args.user if args.user is not None else config.DESKTOP_USER

    # And the sqlite path
    if args.sqlite_path is not None:
        config.SQLITE_PATH = args.sqlite_path

    print('----------')
    print('Loading servers with:')
    print('User:'******'SQLite pgAdmin config:', config.SQLITE_PATH)
    print('----------')

    try:
        with open(args.load_servers) as f:
            data = json.load(f)
    except json.decoder.JSONDecodeError as e:
        print("Error parsing input file %s: %s" %
              (args.load_servers, e))
        sys.exit(1)
    except Exception as e:
        print("Error reading input file %s: [%d] %s" %
              (args.load_servers, e.errno, e.strerror))
        sys.exit(1)

    f.close()

    app = create_app(config.APP_NAME + '-cli')
    with app.app_context():
        user = User.query.filter_by(email=load_user).first()

        if user is None:
            print("The specified user ID (%s) could not be found." %
                  load_user)
            sys.exit(1)

        user_id = user.id

        # Counters
        groups_added = 0
        servers_added = 0

        # Get the server groups
        groups = ServerGroup.query.filter_by(user_id=user_id)

        def print_summary():
            print("Added %d Server Group(s) and %d Server(s)." %
                  (groups_added, servers_added))

        err_msg = _validate_servers_data(data, user.has_role("Administrator"))
        if err_msg is not None:
            print(err_msg)
            print_summary()
            sys.exit(1)

        for server in data["Servers"]:
            obj = data["Servers"][server]

            # Get the group. Create if necessary
            group_id = next(
                (g.id for g in groups if g.name == obj["Group"]), -1)

            if group_id == -1:
                new_group = ServerGroup()
                new_group.name = obj["Group"]
                new_group.user_id = user_id
                db.session.add(new_group)

                try:
                    db.session.commit()
                except Exception as e:
                    print("Error creating server group '%s': %s" %
                          (new_group.name, e))
                    print_summary()
                    sys.exit(1)

                group_id = new_group.id
                groups_added = groups_added + 1
                groups = ServerGroup.query.filter_by(user_id=user_id)

            # Create the server
            new_server = Server()
            new_server.name = obj["Name"]
            new_server.servergroup_id = group_id
            new_server.user_id = user_id
            new_server.ssl_mode = obj["SSLMode"]
            new_server.maintenance_db = obj["MaintenanceDB"]

            new_server.host = obj.get("Host", None)

            new_server.hostaddr = obj.get("HostAddr", None)

            new_server.port = obj.get("Port", None)

            new_server.username = obj.get("Username", None)

            new_server.role = obj.get("Role", None)

            new_server.ssl_mode = obj["SSLMode"]

            new_server.comment = obj.get("Comment", None)

            new_server.db_res = obj.get("DBRestriction", None)

            new_server.passfile = obj.get("PassFile", None)

            new_server.sslcert = obj.get("SSLCert", None)

            new_server.sslkey = obj.get("SSLKey", None)

            new_server.sslrootcert = obj.get("SSLRootCert", None)

            new_server.sslcrl = obj.get("SSLCrl", None)

            new_server.sslcompression = obj.get("SSLCompression", None)

            new_server.bgcolor = obj.get("BGColor", None)

            new_server.fgcolor = obj.get("FGColor", None)

            new_server.service = obj.get("Service", None)

            new_server.connect_timeout = obj.get("Timeout", None)

            new_server.use_ssh_tunnel = obj.get("UseSSHTunnel", None)

            new_server.tunnel_host = obj.get("TunnelHost", None)

            new_server.tunnel_port = obj.get("TunnelPort", None)

            new_server.tunnel_username = obj.get("TunnelUsername", None)

            new_server.tunnel_authentication = \
                obj.get("TunnelAuthentication", None)

            db.session.add(new_server)

            try:
                db.session.commit()
            except Exception as e:
                print("Error creating server '%s': %s" %
                      (new_server.name, e))
                print_summary()
                sys.exit(1)

            servers_added = servers_added + 1

        print_summary()
Exemplo n.º 14
0
def load_servers(args):
    """Load server groups and servers.

    Args:
        args (ArgParser): The parsed command line options
    """
    try:
        with open(args.load_servers) as f:
            data = json.load(f)
    except json.decoder.JSONDecodeError as e:
        print("Error parsing input file %s: %s" % (args.load_servers, e))
        sys.exit(1)
    except Exception as e:
        print("Error reading input file %s: [%d] %s" %
              (args.load_servers, e.errno, e.strerror))
        sys.exit(1)

    f.close()

    app = create_app()
    with app.app_context():

        # What user?
        if args.user is not None:
            dump_user = args.user
        else:
            dump_user = config.DESKTOP_USER

        user = User.query.filter_by(email=dump_user).first()

        if user is None:
            print("The specified user ID (%s) could not be found." % dump_user)
            sys.exit(1)

        user_id = user.id

        # Counters
        groups_added = 0
        servers_added = 0

        # Get the server group
        groups = ServerGroup.query.all()

        def print_summary():
            print("Added %d Server Group(s) and %d Server(s)." %
                  (groups_added, servers_added))

        # Loop through the servers...
        if "Servers" not in data:
            print("'Servers' attribute not found in file '%s'" %
                  args.load_servers)
            print_summary()
            sys.exit(1)

        for server in data["Servers"]:
            obj = data["Servers"][server]

            def check_attrib(attrib):
                if attrib not in obj:
                    print("'%s' attribute not found for server '%s'" %
                          (attrib, server))
                    print_summary()
                    sys.exit(1)

            check_attrib("Name")
            check_attrib("Group")
            check_attrib("Port")
            check_attrib("Username")
            check_attrib("SSLMode")
            check_attrib("MaintenanceDB")

            if "Host" not in obj and \
                "HostAddr" not in obj and \
                    "Service" not in obj:
                print("'Host', 'HostAddr' or 'Service' attribute not found "
                      "for server '%s'" % server)
                print_summary()
                sys.exit(1)

            # Get the group. Create if necessary
            group_id = -1
            for g in groups:
                if g.name == obj["Group"]:
                    group_id = g.id
                    break

            if group_id == -1:
                new_group = ServerGroup()
                new_group.name = obj["Group"]
                new_group.user_id = user_id
                db.session.add(new_group)

                try:
                    db.session.commit()
                except Exception as e:
                    print("Error creating server group '%s': %s" %
                          (new_group.name, e))
                    print_summary()
                    sys.exit(1)

                group_id = new_group.id
                groups_added = groups_added + 1
                groups = ServerGroup.query.all()

            # Create the server
            new_server = Server()
            new_server.name = obj["Name"]
            new_server.servergroup_id = group_id
            new_server.user_id = user_id

            new_server.host = obj["Host"]

            if "HostAddr" in obj:
                new_server.hostaddr = obj["HostAddr"]

            new_server.port = obj["Port"]
            new_server.maintenance_db = obj["MaintenanceDB"]
            new_server.username = obj["Username"]

            if "Role" in obj:
                new_server.role = obj["Role"]

            new_server.ssl_mode = obj["SSLMode"]

            if "Comment" in obj:
                new_server.comment = obj["Comment"]

            if "DBRestriction" in obj:
                new_server.db_res = obj["DBRestriction"]

            if "PassFile" in obj:
                new_server.passfile = obj["PassFile"]

            if "SSLCert" in obj:
                new_server.sslcert = obj["SSLCert"]

            if "SSLKey" in obj:
                new_server.sslkey = obj["SSLKey"]

            if "SSLRootCert" in obj:
                new_server.sslrootcert = obj["SSLRootCert"]

            if "SSLCrl" in obj:
                new_server.sslcrl = obj["SSLCrl"]

            if "SSLCompression" in obj:
                new_server.sslcompression = obj["SSLCompression"]

            if "BGColor" in obj:
                new_server.bgcolor = obj["BGColor"]

            if "FGColor" in obj:
                new_server.fgcolor = obj["FGColor"]

            if "Service" in obj:
                new_server.service = obj["Service"]

            if "Timeout" in obj:
                new_server.connect_timeout = obj["Timeout"]

            if "UseSSHTunnel" in obj:
                new_server.use_ssh_tunnel = obj["UseSSHTunnel"]

            if "TunnelHost" in obj:
                new_server.tunnel_host = obj["TunnelHost"]

            if "TunnelPort" in obj:
                new_server.tunnel_port = obj["TunnelPort"]

            if "TunnelUsername" in obj:
                new_server.tunnel_username = obj["TunnelUsername"]

            if "TunnelAuthentication" in obj:
                new_server.tunnel_authentication = obj["TunnelAuthentication"]

            db.session.add(new_server)

            try:
                db.session.commit()
            except Exception as e:
                print("Error creating server '%s': %s" % (new_server.name, e))
                print_summary()
                sys.exit(1)

            servers_added = servers_added + 1

        print_summary()
Exemplo n.º 15
0
def do_setup(app):
    """Create a new settings database from scratch"""

    if config.SERVER_MODE is False:
        print(u"NOTE: Configuring authentication for DESKTOP mode.")
        email = config.DESKTOP_USER
        p1 = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(32)
        ])

    else:
        print(u"NOTE: Configuring authentication for SERVER mode.\n")

        if all(value in os.environ
               for value in ['PGADMIN_SETUP_EMAIL', 'PGADMIN_SETUP_PASSWORD']):
            email = ''
            p1 = ''
            if os.environ['PGADMIN_SETUP_EMAIL'] and os.environ[
                    'PGADMIN_SETUP_PASSWORD']:
                email = os.environ['PGADMIN_SETUP_EMAIL']
                p1 = os.environ['PGADMIN_SETUP_PASSWORD']
        else:
            # Prompt the user for their default username and password.
            print(
                u"Enter the email address and password to use for the initial "
                u"pgAdmin user account:\n")

            email_filter = re.compile(
                "^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9]"
                "(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9]"
                "(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")

            email = input("Email address: ")
            while email == '' or not email_filter.match(email):
                print(u'Invalid email address. Please try again.')
                email = input("Email address: ")

            def pprompt():
                return getpass.getpass(), getpass.getpass('Retype password:'******'Passwords do not match. Please try again.')
                else:
                    print(
                        u'Password must be at least 6 characters. Please try again.'
                    )
                p1, p2 = pprompt()

    # Setup Flask-Security
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    Security(app, user_datastore)

    with app.app_context():
        password = encrypt_password(p1)

        db.create_all()
        user_datastore.create_role(name='Administrator',
                                   description='pgAdmin Administrator Role')
        user_datastore.create_role(name='User',
                                   description='pgAdmin User Role')
        user_datastore.create_user(email=email, password=password)
        db.session.flush()
        user_datastore.add_role_to_user(email, 'Administrator')

        # Get the user's ID and create the default server group
        user = User.query.filter_by(email=email).first()
        server_group = ServerGroup(user_id=user.id, name="Servers")
        db.session.merge(server_group)

        # Set the schema version
        version = Version(name='ConfigDB',
                          value=config.SETTINGS_SCHEMA_VERSION)
        db.session.merge(version)
        db.session.commit()

        # Create the keys
        key = Keys(name='CSRF_SESSION_KEY', value=config.CSRF_SESSION_KEY)
        db.session.merge(key)

        key = Keys(name='SECRET_KEY', value=config.SECRET_KEY)
        db.session.merge(key)

        key = Keys(name='SECURITY_PASSWORD_SALT',
                   value=config.SECURITY_PASSWORD_SALT)
        db.session.merge(key)

        db.session.commit()

    # Done!
    print(u"")
    print(u"The configuration database has been created at {0}".format(
        config.SQLITE_PATH))