mod_http_authentication/mod_http_authentication.lua
changeset 2341 c6e86b74f62e
child 3446 05725785e3a6
equal deleted inserted replaced
2340:79432b859d21 2341:c6e86b74f62e
       
     1 
       
     2 module:set_global();
       
     3 
       
     4 local b64_decode = require "util.encodings".base64.decode;
       
     5 local server = require "net.http.server";
       
     6 
       
     7 local credentials = module:get_option_string("http_credentials", "username:secretpassword");
       
     8 local unauthed_endpoints = module:get_option_set("unauthenticated_http_endpoints", { "/http-bind", "/http-bind/" })._items;
       
     9 
       
    10 module:wrap_object_event(server._events, false, function (handlers, event_name, event_data)
       
    11 	local request = event_data.request;
       
    12 	if request and not unauthed_endpoints[request.path] then
       
    13 		local response = event_data.response;
       
    14 		local headers = request.headers;
       
    15 		if not headers.authorization then
       
    16 			response.headers.www_authenticate = ("Basic realm=%q"):format(module.host.."/"..module.name);
       
    17 			return 401;
       
    18 		end
       
    19 		local user_password = b64_decode(headers.authorization:match("%s(%S*)$"));
       
    20 		if user_password ~= credentials then
       
    21 			return 401;
       
    22 		end
       
    23 	end
       
    24 	return handlers(event_name, event_data);
       
    25 end);