From a4955d35faa11b56171cb4b232df58eee97e4dbc Mon Sep 17 00:00:00 2001 From: Ryan Cavicchioni Date: Sun, 9 Mar 2025 15:31:27 -0500 Subject: [PATCH] add configuration class --- app.rb | 13 ++++++++++--- lib/config.rb | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 3 deletions(-) create mode 100644 lib/config.rb diff --git a/app.rb b/app.rb index 8f06463..4c2914b 100644 --- a/app.rb +++ b/app.rb @@ -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 diff --git a/lib/config.rb b/lib/config.rb new file mode 100644 index 0000000..1b913bc --- /dev/null +++ b/lib/config.rb @@ -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