From 7d64011cbd6b0d6ce2237de2a3dfcc1f9f81a4c9 Mon Sep 17 00:00:00 2001 From: William Carroll Date: Fri, 31 Jul 2020 10:55:10 +0100 Subject: Protect GET /trips with a session cookie When an admin requests /trips, they see all of the trips in the Trips table. When a user requests /trips, they see only their trips. --- src/API.hs | 1 + src/App.hs | 11 +++++++++-- src/Trips.hs | 10 ++++++++-- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/API.hs b/src/API.hs index 0ae3112ae84c..1bcc47b3a5d6 100644 --- a/src/API.hs +++ b/src/API.hs @@ -48,6 +48,7 @@ type API = :> Delete '[JSON] NoContent -- trips: List :<|> "trips" + :> SessionCookie :> Get '[JSON] [T.Trip] -- Miscellaneous diff --git a/src/App.hs b/src/App.hs index 273bb3951e65..4f02cb4447db 100644 --- a/src/App.hs +++ b/src/App.hs @@ -126,8 +126,15 @@ server T.Config{..} = createAccount liftIO $ Trips.delete dbFile tripPK pure NoContent - listTrips :: Handler [T.Trip] - listTrips = liftIO $ Trips.list dbFile + listTrips :: T.SessionCookie -> Handler [T.Trip] + listTrips cookie = do + mAccount <- liftIO $ Auth.accountFromCookie dbFile cookie + case mAccount of + Nothing -> throwError err401 { errBody = "Your session cookie is invalid. Try logging out and logging back in." } + Just T.Account{..} -> + case accountRole of + T.Admin -> liftIO $ Trips.listAll dbFile + _ -> liftIO $ Trips.list dbFile accountUsername login :: T.AccountCredentials -> Handler (Headers '[Header "Set-Cookie" SetCookie] NoContent) diff --git a/src/Trips.hs b/src/Trips.hs index 55bc6b958d0f..ec52ec58fee9 100644 --- a/src/Trips.hs +++ b/src/Trips.hs @@ -22,6 +22,12 @@ delete dbFile tripPK = (tripPK |> T.tripPKFields) -- | Return a list of all of the trips in `dbFile`. -list :: FilePath -> IO [T.Trip] -list dbFile = withConnection dbFile $ \conn -> +listAll :: FilePath -> IO [T.Trip] +listAll dbFile = withConnection dbFile $ \conn -> query_ conn "SELECT username,destination,startDate,endDate,comment FROM Trips" + +-- | Return a list of all of the trips in `dbFile`. +list :: FilePath -> T.Username -> IO [T.Trip] +list dbFile username = withConnection dbFile $ \conn -> + query conn "SELECT username,destination,startDate,endDate,comment FROM Trips WHERE username = ?" + (Only username) -- cgit 1.4.1