No title

Anonymous Coward 2018-03-04 16:12:05.881162 UTC

1import Data.List (break, null, filter, take)
2
3data Email = MkEmail String deriving (Eq, Show, Ord)
4
5data User = MkUser
6 { userEmail :: Email
7 , userFullName :: String
8 , userPassword :: String
9
10 , userPostalCode :: String
11 , userStatus :: String
12 , userVerificationCode :: String
13 } deriving (Eq, Show, Ord)
14
15data NewUser = MkNewUser
16 { nuserEmail :: Email
17 , nuserFullName :: String
18 , nuserPassword :: String
19 , nuserPostalCode :: String
20 } deriving (Eq, Show, Ord)
21
22registerUser :: NewUser -> [User] -> [User]
23registerUser newUser@MkNewUser{nuserEmail=(MkEmail email)} userDb =
24 let user = MkUser
25 { userEmail = (nuserEmail newUser)
26 , userFullName = (nuserFullName newUser)
27 , userPassword = (nuserPassword newUser)
28 , userPostalCode = (nuserPostalCode newUser)
29 , userStatus = "unverified"
30 , userVerificationCode = (take 2 email) ++ (take 2 (nuserFullName newUser)) ++ (take 2 (nuserPostalCode newUser))
31 }
32 in (user:userDb)
33
34verifyUser :: Email -> String -> [User] -> (Bool, String, [User])
35verifyUser e code userDb =
36 let existingUsers = Data.List.filter (\u -> (userEmail u) == e) userDb
37 in if (Data.List.null existingUsers)
38 then (False, "No such user", userDb)
39 else let existingUser = head existingUsers
40 in if (code==(userVerificationCode existingUser))
41 then let verifiedUser = existingUser{userStatus="active"}
42 newUserDb = replaceUserInDb verifiedUser userDb
43 in (True, "Verified", newUserDb)
44 else (False, "Incorrect verification code", userDb)
45
46deactivateUser :: Email -> [User] -> (Bool, String, [User])
47deactivateUser e userDb =
48 let existingUsers = Data.List.filter (\u -> (userEmail u) == e) userDb
49 in if (Data.List.null existingUsers)
50 then (False, "No such user", userDb)
51 else let existingUser = head existingUsers
52 deactiveUser = existingUser{userStatus = "deactivated"}
53 in (True, "User deactivated", replaceUserInDb deactiveUser userDb)
54
55replaceUserInDb :: User -> [User] -> [User]
56replaceUserInDb u userDb =
57 let (a, b) = Data.List.break (\x -> (userEmail x)==(userEmail u)) userDb
58 in if (Data.List.null b)
59 then (a ++ [u])
60 else (a ++ (u:(tail b)))
61
62countUsers :: String -> [User] -> Int
63countUsers status userDb = length (filter (\u -> (userStatus u) == status) userDb)
64
65userStatusSummary :: [User] -> [(String, Int)]
66userStatusSummary userDb =
67 let statuses = ["unverified", "active", "deactivated"]
68 in map (\status -> (status, countUsers status userDb)) statuses
69