Example #1
0
def configureRoles(gisInfo):
    localLogger.write("Creating roles")
    localLogger.incIndent()

    results = []
    try:
        for configRole in portal_config.roles:
            with localLogger.DisableAPILogging():
                existingRole = _findRole(gisInfo, configRole["name"])

            if existingRole == None:
                localLogger.write("Creating role: " + configRole["name"])
                with localLogger.DisableAPILogging():
                    result = gisInfo.gis.users.roles.create(name = configRole["name"],
                                                    description = configRole["description"],
                                                    privileges = configRole["privileges"])
                if result == None:
                    localLogger.write("ERROR: Failed to create role")
                    results.append(False)
                else:
                    gisInfo.waitForRole(result.name)
                    results.append(True)
            else:
                localLogger.write("Role already exists: " + existingRole.name)
                results.append(True)
        return all(results)
    except Exception as ex:
        localLogger.write(FormatExceptions("ERROR: Unexpected exception thrown", ex))
        return False
    finally:
        localLogger.decIndent()
Example #2
0
def configureSystemProperties(gisInfo):
    localLogger.write("Configuring system properties")
    localLogger.incIndent()

    try:
        if portal_config.systemProperties == None or len(portal_config.systemProperties) == 0:
            localLogger.write("No system properties to apply")
            return True

        system = gisInfo.gis.admin.system
        curProperties = system.properties
        updProperties = json.loads(json.dumps(curProperties))
        for k in portal_config.systemProperties:
            if k == "disableSignup":
               if portal_config.systemProperties[k] == True:
                   portal_config.systemProperties[k] = "true"
               elif portal_config.systemProperties[k] == False:
                   portal_config.systemProperties[k] = "false"
            updProperties[k] = portal_config.systemProperties[k]
        #
        # Check that we are actually going to update something, as calling update
        # will cause Portal to be restarted.
        #
        haveChanges = False
        for k in curProperties:
            if updProperties[k] != curProperties[k]:
                haveChanges = True
        for k in updProperties:
            if k not in curProperties:
                haveChanges = True

        if not haveChanges:
            localLogger.write("No system properties require changing")
            return True
        else:
            #
            # Using the following sends a gis.admin.system._con.get() call, which does not seem to work.
            # gis.admin.system.properties = updProperties
            # The following, therefore, uses a post command
            url = system._url + "/properties/update"
            params = {
                "f" : "json",
                "properties" : updProperties
            }
            localLogger.write("  Updating system properties - this may take several minutes")
            result = system._con.post(path=url, postdata=params)
            if "status" in result:
                return result["status"] == "success"
            else:
                return result
    except Exception as ex:
        localLogger.write(FormatExceptions("ERROR: Unexpected exception thrown", ex))
        return False
    finally:
        localLogger.decIndent()
Example #3
0
def configureSecurity(gisInfo):
    localLogger.write("Configuration security options")
    localLogger.incIndent()

    try:
        if portal_config.securityConfig == None or len(portal_config.securityConfig) == 0:
            localLogger.write("No security configuration to apply")
            return True

        updConfig = json.loads(json.dumps(gisInfo.gis.admin.security.config))
        #
        # Remove items we are not expecting
        #
        for k in ["userStoreConfig", "groupStoreConfig"]:
            if k in updConfig:
                del updConfig[k]

        localLogger.write("Current default role: " + updConfig["defaultRoleForUser"])
        #
        # Add in our changes
        #
        for k in portal_config.securityConfig:
            updConfig[k] = portal_config.securityConfig[k]
        #
        # If the defaultRoleForUser property is not account_user or account_publisher, search the
        # roles to find the named role and substitute it for the role id
        #
        if "defaultRoleForUser" in portal_config.securityConfig and \
            portal_config.securityConfig["defaultRoleForUser"] not in ["account_user", "account_publisher"]:

            roleName = portal_config.securityConfig["defaultRoleForUser"]
            existingRole = _findRole(gisInfo, roleName)
            if existingRole == None:
                localLogger.write("ERROR: Role defined for defaultRoleForUser property does not exist: " + roleName)
                localLogger.write("The security configuration has NOT been updated")
                return False
            updConfig["defaultRoleForUser"] = existingRole.role_id
        #
        # Update the configuration
        #
        gisInfo.gis.admin.security.config = updConfig
        return True
    except Exception as ex:
        localLogger.write(FormatExceptions("ERROR: Unexpected exception thrown", ex))
        return False
    finally:
        localLogger.decIndent()
Example #4
0
def installSSLCertificate(gisInfo):
    """
    Registering the certificate to be used by the Portal.
    """

    localLogger.write("Working on SSL Certificate")
    localLogger.incIndent()

    try:
        certificateAlias = portal_config.sslCertificates["alias"].lower()
        certToInstall = _checkIfCertificateExists(gisInfo, certificateAlias)
        localLogger.write("Checking if SSL Certificate exists")
        if certToInstall == None:
            localLogger.write("ERROR: Certificate with alias \"{}\" has not been registered".format(certificateAlias))
            return False

        installedCertificateAlias = gisInfo.gis.admin.security.ssl.properties["webServerCertificateAlias"]
        certToInstallAlias = _getCertificateAliasName(certToInstall)

        # Makes changes to existing Protocols and Ciphers regardless of installed certificate
        ssl_protocols = ",".join(portal_config.sslCertificates["ssl_protocols"])
        ssl_ciphers = ", ".join(portal_config.sslCertificates["cipher_suites"])
        localLogger.write("Editing existing SSL Protocols & Cipher Suites")
        gisInfo.gis.admin.security.ssl.update(certToInstallAlias,ssl_protocols, ssl_ciphers)

        if certToInstallAlias != installedCertificateAlias:
            #
            # Install the new certificate
            #
            localLogger.write("Registering certificate with alias \"{}\" as the portal certificate".format(certToInstallAlias))
            #portal_config.gis.admin.security.ssl.update(certToInstallAlias, portal_config.sslCertificates["ssl_protocols"],portal_config.sslCertificates["cipher_suites"])
            #
            # Now make the changes to existing Protocols and Ciphers
            #
            ssl_protocols = ",".join(portal_config.sslCertificates["ssl_protocols"])
            ssl_ciphers = ", ".join(portal_config.sslCertificates["cipher_suites"])
            localLogger.write("Editing SSL Protocols & Cipher Suites due to new certificate")
            gisInfo.gis.admin.security.ssl.update(certToInstallAlias, ssl_protocols, ssl_ciphers)
        else:
            localLogger.write("Certificate with alias \"{}\" is already installed as the portal certificate".format(certToInstallAlias))
        return True

    except Exception as ex:
        localLogger.write(FormatExceptions("ERROR: Unexpected exception thrown", ex))
        return False
    finally:
        localLogger.decIndent()
Example #5
0
def configureGeneralProperties(gisInfo):
    localLogger.write("Configuring general properties")
    localLogger.incIndent()

    try:
        if portal_config.generalProperties == None or len(portal_config.generalProperties) == 0:
            localLogger.write("No general properties to apply")
            return True

        updProperties = portal_config.generalProperties
        result = gisInfo.gis.update_properties(updProperties)
        return result
    except Exception as ex:
        localLogger.write(FormatExceptions("ERROR: Unexpected exception thrown", ex))
        return False
    finally:
        localLogger.decIndent()
Example #6
0
def createGroups(gisInfo):
    """Create groups using a CSV file called groups_trek.csv"""
    localLogger.write("Creating groups")
    localLogger.incIndent()
    results = []

    try:
        with open("groups_trek.csv", 'r') as groups_csv:
            groups = csv.DictReader(groups_csv)
            for group in groups:
                try:
                    foundGroup = None
                    for extgrp in gisInfo.allGroups:
                        if extgrp["title"].lower() == group["title"].lower():
                            foundGroup = extgrp

                    if foundGroup == None:
                        localLogger.write("Creating group: " + group['title'])
                        newGroup = gisInfo.gis.groups.create_from_dict(group)
                        if newGroup == None:
                            localLogger.write("  ERROR: Failed to create group {}".format(group["title"]))
                            results.append(False)
                        else:
                            gisInfo.waitForGroup(newGroup["title"])
                            results.append(True)
                    else:
                        localLogger.write("Group \"{}\" already exists".format(foundGroup["title"]))
                        results.append(True)
                except Exception as create_ex:
                    if "title" in group:
                        localLogger.write(FormatExceptions("ERROR: Failed to create group {}".format(group["title"]), create_ex))
                    else:
                        localLogger.write(FormatExceptions("ERROR: Failed to create group", create_ex))
                    results.append(False)
        return all(results)
    except Exception as ex:
        localLogger.write(FormatExceptions("ERROR: Unexpected exception thrown", ex))
        return False
    finally:
        localLogger.decIndent()
Example #7
0
def createUsers(gisInfo):
    """Create users using a CSV file called users_trek.csv"""
    localLogger.write("Creating users")
    localLogger.incIndent()
    results = []

    try:
        with open("users_large_trek.csv", 'r') as users_csv:
            users = csv.DictReader(users_csv)

            for user in users:
                foundUser = None
                result = True
                for extusr in gisInfo.allUsers:
                    if extusr["username"].lower() == user["username"].lower():
                        foundUser = extusr

                if foundUser == None:
                    localLogger.write("Creating user " + user['username'] + ", role " + user['role'])
                    try:
                        foundUser = gisInfo.createUser(user)
                        if foundUser == None:
                            localLogger.write("ERROR: Failed to create user {}".format(user["username"]))
                            result = False
                        else:
                            foundUser = gisInfo.waitForUser(foundUser["username"])
                    except Exception as ex:
                        localLogger.write(FormatExceptions("ERROR: Failed to create user {}".format(user["username"]), ex))
                        result = False
                else:
                    localLogger.write("User \"{}\" already exists".format(foundUser["username"]))
                #
                # The following will update the role of an existing user as well as a new user
                #
                if foundUser != None:
                    # Assign custom role to user
                    localLogger.write("  Assigning role: " + user['role'])
                    foundRole = _findRole(gisInfo, user['role'])
                    if foundRole == None:
                        localLogger.write("    ERROR: Undefined role: {}".format(user["role"]))
                        result = False
                    else:
                        try:
                            foundUser.update_role(foundRole)
                        except Exception as role_ex:
                            localLogger.write(FormatExceptions("ERROR: Failed to assign role \"{}\" to user".format(foundRole.name), role_ex))
                            result = False

                    # Now assign user to group(s)
                    localLogger.write("  Adding to groups:")
                    groups = user['groups']
                    group_list = [g for g in [grp.strip() for grp in groups.split(",")] if len(g) > 0]

                    # Search for the group
                    for g in group_list:
                        foundGroup = None
                        for grp in gisInfo.allGroups:
                            if grp["title"] == g:
                                foundGroup = grp

                        if foundGroup != None:
                            group_members = foundGroup.get_members()
                            if foundUser["username"] in group_members["users"]:
                                localLogger.write("    already a member of group \"{}\"".format(foundGroup["title"]))
                            else:
                                try:
                                    groups_result = foundGroup.add_users([foundUser["username"]])
                                    if len(groups_result['notAdded']) == 0:
                                        localLogger.write("    added to group \"{}\"".format(foundGroup["title"]))
                                    else:
                                        localLogger.write("    ERROR: Not added to group \"{}\"\n      result: {}".format(foundGroup["title"], groups_result))
                                        result = False
                                except Exception as groups_ex:
                                    localLogger.write(FormatExceptions("ERROR: Failed add user to group {}".format(foundGroup["title"]), groups_ex))
                                    result = False
                        else:
                            localLogger.write("    ERROR: Group \"{}\" not found".format(g))
                            result = False
        return all(results)
    except Exception as ex:
        localLogger.write(FormatExceptions("ERROR: Unexpected exception thrown", ex))
        return False
    finally:
        localLogger.decIndent()