-- | A simple program to get a new password from the user and save it -- to a file. It's super secure! module Main where import Control.Monad (guard,msum) import Control.Monad.Trans (lift) import Control.Monad.Trans.Maybe (MaybeT,runMaybeT) import System.IO (hFlush,stdout) -- ** Get and save the password -- | Get a new password from the user. getPass :: IO String getPass = do putStr "Enter new password: " hFlush stdout getLine -- | Save the password. savePass :: String -> IO () savePass p = do writeFile "password.txt" (p ++ "\n") putStrLn "Saved." -- | Get a new password from the user and save it. newPass :: IO () newPass = getPass >>= savePass -- ** Only accept good passwords -- | Check to see if the provided password is a good one. isGood :: String -> Bool isGood p = p /= "password" && length p > 5 -- | Get a good password from the user, or Nothing. getGoodPass :: MaybeT IO String -- equivalent to: IO (Maybe String) getGoodPass = do p <- lift getPass guard (isGood p) return p -- | The password was bad, try again. tryAgain :: MaybeT IO String tryAgain = do lift $ putStrLn "Bad password! Try again." getGoodPass -- | Get a new good password from the user and save it. newGoodPass :: MaybeT IO () newGoodPass = msum (getGoodPass : repeat tryAgain) >>= lift . savePass -- do p <- msum (getGoodPass : repeat tryAgain) -- lift $ savePass p -- ** Main -- | Entry point to the program. main :: IO () main = runMaybeT newGoodPass >> return ()