local http = require "resty.http"

local AuthServerHandler = {
    PRIORITY = 1000,
    VERSION = "1.0",
}

local function introspect_access_token(conf, access_token)
  local httpc = http:new()
  httpc:set_timeout(conf.connect_timeout)

  local res, err = httpc:request_uri(conf.authorization_endpoint, {
      method = "GET",
      ssl_verify = false,
      headers = {
        ["Content-Type"] = "application/json",
        ["Authorization"] = "Bearer " .. access_token
      },
      keepalive_timeout = conf.read_timeout,
      keepalive_pool = 10,
  })

  if not res then
    return kong.response.exit(503, { message = "Failed to introspect access token: " .. (err or "unknown error") })
  end

  if res.status ~= 200 then
      if res.status == 401 then
          kong.response.exit(401) -- unauthorized
      elseif res.status == 403 then
          kong.response.exit(403) -- forbidden
      end
      -- other errors
      return kong.response.exit(502, { message = "Authorization service returned error: " .. res.status .. " - " .. (res.body or "no response body") })
  end

  return true -- all is well
end

function AuthServerHandler:access(conf)
  local access_token = kong.request.get_headers()[conf.token_header]
  if not access_token then
      kong.response.exit(401)  --unauthorized
  end
  -- replace Bearer prefix
  access_token = access_token:sub(8,-1) -- drop "Bearer "
  introspect_access_token(conf, access_token)

  kong.service.request.clear_header(conf.token_header)
end

return AuthServerHandler
