// restore roles and authentication level
// which may have been returned in the AuthnContext of the SAML Response
// example: saml.assertion.authnContextClassRef = auth.weak,2,urn:nevis:level:2
def context = notes['saml.assertion.authnContextClassRef']
if (context != null) {
    LOG.debug("SAML Response contains AuthnContextClassRef: $context")
    def roles = []
    Integer maximumLevel = null
    context.split(',').each { value ->
        if (value.startsWith('urn:nevis:level:')) {
            // remove prefix
            def level = Integer.parseInt(value.substring(16))
            LOG.debug("found level: $level")
            if (maximumLevel == null || level > maximumLevel) {
                maximumLevel = level
            }
        }
        else {
            LOG.debug("adding role $value from SAML Response / AuthnContext")
            roles.add(value)
        }
    }
    response.setAuthLevel("$maximumLevel")
    if (!roles.isEmpty()) {
        response.setActualRoles(roles as String[])
    }
}

// revoke token roles to ensure that Application Access Tokens are recreated (stepup)
def roles = []
response.actualRoles.each { role ->
    if (!role.startsWith('token.')) {
        roles.add(role)
    }
}
response.setActualRoles(roles as String[])

// ensure session exists
if (request.getSession(false) == null) {
    session = request.getSession(true).getData()
}

// store RelayState query parameter in the session to ensure user can be redirected
// the redirect is performed by a script in case post-processing steps are assigned
if (inargs.containsKey('RelayState')) {
    def value = inargs.get("RelayState")
    session.put('cached-RelayState', value)
}

// set transition to signal that the script has been successfully executed
response.setResult('ok')
