import ch.nevis.esauth.auth.states.saml.util.Communicator
import ch.nevis.esauth.auth.states.saml.util.Communicator.RelayStateProtection

def redirect(location) {
    outargs.put('nevis.transfer.type', 'redirect')
    outargs.put('nevis.transfer.destination', location)
}

// ServiceProviderState is not a finisher for AUTH_DONE
// thus the RelayState is stored in the session and the redirect is done here
// this is needed when a post-processing flow is assigned in the SAML SP Realm
def encodedRelayState = session.get('cached-RelayState')
if (encodedRelayState != null) {
    def communicator = new Communicator()
    communicator.setRelayStateProtection(RelayStateProtection.OBFUSCATED_AND_ENCODED)
    def url = communicator.decodeRelayState(encodedRelayState)
    if (url != null) {
        LOG.debug("redirecting to ${url} according to stored RelayState")
        session.remove('cached-RelayState')
        redirect(url)
    }
}
