Protection against non-parsable Accept-Language header

This commit is contained in:
Claude Brisson
2024-05-09 06:53:38 +02:00
parent c79344c3d1
commit 539ece97f4
2 changed files with 11 additions and 1 deletions

View File

@@ -2,6 +2,7 @@ package org.jeudego.pairgoth.view
import org.apache.velocity.tools.config.ValidScope import org.apache.velocity.tools.config.ValidScope
import org.jeudego.pairgoth.web.WebappManager import org.jeudego.pairgoth.web.WebappManager
import org.slf4j.LoggerFactory
import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletRequest
@ValidScope("request") @ValidScope("request")
@@ -19,12 +20,15 @@ class CountriesTool {
countries[iso]?.let { name -> countries[iso]?.let { name ->
Pair(iso, name) Pair(iso, name)
} }
} ?: null.also {
logger.warn("could not get country from Accept-Language header: ${request.getHeader("Accept-Language")}")
} }
} }
public fun getCountries() = countries.entries.sortedBy { it.value } public fun getCountries() = countries.entries.sortedBy { it.value }
companion object { companion object {
val logger = LoggerFactory.getLogger("view")
private val langHeaderParser = Regex("(?:\\b(\\*|[a-z]{2})(?:(?:_|-)([a-z]{2}))?)(?:;q=([0-9.]+))?", RegexOption.IGNORE_CASE) private val langHeaderParser = Regex("(?:\\b(\\*|[a-z]{2})(?:(?:_|-)([a-z]{2}))?)(?:;q=([0-9.]+))?", RegexOption.IGNORE_CASE)
public val countries = mapOf( public val countries = mapOf(
"ad" to "Andorra", "ad" to "Andorra",

View File

@@ -25,7 +25,13 @@
<span class="info"></span> <span class="info"></span>
<select name="country" placeholder="country"> <select name="country" placeholder="country">
<option></option> <option></option>
#set($defaultCountry = $countries.country.first) #set($countryFromPreferredLanguage = $countries.country)
#if($countryFromPreferredLanguage)
#set($defaultCountry = $countryFromPreferredLanguage.first)
#else
## Accept-Language could not be parsed
#set($defaultCountry = 'en')
#end
#foreach($country in $countries.countries) #foreach($country in $countries.countries)
<option value="$country.key" #if($tour && $country.key.toLowerCase() == $tour.country.toLowerCase() || !$tour && $country.key.toLowerCase() == $defaultCountry.toLowerCase()) selected #end>$country.value</option> <option value="$country.key" #if($tour && $country.key.toLowerCase() == $tour.country.toLowerCase() || !$tour && $country.key.toLowerCase() == $defaultCountry.toLowerCase()) selected #end>$country.value</option>
#end #end