package.path = package.path .. ";/opt/nevisproxy/webapp/WEB-INF/lib/lua/Utils.lua"
local Utils = require "Utils"

function inputHeader(request, response)
   local trace = request:getTracer()

   local cookies = Utils.parseCookieHeader(request)
   local token = nil
   local language = nil

   for name, value in pairs(cookies) do
       if (name == "agovRecoveryCode" and value) then
           token = value
       end
       if (name == "LANG" and value) then
           language = value
       end
   end

   if (token and language) then

       local jwtHandler = nevis.util.jwt.new()

       local publickey = param_auth_signer_key:gsub("<br>", "\n")
       trace:debug("public key: '" .. publickey .. "'")

       local newPublickey = param_auth_signer_new_key:gsub("<br>", "\n")
       trace:debug("new public key: '" .. newPublickey .. "'")

       local base64 = nevis.crypto.base64.new()
       token = base64:decode(token)
       trace:debug("token: " .. token)

       local verified = jwtHandler:verifySignature(token, "rs256", publickey)

       if not verified and newPublickey ~= "none" then
          trace:notice("AGOV: Check key rotation, using new public key to validate JWT token")
          verified = jwtHandler:verifySignature(token, "rs256", newPublickey)
       end

       if not verified then
          trace:error("Blocking request: Invalid JWT : '" .. token .. "'")
          response:setBody("Blocking request: Invalid JWT")
          response:send(403)
       else
          local jwtPayload = string.gsub(token, "^.*%.([^%.]+)%..*$", "%1")

          local padding = string.len(jwtPayload) % 4
          while (padding > 0) do
              padding = padding - 1
              jwtPayload = jwtPayload .. "="
          end

          trace:debug("jwtPayload: " .. jwtPayload)

          local json = base64:decode(jwtPayload)
          trace:debug("json: " .. json)

          local userId = string.gsub(json, '^.*%"sub%"%:%"([^%"]+).*$', "%1")
          trace:info("userId: " .. userId)
          local sessionId = string.gsub(json, '^.*%"sessionId%"%:([^,]+).*$', "%1")
          trace:info("sessionId: " .. sessionId)

          local query = request:getQuery()
          if query then
              query = query.."&userId="..userId.."&userSessionId="..sessionId.."&language="..language
          else
              query = "userId="..userId.."&userSessionId="..sessionId.."&language="..language
          end
          request:removeHeader("Cookie")
          request:setQuery(query)
       end

    else
       trace:error("Accessed recovery pdf endpoint without required cookies")
       response:send(404)
    end
end
