-
Notifications
You must be signed in to change notification settings - Fork 0
/
RestNews.hs
330 lines (285 loc) · 11.9 KB
/
RestNews.hs
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
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module RestNews
( SessionErrorThatNeverOccured(..)
, makeApplication
, runWarpWithLogger
, restAPI
, processConfig
) where
import qualified RestNews.Config as C
import qualified RestNews.DB.ProcessRequest as PR
import RestNews.DB.RequestRunner (cantDecodeS, runSession)
import qualified RestNews.DBConnection as DBC
import qualified RestNews.Logger as L
import qualified RestNews.Middleware.Sessions as S
import qualified RestNews.Middleware.Static as Static
import qualified RestNews.Requests.PrerequisitesCheck as PC
import RestNews.Requests.SessionName (getSessionName)
import qualified RestNews.WAI as WAI
import Control.Exception (Exception, bracket_, throw)
import Control.Monad (void, when)
import Control.Monad.Except (ExceptT (..), runExceptT)
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString.Lazy.UTF8 as UTFLBS
import Data.Either (fromRight)
import Data.Int (Int32)
import Data.Maybe (fromMaybe, isJust)
import Data.String (fromString)
import qualified Data.Vault.Lazy as Vault
import Database.PostgreSQL.Simple (ConnectInfo (..), connectPostgreSQL, postgreSQLConnectionString)
import Hasql.Connection (Settings, acquire, settings)
import qualified Network.HTTP.Types as H
import Network.Wai (Application, Request, Response, ResponseReceived, pathInfo, requestMethod, responseLBS,
strictRequestBody, vault)
import Network.Wai.Handler.Warp (Port, run)
import Network.Wai.Session (SessionStore, withSession)
import Network.Wai.Session.PostgreSQL (clearSession, dbStore, defaultSettings, fromSimpleConnection, purger,
storeSettingsLog)
import Prelude hiding (error)
import System.Exit (exitFailure)
import System.Log.Logger (Priority (DEBUG, ERROR), debugM, errorM, infoM, setLevel, traplogging, updateGlobalLogger)
import Web.Cookie (defaultSetCookie)
dbError :: UTFLBS.ByteString
dbError = "DB connection error"
getIdString :: Maybe String -> String
getIdString = fromMaybe "0"
getSessionName' ::
L.Handle a
-> WAI.Handle a
-> Request
-> IO (Either String String)
getSessionName' loggerH waiH request = do
_ <- liftIO . L.hDebug loggerH $ show request
let method = WAI.hRequestMethod waiH request
pathTextChunks = WAI.hPathInfo waiH request
_ <- liftIO . L.hInfo loggerH $ show (method, pathTextChunks)
let eitherSessionName = getSessionName (pathTextChunks, method)
_ <- liftIO . L.hInfo loggerH $ show eitherSessionName
pure eitherSessionName
data DBSessionNameAndSessionThings = DBSessionNameAndSessionThings {
sessionName :: String,
maybeUserId :: Maybe String,
sessionUserIdString :: String,
sessionAuthorIdString :: String,
sessionLookup :: String -> IO (Maybe String),
sessionInsert :: String -> String -> IO (),
clearSessionPartial :: Request -> IO ()
}
data SessionErrorThatNeverOccured = SessionErrorThatNeverOccured deriving Show
instance Exception SessionErrorThatNeverOccured
prerequisitesCheck ::
L.Handle a
-> S.Handle
-> Request
-> String
-> IO (Either String DBSessionNameAndSessionThings)
prerequisitesCheck loggerH sessionsH request sessionName' = do
let maybeSessionMethods = S.hMaybeSessionMethods sessionsH request
(sessionLookup', sessionInsert') = fromMaybe (throw SessionErrorThatNeverOccured) maybeSessionMethods
maybeUserId' <- sessionLookup' "user_id"
maybeIsAdmin <- sessionLookup' "is_admin"
maybeAuthorId <- sessionLookup' "author_id"
_ <- liftIO . L.hDebug loggerH $ show ("session user_id" :: String, maybeUserId')
_ <- liftIO . L.hDebug loggerH $ show ("session is_admin" :: String, maybeIsAdmin)
_ <- liftIO . L.hDebug loggerH $ show ("session author_id" :: String, maybeAuthorId)
let sessionUserIdString' = getIdString maybeUserId'
sessionAuthorIdString' = getIdString maybeAuthorId
params = PC.Params {
PC.isAdmin = maybeIsAdmin == Just "True",
PC.hasUserId = sessionUserIdString' /= "0",
PC.hasAuthorId = sessionAuthorIdString' /= "0"
}
pure . fmap
(\sessionNameFromRight ->
DBSessionNameAndSessionThings {
sessionName = sessionNameFromRight,
maybeUserId = maybeUserId',
sessionUserIdString = sessionUserIdString',
sessionAuthorIdString = sessionAuthorIdString',
sessionLookup = sessionLookup',
sessionInsert = sessionInsert',
clearSessionPartial = S.hClearSession sessionsH
}
)
$ PC.prerequisitesCheck params sessionName'
processCredentials :: Monad m => (String -> m a)
-> (Request -> m ())
-> Request
-> Maybe String
-> (String -> String -> m ())
-> PR.HasqlSessionResults (Int32, Bool, Int32)
-> m (PR.HasqlSessionResults (Int32, Bool, Int32))
processCredentials
debug
clearSessionPartial'
request
maybeUserId'
sessionInsert'
wrappedSessionResults = do
let (PR.H sessionResults) = wrappedSessionResults
(user_id, is_admin, author_id) = fromRight (0, False, 0) $ fromRight (Left "pluh") sessionResults
-- clearSession will fail if request has no associated session with cookies:
-- https://github.com/hce/postgresql-session/blob/8d41ea2e8b01c81e648a7c74f4915bee79822678/src/Network/Wai/Session/PostgreSQL.hs#L232
when
(isJust maybeUserId')
(clearSessionPartial' request)
_ <- debug (show ("put into sessions:" :: String, user_id, is_admin, author_id))
sessionInsert' "is_admin" (show is_admin)
sessionInsert' "user_id" (show user_id)
sessionInsert' "author_id" (show author_id)
pure wrappedSessionResults
newtype HasqlSessionError = HasqlSessionError String deriving Show
instance Exception HasqlSessionError
runDBSession ::
L.Handle a
-> WAI.Handle a
-> DBC.Handle
-> Request
-> DBSessionNameAndSessionThings
-> IO (Either String UTFLBS.ByteString)
runDBSession
loggerH
waiH
dbH
request
(DBSessionNameAndSessionThings
sessionName'
maybeUserId'
sessionUserIdString'
sessionAuthorIdString'
_
sessionInsert'
clearSessionPartial'
) = do
let runSessionResults = do
requestBody <- WAI.hStrictRequestBody waiH request
_ <- liftIO . L.hInfo loggerH $ show requestBody
eitherConnection <- DBC.hAcquiredConnection dbH
case eitherConnection of
Left connectionError ->
liftIO $ L.hError loggerH (show connectionError)
>> pure (PR.H . Left $ UTFLBS.toString dbError)
Right connection ->
let processCredentialsPartial =
processCredentials
(L.hDebug loggerH)
clearSessionPartial'
request
maybeUserId'
sessionInsert'
sessionAuthorId' = (read sessionAuthorIdString' :: Int32)
sessionUserId' = (read sessionUserIdString' :: Int32)
in runSession
connection
requestBody
processCredentialsPartial
sessionUserId'
sessionAuthorId'
sessionName'
hRunSessionResults <- runSessionResults
_ <- liftIO . L.hDebug loggerH $ show hRunSessionResults
let (PR.H runSessionResultsUnpacked) = hRunSessionResults
pure $ case runSessionResultsUnpacked of
Left unhandledError -> throw $ HasqlSessionError unhandledError
Right (Left errorForUser) -> Right errorForUser
Right (Right runSessionResults') -> Right runSessionResults'
respond' :: (Response -> IO ResponseReceived) -> Either String UTFLBS.ByteString -> IO ResponseReceived
respond' respond (Left error) =
let status =
if error == cantDecodeS
then H.status400
else H.status404
in respond $ responseLBS status [] $ UTFLBS.fromString error
respond' respond (Right results) = respond $ responseLBS H.status200 [] results
--type Application = Request -> (Response -> IO ResponseReceived) -> IO ResponseReceived
restAPI ::
L.Handle a
-> S.Handle
-> DBC.Handle
-> WAI.Handle a
-> Application
restAPI loggerH sessionsH dbH waiH request respond =
bracket_
(L.hDebug loggerH "Allocating scarce resource")
(L.hDebug loggerH "Cleaning up")
(do
let exceptTRequestResults =
ExceptT (getSessionName' loggerH waiH request)
>>= (ExceptT . prerequisitesCheck loggerH sessionsH request)
>>= (ExceptT . runDBSession loggerH waiH dbH request)
runExceptT exceptTRequestResults >>= respond' respond
)
processConfig :: C.Config -> (Port, Settings, ConnectInfo)
processConfig (C.Config runAtPort dbHost dbPort dbUser dbPassword dbName) =
(
runAtPort,
settings (fromString dbHost) (toEnum dbPort) (fromString dbUser) (fromString dbPassword) (fromString dbName),
ConnectInfo {
connectHost = dbHost,
connectPort = toEnum dbPort,
connectUser = dbUser,
connectPassword = dbPassword,
connectDatabase = dbName
}
)
makeApplication :: L.Handle () -> Settings -> ConnectInfo -> IO Application
makeApplication loggerH dbConnectionSettings connectInfo = do
let storeSettings = defaultSettings {storeSettingsLog = L.hDebug loggerH}
vaultKey <- Vault.newKey
simpleConnection <- connectPostgreSQL (postgreSQLConnectionString connectInfo)
>>= fromSimpleConnection
store <- dbStore simpleConnection storeSettings :: IO (SessionStore IO String String)
void (purger simpleConnection storeSettings)
pure $ S.withSessions
(S.Config
(withSession store "SESSION" defaultSetCookie vaultKey)
(Vault.lookup vaultKey . vault)
(clearSession simpleConnection "SESSION")
)
(\ sessionsH ->
DBC.withDBConnection
(DBC.Config $ acquire dbConnectionSettings)
(\ dbH ->
WAI.withWAI
(WAI.Config
requestMethod
pathInfo
strictRequestBody
)
(\ waiH ->
Static.router (
S.hWithSession
sessionsH
$ restAPI loggerH sessionsH dbH waiH
)
)
)
)
runWarpWithLogger :: IO ()
runWarpWithLogger = do
L.withLogger
(L.Config
-- use INFO, DEBUG or ERROR here
-- (add to System.Log.Logger import items if missed)
DEBUG
(traplogging
"rest-news"
ERROR
"Unhandled exception occured"
. updateGlobalLogger "rest-news" . setLevel)
(debugM "rest-news")
(infoM "rest-news")
(errorM "rest-news"))
(\ loggerH ->
C.parseConfig "config.ini"
>>= \ case
Left errorMessage ->
L.hError loggerH errorMessage
>> exitFailure
Right config ->
let (port, dbConnectionSettings, connectInfo) = processConfig config
in makeApplication loggerH dbConnectionSettings connectInfo
>>= run port
)
pure ()