commit 66cf9d460076e0a6630fa6eff8acea62635954e2
parent 5072fb4df4033c1b94e9af47723abff81c726f01
Author: James Eversole <james@eversole.co>
Date: Tue, 20 Feb 2024 06:22:03 -0600
More explicit error handling and messages when required environment variables are missing
Diffstat:
1 file changed, 37 insertions(+), 6 deletions(-)
diff --git a/src/Core/Configuration.hs b/src/Core/Configuration.hs
@@ -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"
+ ]