Skip to content

Commit 74b87cd

Browse files
authored
add askPassword (#37)
1 parent 9557ec3 commit 74b87cd

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
module AskPassword where
2+
3+
import Control.Monad.Trans.Except
4+
import Control.Monad.IO.Class (liftIO)
5+
import Data.Foldable (msum)
6+
import Data.Char (isNumber, isPunctuation)
7+
8+
9+
newtype PwdError = PwdError String
10+
11+
instance Monoid PwdError where
12+
-- mempty :: a
13+
mempty = PwdError ""
14+
15+
-- mappend :: a -> a -> a
16+
(PwdError x) `mappend` (PwdError y) = PwdError $ x `mappend` y
17+
18+
type PwdErrorMonad = ExceptT PwdError IO
19+
20+
21+
askPassword :: PwdErrorMonad ()
22+
askPassword = do
23+
liftIO $ putStrLn "Enter you new password:"
24+
value <- msum $ repeat getValidPassword
25+
liftIO $ putStrLn "Storing in database..."
26+
27+
28+
getValidPassword :: PwdErrorMonad String
29+
getValidPassword = do
30+
s <- liftIO getLine
31+
catchE (validatePassword s) reportError
32+
33+
34+
reportError :: PwdError -> PwdErrorMonad String
35+
reportError x@(PwdError e) = do
36+
liftIO $ putStrLn e
37+
throwE x
38+
39+
40+
validatePassword :: String -> PwdErrorMonad String
41+
validatePassword s | length s <= 8 = throwE $ PwdError "Incorrect input: password is too short!"
42+
| not (any isNumber s) = throwE $ PwdError "Incorrect input: password must contain some digits!"
43+
| not (any isPunctuation s) = throwE $ PwdError "Incorrect input: password must contain some punctuation!"
44+
| otherwise = return s

0 commit comments

Comments
 (0)