61 lines
1.6 KiB
Ruby
Executable File
61 lines
1.6 KiB
Ruby
Executable File
#!/usr/bin/env ruby
|
|
|
|
require "cgi"
|
|
require "erb"
|
|
require "digest"
|
|
require "securerandom"
|
|
|
|
ASSETS_DIR = File.join(__dir__, "../assets")
|
|
DATA_DIR = File.join(__dir__, "../data")
|
|
SESSIONS_FILE = File.join(DATA_DIR, "sessions.txt")
|
|
USER_FILE = File.join(DATA_DIR, "user.txt")
|
|
|
|
cgi = CGI.new
|
|
|
|
hostname = File.read("/etc/hostname").strip rescue "localhost"
|
|
|
|
def valid_session?(token)
|
|
return false if token.nil? || token.empty?
|
|
return false unless File.exist?(SESSIONS_FILE)
|
|
File.readlines(SESSIONS_FILE).any? { |line| line.strip == token }
|
|
end
|
|
|
|
def check_credentials(username, password)
|
|
return false unless File.exist?(USER_FILE)
|
|
stored_user, salt, stored_hash_hex2 = File.read(USER_FILE).strip.split(":", 3)
|
|
return false unless username == stored_user
|
|
stored_hash = [stored_hash_hex2].pack("H*")
|
|
computed_hash = Digest::SHA256.hexdigest(salt + password)
|
|
stored_hash == computed_hash
|
|
end
|
|
|
|
def create_session
|
|
token = SecureRandom.hex(32)
|
|
File.open(SESSIONS_FILE, "a") { |f| f.puts(token) }
|
|
token
|
|
end
|
|
|
|
session_token = (cgi.cookies["MALP"] || []).first
|
|
authenticated = valid_session?(session_token)
|
|
cookie = nil
|
|
|
|
if cgi.request_method == "POST" && !authenticated
|
|
username = cgi.params["username"]&.first.to_s
|
|
password = cgi.params["password"]&.first.to_s
|
|
|
|
if check_credentials(username, password)
|
|
token = create_session
|
|
cookie = CGI::Cookie.new("name" => "MALP", "value" => token, "path" => "/")
|
|
authenticated = true
|
|
end
|
|
end
|
|
|
|
template = ERB.new(File.read(File.join(ASSETS_DIR, "page.erb")))
|
|
|
|
out_params = { "type" => "text/html", "charset" => "UTF-8" }
|
|
out_params["cookie"] = cookie if cookie
|
|
|
|
cgi.out(out_params) do
|
|
template.result(binding)
|
|
end
|