import java.util.regex.Matcher;
import java.util.regex.Pattern;

def getPathFromURL(url) {
    def pattern = ~/https?.\/\/[^\/]+(\/[^\?]*|.*).*/
    def matcher = pattern.matcher(url)

    if (matcher.matches()) {
        return matcher.group(1)
    } else {
        return null
    }
}

if (request.getSession(false) == null) {
    LOG.debug("No session - create new session")
    session = request.getSession(true).getData()
}

def redirectionPath = getPathFromURL(request['currentResource'])
def applicationPaths = ["/dispatch/authentication","/nevisauth/","/register/","/pwreset/"]
def denyRegexes = [".*[\\n\\r]+.*"]

def denied = false
if (denyRegexes.size() > 0) {
    for (def denyRegex : denyRegexes) {
        def pattern = Pattern.compile(denyRegex)
        def matcher = pattern.matcher(redirectionPath)

        if (matcher.find()) {
            denied = true
        }
    }
    if (!denied) {
        session.put('redirect', redirectionPath)
        response.setResult('ok')
        return
    }
}


if (!applicationPaths.isEmpty()) {
    for (String path : applicationPaths) {
        if (redirectionPath.startsWith(path)) {
            session.put('redirect', path)
            response.setResult('ok')
            return
        }
    }
}

if (denied) {
    response.setResult('redirectionPathInvalid')
    return
} else {
    session.put('redirect', redirectionPath)
    response.setResult('ok')
    return
}
