moonming commented on a change in pull request #1029: feat: add basic-auth
plugin
URL: https://github.com/apache/incubator-apisix/pull/1029#discussion_r363637753
##########
File path: lua/apisix/plugins/basic-auth.lua
##########
@@ -0,0 +1,225 @@
+local core = require("apisix.core")
+local ngx = ngx
+local ngx_re = require("ngx.re")
+local json = require("apisix.core.json")
+
+local authorizations_etcd
+
+local lrucache = core.lrucache.new({
+ ttl = 300, count = 512
+})
+
+-- You can follow this document to write schema:
+-- https://github.com/Tencent/rapidjson/blob/master/bin/draft-04/schema
+-- rapidjson not supported `format` in draft-04 yet
+local schema = {
+ type = "object",
+ properties = {
+ enable = { type = "boolean", default = true, enum = { true, false } },
+ },
+}
+
+local plugin_name = "basic-auth"
+
+local function gen_key(username)
+ local key = "/authorizations/" .. username
+ return key
+end
+
+local _M = {
+ version = 0.1,
+ priority = 1802,
+ name = plugin_name,
+ schema = schema,
+}
+
+function _M.check_schema(conf)
+ local ok, err = core.schema.check(schema, conf)
+
+ if not ok then
+ return false, err
+ end
+
+ return true
+end
+
+local function extract_auth_header(authorization)
+
+ local function do_extract(auth)
+ local obj = { username = "", password = "" }
+
+ local m, err = ngx.re.match(auth, "Basic\\s(.+)")
+ if err then
+ -- error authorization
+ return nil, err
+ end
+
+ local decoded = ngx.decode_base64(m[1])
+
+ local res
+ res, err = ngx_re.split(decoded, ":")
+ if err then
+ return nil, "split authorization err:" .. err
+ end
+
+ obj.username = ngx.re.gsub(res[1], "\\s+", "")
+ obj.password = ngx.re.gsub(res[2], "\\s+", "")
+ core.log.info("plugin access phase, authorization: ", obj.username, ":
", obj.password)
+
+ return obj, nil
+ end
+
+ local matcher, err = lrucache(authorization, nil, do_extract,
authorization)
+
+ if matcher then
+ return matcher.username, matcher.password, err
+ else
+ return "", "", err
+ end
+
+
+end
+
+function _M.access(conf, ctx)
+ core.log.info("plugin access phase, conf: ", core.json.delay_encode(conf))
+
+ -- 0. check the plugin is enabled
+ if not conf.enable then
+ return
+ end
+
+
+ -- 1. extract authorization from header
+ local headers = ngx.req.get_headers()
+ if not headers.Authorization then
Review comment:
recommand use `local auth_header = core.request.header(ctx, "Authorization")`
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
With regards,
Apache Git Services