|
| 1 | +module Web.Controller.Users where |
| 2 | + |
| 3 | +import Web.Controller.Prelude |
| 4 | +import Web.View.Users.Index |
| 5 | +import Web.View.Users.New |
| 6 | +import Web.View.Users.Edit |
| 7 | +import Web.View.Users.Show |
| 8 | + |
| 9 | +import qualified Web.Controller.Sessions () |
| 10 | + |
| 11 | +-- instance Confirmations.ConfirmationsControllerConfig User where |
| 12 | + |
| 13 | +instance Controller UsersController where |
| 14 | + action UsersAction = do |
| 15 | + users <- query @User |> fetch |
| 16 | + render IndexView { .. } |
| 17 | + |
| 18 | + action NewUserAction = do |
| 19 | + let user = newRecord |
| 20 | + render NewView { .. } |
| 21 | + |
| 22 | + action ShowUserAction { userId } = do |
| 23 | + user <- fetch userId |
| 24 | + render ShowView { .. } |
| 25 | + |
| 26 | + action EditUserAction { userId } = do |
| 27 | + user <- fetch userId |
| 28 | + render EditView { .. } |
| 29 | + |
| 30 | + action UpdateUserAction { userId } = do |
| 31 | + user <- fetch userId |
| 32 | + user |
| 33 | + |> buildUser |
| 34 | + |> ifValid \case |
| 35 | + Left user -> render EditView { .. } |
| 36 | + Right user -> do |
| 37 | + user <- user |> updateRecord |
| 38 | + setSuccessMessage "User updated" |
| 39 | + redirectTo EditUserAction { .. } |
| 40 | + |
| 41 | + action CreateUserAction = do |
| 42 | + let user = newRecord @User |
| 43 | + -- The value from the password confirmation input field. |
| 44 | + let passwordConfirmation = param @Text "passwordConfirmation" |
| 45 | + user |
| 46 | + |> fill @["email", "passwordHash"] |
| 47 | + -- We ensure that the error message doesn't include |
| 48 | + -- the entered password. |
| 49 | + |> validateField #passwordHash (isEqual passwordConfirmation |> withCustomErrorMessage "Passwords don't match") |
| 50 | + |> validateField #passwordHash nonEmpty |
| 51 | + |> validateField #email isEmail |
| 52 | + -- After this validation, since it's operation on the IO, we'll need to use >>=. |
| 53 | + |> validateIsUnique #email |
| 54 | + >>= ifValid \case |
| 55 | + Left user -> render NewView { .. } |
| 56 | + Right user -> do |
| 57 | + hashed <- hashPassword user.passwordHash |
| 58 | + user <- user |
| 59 | + |> set #passwordHash hashed |
| 60 | + |> createRecord |
| 61 | + setSuccessMessage "You have registered successfully" |
| 62 | + redirectToPath "/" |
| 63 | + |
| 64 | + action DeleteUserAction { userId } = do |
| 65 | + user <- fetch userId |
| 66 | + deleteRecord user |
| 67 | + setSuccessMessage "User deleted" |
| 68 | + redirectTo UsersAction |
| 69 | + |
| 70 | + -- action ConfirmUserAction { userId, confirmationToken } = Confirmations.confirmAction userId confirmationToken |
| 71 | + |
| 72 | + |
| 73 | +buildUser user = user |
| 74 | + |> fill @'["email", "passwordHash", "failedLoginAttempts", "logins", "isconfirmed"] |
| 75 | + |
0 commit comments