add configuration class

This commit is contained in:
Ryan Cavicchioni 2025-03-09 15:31:27 -05:00
parent aa907dfa5f
commit a4955d35fa
Signed by: ryanc
SSH Key Fingerprint: SHA256:KbXiwUnZnHFwFtt3Bytd+F3FN9pPHn1Z1cxMIE1TPbg
2 changed files with 60 additions and 3 deletions

13
app.rb
View File

@ -13,9 +13,14 @@ require "anyflake"
require "jwt"
SESSION_SECRET_HEX_LENGTH = 64
$LOAD_PATH.unshift File.dirname(__FILE__) + "/lib"
set :session_secret, ENV.fetch("SESSION_SECRET") { SecureRandom.hex(SESSION_SECRET_HEX_LENGTH) }
require "config"
SESSION_SECRET_HEX_LENGTH = 64
JWT_SECRET_HEX_LENGTH = 64
ENV_PREFIX = "KIPUNJI"
CLK_TCK = 100
PID_FILE_PATH = "/run/app/pid".freeze
@ -38,7 +43,9 @@ DURATION_PARTS = [
[1, "second", "s"]
].freeze
JWT_SECRET = SecureRandom.bytes(64).freeze
config = Config.new
set :session_secret, config.session_secret.unwrap
module Sinatra
module RequestHeadersHelper

50
lib/config.rb Normal file
View File

@ -0,0 +1,50 @@
require "sensitive"
class Config
attr_accessor :cat
attr_reader :jwt_secret, :session_secret
def initialize(prefix = ENV_PREFIX, jwt_secret = nil, session_secret = nil, cat = nil)
@prefix = prefix
@cat = cat
session_secret ||= ENV.fetch "SESSION_SECRET" do
SecureRandom.hex SESSION_SECRET_HEX_LENGTH
end
jwt_secret ||= fetch_env "JWT_SECRET" do
SecureRandom.hex JWT_SECRET_HEX_LENGTH
end
@session_secret = Sensitive.new session_secret
@jwt_secret = Sensitive.new jwt_secret
@cat ||= ENV.fetch "#{@prefix}_CAT", nil
end
def fetch_env(name, &)
ENV.fetch "#{@prefix}_#{name}", &
end
def as_json(options = nil)
{jwt_secret: jwt_secret, session_secret: @session_secret, cat: @cat}
end
def to_json(options = nil)
if options &&
options.key?(:pretty) &&
options[:pretty] == true
JSON.pretty_generate as_json(options)
else
JSON.generate as_json(options)
end
end
def session_secret=(v)
@session_secret = Sensitive.new v
end
def jwt_secret=(v)
@jwt_secret = Sensitive.new v
end
end