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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
|
{-# LANGUAGE NoCPP #-}
module Foundation where
import Import.NoFoundation
import Database.Persist.Sql (ConnectionPool, runSqlPool)
import qualified Yesod.Auth.Message as AuthMsg
import Text.Hamlet (hamletFile)
import Text.Jasmine (minifym)
import Yesod.Core.Types (Logger)
import Yesod.Default.Util (addStaticContentExternal)
import Yesod.Auth.Email
import Network.Mail.Mime
import Text.Shakespeare.Text (stext)
import Text.Blaze.Html.Renderer.Utf8 (renderHtml)
import Text.Cassius (PixelSize (..))
import Model.Unit (Unit (..))
import Model.Amount (Amount (..))
import qualified Database.Esqueleto as E
import qualified Yesod.Core.Unsafe as Unsafe
-- | The foundation datatype for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data App = App
{ appNavbar :: WidgetT App IO ()
, appSettings :: AppSettings
, appStatic :: Static -- ^ Settings for static file serving.
, appConnPool :: ConnectionPool -- ^ Database connection pool.
, appHttpManager :: Manager
, appLogger :: Logger
}
instance HasHttpManager App where
getHttpManager = appHttpManager
-- Set up i18n messages. See the message folder.
mkMessage "App" "messages" "en"
getUnitMsg :: (MonadHandler m, RenderMessage (HandlerSite m) AppMessage) => Unit -> m Text
getUnitMsg unit = do
mr <- getMessageRender
return $ mr $ unitToMsg unit
where
unitToMsg :: Unit -> AppMessage
unitToMsg Unit = MsgUnitUnit
unitToMsg Gram = MsgUnitGram
unitToMsg Litre = MsgUnitLitre
setMessageILevel :: (MonadHandler m, RenderMessage (HandlerSite m) msg) => Text -> msg -> m ()
setMessageILevel level msg = do
mr <- getMessageRender
let msgr = mr msg
setMessage $ [shamlet|
<div class="alert alert-dismissable #{level}" #message>
<a class="close" data-dismiss="alert" aria-hidden="true">×
\#{msgr}
|]
isAdmin :: User -> Bool
isAdmin user = userEmail user == "gueux@capeo"
authShopVendor :: ShopId -> User -> HandlerT App IO AuthResult
authShopVendor shopId user
| isAdmin user = return Authorized
| otherwise = do
shop <- runDB $ get404 shopId
suser <- runDB $ get404 $ shopVendor shop
authEqual suser user
authShop :: ShopId -> HandlerT App IO AuthResult
authShop shopId = maybeAuth
>>= maybe (return AuthenticationRequired)
(authShopVendor shopId . entityVal)
authShopDelivery :: ShopDeliveryId -> HandlerT App IO AuthResult
authShopDelivery shopdeliveryid = maybeAuth
>>= maybe (return AuthenticationRequired)
authShopDeliveryAux
where
authShopDeliveryAux euser = do
shopdelivery <- runDB $ get404 shopdeliveryid
authShopVendor (shopDeliveryShop shopdelivery) $ entityVal euser
authEqual :: Eq a => a -> a -> HandlerT App IO AuthResult
authEqual a b
| a == b = return Authorized
| otherwise = unauthorizedI MsgNotAuthorized
authUserAux :: UserId -> Entity User -> HandlerT App IO AuthResult
authUserAux userId euser
| isAdmin user = return Authorized
| otherwise = authEqual userId key
where
Entity key user = euser
authUser :: UserId -> HandlerT App IO AuthResult
authUser userId = maybeAuth
>>= maybe (return AuthenticationRequired) (authUserAux userId)
authAuthentified :: HandlerT App IO AuthResult
authAuthentified = maybeAuthId
>>= maybe (return AuthenticationRequired) (const $ return Authorized)
authNotAuthentified :: HandlerT App IO AuthResult
authNotAuthentified = maybeAuthId
>>= maybe (return Authorized) (const $ unauthorizedI MsgLogoutFirst)
formLayout :: BootstrapFormLayout
formLayout = BootstrapHorizontalForm {
bflLabelOffset = ColSm 0
, bflLabelSize = ColSm 2
, bflInputOffset = ColSm 0
, bflInputSize = ColSm 8
}
quantityPrice :: Amount -> Quantity -> Amount
quantityPrice unitprice = (*) unitprice . toAmount
quantityItemPrice :: Item -> CartItem -> Amount
quantityItemPrice i = quantityPrice (itemPrice i) . cartItemQuantity
cartAmount' :: UserId -> HandlerT App IO Amount
cartAmount' userid = do
cart <- runDB $
E.select $
E.from $ \(i, si) -> do
E.where_ ( si E.^. CartItemCustomer E.==. E.val userid
E.&&. si E.^. CartItemItem E.==. i E.^. ItemId
)
return (i, si)
return $ foldr addCart (Amount 0) cart
where
addCart (ei, esi) = (+) $ quantityItemPrice (entityVal ei) (entityVal esi)
getCartId :: UserId -> HandlerT App IO CartId
getCartId userid = runDB (getBy $ UniqueCustomer userid)
>>= maybe (insertCart userid) (return . entityKey)
where
insertCart userid' = do
date <- liftIO getCurrentTime
runDB $ insert $ Cart userid' date date (Amount 0)
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://www.yesodweb.com/book/routing-and-handlers
--
-- Note that this is really half the story; in Application.hs, mkYesodDispatch
-- generates the rest of the code. Please see the linked documentation for an
-- explanation for this split.
mkYesodData "App" $(parseRoutesFile "config/routes")
-- | A convenient synonym for creating forms.
type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget)
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod App where
-- Controls the base of generated URLs. For more information on modifying,
-- see: https://github.com/yesodweb/yesod/wiki/Overriding-approot
approot = ApprootMaster $ appRoot . appSettings
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ = Just <$> defaultClientSessionBackend
120 -- timeout in minutes
"config/client_session_key.aes"
defaultLayout widget = do
master <- getYesod
mmsg <- getMessage
mr <- getMessageRender
let thumbnailHeight = PixelSize $ toRational $ appThumbnailHeight $ appSettings master
thumbnailWidth = PixelSize $ toRational $ appThumbnailWidth $ appSettings master
cartThumbnailHeight = PixelSize $ toRational $ appCartThumbnailHeight $ appSettings master
cartThumbnailWidth = PixelSize $ toRational $ appCartThumbnailWidth $ appSettings master
navbar = appNavbar master
-- We break up the default layout into two components:
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
-- value passed to hamletToRepHtml cannot be a widget, this allows
-- you to use normal widget features in default-layout.
pc <- widgetToPageContent $ do
$(combineStylesheets 'StaticR
[ css_bootstrap_css
])
$(combineScripts 'StaticR
[ js_jquery_min_js
, js_bootstrap_min_js
])
navbar
$(widgetFile "default-layout")
withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")
-- The page to be redirected to when authentication is required.
authRoute _ = Just LoginPanelR
-- Authorizations for various routes
isAuthorized HomeR _ = return Authorized
isAuthorized (ShopR _) _ = return Authorized
isAuthorized ShopListR True = authAuthentified
isAuthorized ShopListR False = return Authorized
isAuthorized (ShopAdminR shopid) _ = authShop shopid
isAuthorized (ShopEditR shopid) writeBool = isAuthorized (ShopAdminR shopid) writeBool
isAuthorized (ShopDeleteR shopid) writeBool = isAuthorized (ShopEditR shopid) writeBool
isAuthorized (ItemEditR itemId) writeBool = do
item <- runDB $ get404 itemId
shopdelivery <- runDB $ get404 $ itemShopdelivery item
isAuthorized (ShopAdminR $ shopDeliveryShop shopdelivery) writeBool
isAuthorized (ItemDeleteR itemid) writeBool = isAuthorized (ItemEditR itemid) writeBool
isAuthorized (ImageR _) _ = return Authorized
isAuthorized (ImageListR userid) _ = authUser userid
isAuthorized (ImageDeleteR userid _) writeBool = isAuthorized (ImageListR userid) writeBool
isAuthorized CartR _ = authAuthentified
isAuthorized (CartItemR _) _ = authAuthentified
isAuthorized (CartItemEditR _) _ = authAuthentified
isAuthorized (CartItemDeleteR _) _ = authAuthentified
isAuthorized LoginPanelR _ = authNotAuthentified
isAuthorized PlaceListR True = authAuthentified
isAuthorized PlaceListR False = return Authorized
isAuthorized (PlaceR _) _ = return Authorized
isAuthorized DeliveryListR True = authAuthentified
isAuthorized DeliveryListR False = return Authorized
isAuthorized (DeliveryR _) _ = return Authorized
isAuthorized (DeliveryPlaceR _) _ = authAuthentified
isAuthorized (ShopShopDeliveryR shopid) _ = authShop shopid
isAuthorized (ShopDeliveryR _) _ = return Authorized
isAuthorized (ShopDeliveryAdminR shopdeliveryid) _ = authShopDelivery shopdeliveryid
isAuthorized (ShopPlaceListR _) _ = return Authorized
isAuthorized (UserR userid) _ = authUser userid
isAuthorized (StaticR _) _ = return Authorized
isAuthorized (AuthR LogoutR) _ = authAuthentified
isAuthorized (AuthR LoginR) _ = authNotAuthentified
isAuthorized (AuthR (PluginR "email" ["register"])) _ = authNotAuthentified
isAuthorized (AuthR _) _ = return Authorized
isAuthorized FaviconR _ = return Authorized
isAuthorized RobotsR _ = return Authorized
-- Default to Authorized for now.
isAuthorized _ _ = return Authorized
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent ext mime content = do
master <- getYesod
let staticDir = appStaticDir $ appSettings master
addStaticContentExternal
minifym
genFileName
staticDir
(StaticR . flip StaticRoute [])
ext
mime
content
where
-- Generate a unique filename based on the content itself
genFileName lbs = "autogen-" ++ base64md5 lbs
-- What messages should be logged. The following includes all messages when
-- in development, and warnings and errors in production.
shouldLog app _source level =
appShouldLogAll (appSettings app)
|| level == LevelWarn
|| level == LevelError
makeLogger = return . appLogger
-- How to run database actions.
instance YesodPersist App where
type YesodPersistBackend App = SqlBackend
runDB action = do
master <- getYesod
runSqlPool action $ appConnPool master
instance YesodPersistRunner App where
getDBRunner = defaultGetDBRunner appConnPool
instance YesodAuth App where
type AuthId App = UserId
-- Where to send a user after successful login
loginDest _ = HomeR
-- Where to send a user after logout
logoutDest _ = HomeR
-- Override the above two destinations when a Referer: header is present
redirectToReferer _ = True
-- getAuthId creds = runDB $ do
-- x <- getBy $ UniqueUser $ credsIdent creds
-- case x of
-- Just (Entity uid _) -> return $ Just uid
-- Nothing -> Just <$> insert User
-- { userIdent = credsIdent creds
-- , userPassword = Nothing
-- }
-- Need to find the UserId for the given email address.
getAuthId creds = do
date <- liftIO getCurrentTime
x <- runDB $ insertBy $ User (credsIdent creds) Nothing Nothing False date
return $ Just $
case x of
Left (Entity userid _) -> userid -- newly added user
Right userid -> userid -- existing user
-- You can add other plugins like BrowserID, email or OAuth here
authPlugins _ = [authEmail]
authHttpManager = getHttpManager
onLogin = setMessageILevel "alert-info" MsgNowLoggedIn
onLogout = setMessageILevel "alert-info" MsgNowLoggedOut
instance YesodAuthPersist App
-- This instance is required to use forms. You can modify renderMessage to
-- achieve customized and internationalized form validation messages.
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
unsafeHandler :: App -> Handler a -> IO a
unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger
-- Note: Some functionality previously present in the scaffolding has been
-- moved to documentation in the Wiki. Following are some hopefully helpful
-- links:
--
-- https://github.com/yesodweb/yesod/wiki/Sending-email
-- https://github.com/yesodweb/yesod/wiki/Serve-static-files-from-a-separate-domain
-- https://github.com/yesodweb/yesod/wiki/i18n-messages-in-the-scaffolding
instance YesodAuthEmail App where
type AuthEmailId App = UserId
addUnverified email verkey = do
date <- liftIO getCurrentTime
runDB $ insert $ User email Nothing (Just verkey) False date
sendVerifyEmail email _ verurl = do
messageRender <- getMessageRender
let plainPart' = plainPart [stext|#{messageRender MsgVerifyEmailIntro}
#{verurl}
#{messageRender MsgVerifyEmailOutro}
|]
let htmlPart' = Part {
partType = "text/html; charset=utf-8"
, partEncoding = None
, partFilename = Nothing
, partHeaders = []
, partContent = renderHtml
[shamlet|
<p>#{messageRender MsgVerifyEmailIntro}
<p>
<a href=#{verurl}>#{verurl}
<p>#{messageRender MsgVerifyEmailOutro}
|]
}
liftIO $ renderSendMail (emptyMail $ Address Nothing "noreply")
{ mailTo = [Address Nothing email]
, mailHeaders =
[ ("Subject", messageRender MsgVerifyEmailSubject)
]
, mailParts = [[plainPart', htmlPart']]
}
getVerifyKey = runDB . fmap (join . fmap userVerkey) . get
setVerifyKey uid key = runDB $ update uid [UserVerkey =. Just key]
verifyAccount uid = runDB $ do
mu <- get uid
case mu of
Nothing -> return Nothing
Just _ -> do
update uid [UserVerified =. True]
return $ Just uid
getPassword = runDB . fmap (join . fmap userPassword) . get
setPassword uid pass = runDB $ update uid [UserPassword =. Just pass]
getEmailCreds email = runDB $ do
mu <- getBy $ UniqueUser email
case mu of
Nothing -> return Nothing
Just (Entity uid u) -> return $ Just EmailCreds
{ emailCredsId = uid
, emailCredsAuthId = Just uid
, emailCredsStatus = isJust $ userPassword u
, emailCredsVerkey = userVerkey u
, emailCredsEmail = userEmail u
}
getEmail = runDB . fmap (fmap userEmail) . get
afterPasswordRoute _ = HomeR
registerHandler = do
email <- newIdent
lift $ authLayout $ do
setTitleI AuthMsg.RegisterLong
$(widgetFile "register")
confirmationEmailSentResponse identifier = do
mr <- getMessageRender
selectRep $ do
provideJsonMessage (mr msg)
provideRep $ authLayout $ do
setTitleI AuthMsg.ConfirmationEmailSentTitle
setMessageILevel "alert-info" msg
redirectUltDest HomeR
where
msg = AuthMsg.ConfirmationEmailSent identifier
|