/
Main.elm
304 lines (253 loc) · 9.6 KB
/
Main.elm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
module Main exposing (..)
import Html exposing (..)
import Html.App as Html
import Html.Events exposing (..)
import Html.Attributes exposing (..)
import String
import Http
import Http.Decorators
import Task exposing (Task)
import Json.Decode as Decode exposing (..)
import Json.Encode as Encode exposing (..)
main : Program Never
main =
Html.program
{ init = init
, update = update
, subscriptions = \_ -> Sub.none
, view = view
}
{-
MODEL
* Model type
* Initialize model with empty values
* Initialize with a random quote
-}
type alias Model =
{ username : String
, password : String
, token : String
, quote : String
, protectedQuote : String
, errorMsg : String
}
init : (Model, Cmd Msg)
init =
( Model "" "" "" "" "" "", fetchRandomQuoteCmd )
{-
UPDATE
* API routes
* GET and POST
* Encode request body
* Decode responses
* Messages
* Update case
-}
-- API request URLs
api : String
api =
"http://localhost:3001/"
randomQuoteUrl : String
randomQuoteUrl =
api ++ "api/random-quote"
registerUrl : String
registerUrl =
api ++ "users"
loginUrl : String
loginUrl =
api ++ "sessions/create"
protectedQuoteUrl : String
protectedQuoteUrl =
api ++ "api/protected/random-quote"
-- GET a random quote (unauthenticated)
fetchRandomQuote : Platform.Task Http.Error String
fetchRandomQuote =
Http.getString randomQuoteUrl
fetchRandomQuoteCmd : Cmd Msg
fetchRandomQuoteCmd =
Task.perform HttpError FetchQuoteSuccess fetchRandomQuote
-- Encode user to construct POST request body (for Register and Log In)
userEncoder : Model -> Encode.Value
userEncoder model =
Encode.object
[ ("username", Encode.string model.username)
, ("password", Encode.string model.password)
]
-- POST register / login request
authUser : Model -> String -> Task Http.Error String
authUser model apiUrl =
{ verb = "POST"
, headers = [ ("Content-Type", "application/json") ]
, url = apiUrl
, body = Http.string <| Encode.encode 0 <| userEncoder model
}
|> Http.send Http.defaultSettings
|> Http.fromJson tokenDecoder
authUserCmd : Model -> String -> Cmd Msg
authUserCmd model apiUrl =
Task.perform AuthError GetTokenSuccess <| authUser model apiUrl
-- Decode POST response to get token
tokenDecoder : Decoder String
tokenDecoder =
"id_token" := Decode.string
-- GET request for random protected quote (authenticated)
fetchProtectedQuote : Model -> Task Http.Error String
fetchProtectedQuote model =
{ verb = "GET"
, headers = [ ("Authorization", "Bearer " ++ model.token) ]
, url = protectedQuoteUrl
, body = Http.empty
}
|> Http.send Http.defaultSettings
|> Http.Decorators.interpretStatus -- decorates Http.send result so error type is Http.Error instead of RawError
|> Task.map responseText
fetchProtectedQuoteCmd : Model -> Cmd Msg
fetchProtectedQuoteCmd model =
Task.perform HttpError FetchProtectedQuoteSuccess <| fetchProtectedQuote model
-- Extract GET plain text response to get protected quote
responseText : Http.Response -> String
responseText response =
case response.value of
Http.Text t ->
t
_ ->
""
-- Messages
type Msg
= GetQuote
| FetchQuoteSuccess String
| HttpError Http.Error
| AuthError Http.Error
| SetUsername String
| SetPassword String
| ClickRegisterUser
| ClickLogIn
| GetTokenSuccess String
| GetProtectedQuote
| FetchProtectedQuoteSuccess String
| LogOut
-- Update
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
GetQuote ->
( model, fetchRandomQuoteCmd )
FetchQuoteSuccess newQuote ->
( { model | quote = newQuote }, Cmd.none )
HttpError _ ->
( model, Cmd.none )
AuthError error ->
( { model | errorMsg = (toString error) }, Cmd.none )
SetUsername username ->
( { model | username = username }, Cmd.none )
SetPassword password ->
( { model | password = password }, Cmd.none )
ClickRegisterUser ->
( model, authUserCmd model registerUrl )
ClickLogIn ->
( model, authUserCmd model loginUrl )
GetTokenSuccess newToken ->
( { model | token = newToken, password = "", errorMsg = "" }, Cmd.none )
GetProtectedQuote ->
( model, fetchProtectedQuoteCmd model )
FetchProtectedQuoteSuccess newPQuote ->
( { model | protectedQuote = newPQuote }, Cmd.none )
LogOut ->
( { model | username = "", protectedQuote = "", token = "" }, Cmd.none )
{-
VIEW
* Hide sections of view depending on authenticaton state of model
* Get a quote
* Log In or Register
* Get a protected quote
-}
view : Model -> Html Msg
view model =
let
-- Is the user logged in?
loggedIn : Bool
loggedIn =
if String.length model.token > 0 then True else False
-- If the user is logged in, show a greeting; if logged out, show the login/register form
authBoxView =
let
-- If there is an error on authentication, show the error alert
showError : String
showError =
if String.isEmpty model.errorMsg then "hidden" else ""
-- Greet a logged in user by username
greeting : String
greeting =
"Hello, " ++ model.username ++ "!"
in
if loggedIn then
div [id "greeting" ][
h3 [ class "text-center" ] [ text greeting ]
, p [ class "text-center" ] [ text "You have super-secret access to protected quotes." ]
, p [ class "text-center" ] [
button [ class "btn btn-danger", onClick LogOut ] [ text "Log Out" ]
]
]
else
div [ id "form" ] [
h2 [ class "text-center" ] [ text "Log In or Register" ]
, p [ class "help-block" ] [ text "If you already have an account, please Log In. Otherwise, enter your desired username and password and Register." ]
, div [ class showError ] [
div [ class "alert alert-danger" ] [ text model.errorMsg ]
]
, div [ class "form-group row" ] [
div [ class "col-md-offset-2 col-md-8" ] [
label [ for "username" ] [ text "Username:" ]
, input [ id "username", type' "text", class "form-control", Html.Attributes.value model.username, onInput SetUsername ] []
]
]
, div [ class "form-group row" ] [
div [ class "col-md-offset-2 col-md-8" ] [
label [ for "password" ] [ text "Password:" ]
, input [ id "password", type' "password", class "form-control", Html.Attributes.value model.password, onInput SetPassword ] []
]
]
, div [ class "text-center" ] [
button [ class "btn btn-primary", onClick ClickLogIn ] [ text "Log In" ]
, button [ class "btn btn-link", onClick ClickRegisterUser ] [ text "Register" ]
]
]
-- If user is logged in, show button and quote; if logged out, show a message instructing them to log in
protectedQuoteView =
let
-- If no protected quote, apply a class of "hidden"
hideIfNoProtectedQuote : String
hideIfNoProtectedQuote =
if String.isEmpty model.protectedQuote then "hidden" else ""
in
if loggedIn then
div [] [
p [ class "text-center" ] [
button [ class "btn btn-info", onClick GetProtectedQuote ] [ text "Grab a protected quote!" ]
]
-- Blockquote with protected quote: only show if a protectedQuote is present in model
, blockquote [ class hideIfNoProtectedQuote ] [
p [] [text model.protectedQuote]
]
]
else
p [ class "text-center" ] [ text "Please log in or register to see protected quotes." ]
in
div [ class "container" ] [
h2 [ class "text-center" ] [ text "Chuck Norris Quotes" ]
, p [ class "text-center" ] [
button [ class "btn btn-success", onClick GetQuote ] [ text "Grab a quote!" ]
]
-- Blockquote with quote
, blockquote [] [
p [] [text model.quote]
]
, div [ class "jumbotron text-left" ] [
-- Login/Register form or user greeting
authBoxView
], div [] [
h2 [ class "text-center" ] [ text "Protected Chuck Norris Quotes" ]
-- Protected quotes
, protectedQuoteView
]
]