if (inargs['authRequestId'] && (!session['ch.nevis.auth.saml.request.id'] || inargs['authRequestId'] != session['ch.nevis.auth.saml.request.id'])) {
    // make sure we start from scratch
    def mInargs = request.getInArgs()
    mInargs.remove('email')
    mInargs.remove('recaptcha_sitekey')
    mInargs.remove('recaptcha_response')
    mInargs.remove('continue')
    mInargs.remove('authRequestId')
    mInargs.remove('cancel')
}

if (inargs['cd'] && session['agov.recovery.code']) {
  // we are called with a new URL --> make sure we start from scratch
  def s = request.getAuthSession(true)
  def sessionKeySet = new HashSet(session.keySet()) 
  sessionKeySet.each { key -> 
    if ( key ==~ /ch.nevis.idm.*/ || key ==~ /ch.adnovum.nevisidm.*/ || key ==~ /agov.recovery.*/ ) {
      s.removeAttribute(key)
    }
  }
}

if (!session['ch.nevis.auth.saml.request.id']) {
    response.setSessionAttribute('ch.nevis.auth.saml.request.id', java.util.UUID.randomUUID().toString())
}

def sourceIp = request.getLoginContext()['connection.HttpHeader.X-Real-IP'] ?: 'unknown'
def userAgent = request.getLoginContext()['connection.HttpHeader.user-agent'] ?: request.getLoginContext()['connection.HttpHeader.User-Agent'] ?: 'unknown'

response.setSessionAttribute('agov.recovery.ip', '' + sourceIp)
response.setSessionAttribute('agov.recovery.userAgent', '' + userAgent)

response.setResult('default')