malp/cgi-bin/malp.rb

76 lines
2.1 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 load_sessions
return [] unless File.exist?(SESSIONS_FILE)
now = Time.now.to_i
max_age = 3 * 7 * 24 * 60 * 60 # 3 weeks
sessions = File.readlines(SESSIONS_FILE).filter_map do |line|
token, timestamp = line.strip.split(":", 2)
next if token.nil? || token.empty?
[token, timestamp.to_i]
end
active, expired = sessions.partition { |_, ts| now - ts < max_age }
if expired.any?
File.write(SESSIONS_FILE, active.map { |t, ts| "#{t}:#{ts}" }.join("\n") + "\n")
end
active
end
def valid_session?(token)
return false if token.nil? || token.empty?
load_sessions.any? { |t, _| t == 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}:#{Time.now.to_i}") }
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