diff --git a/src/Core/Configuration.hs b/src/Core/Configuration.hs index f02f157..77a146d 100644 --- 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" + ]