More explicit error handling and messages when required environment variables are missing

This commit is contained in:
James Eversole 2024-02-20 06:22:03 -06:00
parent 5072fb4df4
commit 66cf9d4600

View File

@ -1,7 +1,11 @@
module Core.Configuration where
module Core.Configuration ( adminEmail, appPort
, confLinkLength, dataPath, dbPath
, encKey, getRuntimeEnvironment
, keyFileInit, main) where
import qualified Data.ByteString as B
import Control.Monad (mapM)
import Core.Types
import Crypto.Saltine.Core.SecretBox (newKey)
import Crypto.Saltine.Class (encode)
@ -9,13 +13,35 @@ import Configuration.Dotenv
import System.Directory (doesFileExist)
import System.Environment (getEnv, lookupEnv)
-- Make the dotenv file configuration available if PURRNOFILE is not present
-- Load environment variables from dotenv file if required
main :: IO ()
main = do
envFile <- lookupEnv "PURRNOFILE"
case envFile of
Nothing -> loadFile defaultConfig
_ -> putStrLn "Not using dotenv file"
reqEnvLookup <- getRequiredEnv
if (Nothing `elem` reqEnvLookup)
then checkEnvFile requiredEnvVars
else pure ()
where
getRequiredEnv :: IO [Maybe String]
getRequiredEnv = mapM (\s -> lookupEnv s) requiredEnvVars
checkEnvFile :: [String] -> IO ()
checkEnvFile requiredEnv = do
dotEnvExists <- doesFileExist "./.env"
if dotEnvExists
then do
loadFile defaultConfig
fromEnvFile <- getRequiredEnv
if (Nothing `elem` fromEnvFile)
then error $ missingEnvMsg requiredEnv
else pure ()
else error $ "Cannot find .env file in application directory.\n"
++ missingEnvMsg requiredEnv
missingEnvMsg :: [String] -> String
missingEnvMsg required =
"Missing required environment variable(s).\n"
++ "All required environment variables:\n"
++ unlines required
-- Check if an encryption key exists on the filesystem and create one if not
keyFileInit :: IO ()
@ -53,3 +79,8 @@ dbPath = "data/Purr.sqlite"
confLinkLength :: IO String
confLinkLength = getEnv "LINKLENGTH"
requiredEnvVars :: [String]
requiredEnvVars = [ "ADMINEMAIL", "APPLICATIONHOST", "APPLICATIONPORT"
, "DATADIR", "ENVIRONMENT", "LINKLENGTH"
]