def EMAIL_REGEXP = '^(([^<>()\\[\\]\\\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\\\.,;:\\s@"]+)*)|(\\.\\+))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$'


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'


if ( inargs['cancelFido2'] && inargs['cancelFido2'] == 'cancelFido2') {
    response.setResult('cancel')
    return
}

if ( inargs['authRequestId'] && inargs['authRequestId'] != session['ch.nevis.auth.saml.request.id'] ) {
    response.setResult('timeout')
    return
}

if ( inargs['submit'] && inargs['submit'] == 'submit' ) {
  if (inargs['userInputValue_prompt.email'] && inargs['userInputValue_prompt.email'].matches(EMAIL_REGEXP)) {
    response.setResult('verifyEmail')
    return
  } else {
    LOG.warn("User attempted to bypass frontend emailvalidation with inavlid email: '${inargs['userInputValue_prompt.email']}', SourceIp=${sourceIp}, UserAgent='${userAgent}'")
    request.getInArgs().setProperty('userInputValue_prompt.email', 'inavalid@email.org')
    response.setResult('stay')
    return
  }
}

response.setResult('stay')
return
