local kong_meta = require "kong.meta"

local BearerTokenAuth = {PRIORITY = 1101, VERSION = kong_meta.version}

function BearerTokenAuth:access(conf)
    local bearer_token = kong.request.get_header("authorization")
    if not bearer_token then
        kong.log.info(
            "skip bear auth since no authorization header, trace_id: ",
            kong.ctx.shared.trace_id or "-")
        return
    end
    local match = ngx.re.match(bearer_token,"^[Bb]earer\\s.","oj")
    if match then
        kong.ctx.shared.has_authed = true
        kong.service.request.set_header("x-auth-method", "bear")
        kong.service.request.set_header("x-auth-raw", bearer_token)
        kong.service.request.clear_header("authorization")
    end
end

return BearerTokenAuth
