-- nur "/geheim.php" soll passwortgeschützt sein if ( string.format('%s', lighty.env["uri.path"]) == "/geheim.php" ) then -- Passwörter dürfen nur per https eingegeben werden if (lighty.env["uri.scheme"] == "http") then lighty.header["Location"] = "https://" .. lighty.env["uri.authority"] .. lighty.env["request.uri"] return 302 end --[[ Config Variables ]] local dbConf = {} dbConf.database = 'pwdb' dbConf.username = 'fritz' dbConf.passwort = 'geheim' dbConf.hostname = '10.123.45.67' dbConf.port = "3306" --[[ Requires ]] -- Debian package: liblua5.1-socket2 -- required for Base64 De-/encoding. See: http://w3.impa.br/~diego/software/luasocket/home.html require("mime") -- Debian package: liblua5.1-sql-mysql-2 -- Lua Mysql Driver luasql = require("luasql.mysql") --[[ Function to send HTTP-Auth request ]] function doAuth() lighty.header["WWW-Authenticate"] = string.format('Basic realm="%s"', lighty.env["uri.authority"]) return 401 end --[[ Function to check Auth Creds against MySQL Database ]] local env = assert(luasql.mysql()) local con = assert(env:connect ( dbConf.database ,dbConf.username ,dbConf.passwort ,dbConf.hostname ,dbConf.port )) function checkAuthMySQL(user,pass) local res = con:execute(string.format([[ SELECT * FROM `pwtab` WHERE `name` = '%s' AND `passwort` = '%s' ]], user, pass) ) -- Die Tabelle wir in ein Array gespeichert local row = res:fetch ({}, "a") -- print(type(row)) -- close everything -- res:close() -- already closed because all the result set was consumed con:close() -- env:close() if (not row) then return false else lighty.req_env['REMOTE_USER'] = user return true end end -- MAIN --[[ Check for Authorization Header and force Basic Auth if not set. ]] if (not lighty.request.Authorization) then return doAuth() end --[[ Header found: check string for "Basic" and base64 encoded username & password - upb = User Password Base64 encoded ]] _, _, upb = string.find(lighty.request.Authorization, "^Basic%s+(.+)$") up = mime.unb64(upb) -- Base64 Decode _, _, username, passwort = string.find(up, "^(.+):(.+)$") -- split by ":" to get username and password supplied -- ============================================================================= -- In der DB steht das Passwort nicht im klartext drin, sondern verschlüsselt -- deshalb muss auch der Passwort-Hash und nicht das Passwort verglichen werden. -- -- hier wird aus dem Passwort der Passwort-Hash generiert -- local kommando = ("/usr/bin/php /etc/lighttpd/sha512crypt.php " .. passwort) ausgabe = assert (io.popen (kommando)) pwhash = ausgabe:read ("*l") -- read one line -- ============================================================================= if (not checkAuthMySQL(username, pwhash)) then return doAuth() end end -- return nothing to proceed normal operation return