2 Module : Gargantext.API
3 Description : REST API declaration
4 Copyright : (c) CNRS, 2017-Present
5 License : AGPL + CECILL v3
6 Maintainer : team@gargantext.org
7 Stability : experimental
10 Main (RESTful) API of the instance Gargantext.
12 The Garg-API is typed to derive the documentation, the mock and tests.
14 This API is indeed typed in order to be able to derive both the server
17 The Garg-API-Monad enables:
20 - Database connection (long term)
21 - In Memory stack management (short term)
24 Thanks to Yann Esposito for our discussions at the start and to Nicolas
25 Pouillard (who mainly made it).
29 {-# OPTIONS_GHC -fno-warn-name-shadowing #-}
31 {-# LANGUAGE ConstraintKinds #-}
32 {-# LANGUAGE TemplateHaskell #-}
33 {-# LANGUAGE TypeOperators #-}
34 {-# LANGUAGE KindSignatures #-}
35 {-# LANGUAGE ScopedTypeVariables #-}
36 {-# LANGUAGE TypeFamilies #-}
37 {-# LANGUAGE UndecidableInstances #-}
39 ---------------------------------------------------------------------
42 ---------------------------------------------------------------------
43 import Control.Exception (finally)
45 import Control.Monad.Except (withExceptT)
46 import Control.Monad.Reader (runReaderT)
47 import Data.Aeson.Encode.Pretty (encodePretty)
48 import Data.List (lookup)
50 import Data.Text (Text)
51 import Data.Text.Encoding (encodeUtf8)
53 import Data.Version (showVersion)
54 import GHC.Base (Applicative)
55 import GHC.Generics (D1, Meta (..), Rep, Generic)
56 import GHC.TypeLits (AppendSymbol, Symbol)
57 import Gargantext.API.Admin.Auth (AuthContext, auth)
58 import Gargantext.API.Admin.FrontEnd (frontEndServer)
59 import Gargantext.API.Admin.Settings
60 import Gargantext.API.Ngrams (HasRepoSaver(..), saveRepo)
61 import Gargantext.API.Prelude
62 import Gargantext.API.Routes
63 import Gargantext.Prelude
64 import Network.HTTP.Types hiding (Query)
66 import Network.Wai (Request, requestHeaders)
67 import Network.Wai.Handler.Warp hiding (defaultSettings)
68 import Network.Wai.Middleware.Cors
69 import Network.Wai.Middleware.RequestLogger
71 import Servant.Auth.Server (AuthResult(..))
72 import Servant.Auth.Swagger ()
73 import Servant.Swagger
74 import Servant.Swagger.UI
75 import System.IO (FilePath)
76 import qualified Data.ByteString.Lazy.Char8 as BL8
77 import qualified Data.Text.IO as T
78 import qualified Paths_gargantext as PG -- cabal magic build module
81 data Mode = Dev | Mock | Prod
82 deriving (Show, Read, Generic)
85 -- | startGargantext takes as parameters port number and Ini file.
86 startGargantext :: Mode -> PortNumber -> FilePath -> IO ()
87 startGargantext mode port file = do
88 env <- newEnv port file
91 mid <- makeDevMiddleware mode
92 run port (mid app) `finally` stopGargantext env
94 portRouteInfo :: PortNumber -> IO ()
95 portRouteInfo port = do
96 T.putStrLn " ----Main Routes----- "
97 T.putStrLn $ "http://localhost:" <> toUrlPiece port <> "/index.html"
98 T.putStrLn $ "http://localhost:" <> toUrlPiece port <> "/swagger-ui"
100 -- TODO clean this Monad condition (more generic) ?
101 stopGargantext :: HasRepoSaver env => env -> IO ()
102 stopGargantext env = do
103 T.putStrLn "----- Stopping gargantext -----"
104 runReaderT saveRepo env
107 -- | Output generated @swagger.json@ file for the @'TodoAPI'@.
108 swaggerWriteJSON :: IO ()
109 swaggerWriteJSON = BL8.writeFile "swagger.json" (encodePretty swaggerDoc)
111 -- | Swagger Specifications
112 swaggerDoc :: Swagger
113 swaggerDoc = toSwagger (Proxy :: Proxy GargAPI)
114 & info.title .~ "Gargantext"
115 & info.version .~ (cs $ showVersion PG.version)
116 -- & info.base_url ?~ (URL "http://gargantext.org/")
117 & info.description ?~ "REST API specifications"
118 -- & tags .~ Set.fromList [Tag "Garg" (Just "Main perations") Nothing]
119 & applyTagsFor (subOperations (Proxy :: Proxy GargAPI)(Proxy :: Proxy GargAPI))
120 ["Gargantext" & description ?~ "Main operations"]
121 & info.license ?~ ("AGPLV3 (English) and CECILL (French)" & url ?~ URL urlLicence )
123 urlLicence = "https://gitlab.iscpif.fr/gargantext/haskell-gargantext/blob/master/LICENSE"
126 startGargantextMock :: PortNumber -> IO ()
127 startGargantextMock port = do
129 application <- makeMockApp . MockEnv $ FireWall False
133 ----------------------------------------------------------------------
135 fireWall :: Applicative f => Request -> FireWall -> f Bool
137 let origin = lookup "Origin" (requestHeaders req)
138 let host = lookup "Host" (requestHeaders req)
140 if origin == Just (encodeUtf8 "http://localhost:8008")
141 && host == Just (encodeUtf8 "localhost:3000")
142 || (not $ unFireWall fw)
148 -- makeMockApp :: Env -> IO (Warp.Settings, Application)
149 makeMockApp :: MockEnv -> IO Application
151 let serverApp = appMock
153 -- logWare <- mkRequestLogger def { destination = RequestLogger.Logger $ env^.logger }
154 --logWare <- mkRequestLogger def { destination = RequestLogger.Logger "/tmp/logs.txt" }
155 let checkOriginAndHost app req resp = do
156 blocking <- fireWall req (env ^. menv_firewall)
159 False -> resp ( responseLBS status401 []
160 "Invalid Origin or Host header")
162 let corsMiddleware = cors $ \_ -> Just CorsResourcePolicy
163 -- { corsOrigins = Just ([env^.settings.allowedOrigin], False)
164 { corsOrigins = Nothing -- == /*
165 , corsMethods = [ methodGet , methodPost , methodPut
166 , methodDelete, methodOptions, methodHead]
167 , corsRequestHeaders = ["authorization", "content-type"]
168 , corsExposedHeaders = Nothing
169 , corsMaxAge = Just ( 60*60*24 ) -- one day
170 , corsVaryOrigin = False
171 , corsRequireOrigin = False
172 , corsIgnoreFailures = False
175 --let warpS = Warp.setPort (8008 :: Int) -- (env^.settings.appPort)
176 -- $ Warp.defaultSettings
178 --pure (warpS, logWare $ checkOriginAndHost $ corsMiddleware $ serverApp)
179 pure $ logStdoutDev $ checkOriginAndHost $ corsMiddleware $ serverApp
183 makeDevMiddleware :: Mode -> IO Middleware
184 makeDevMiddleware mode = do
186 -- logWare <- mkRequestLogger def { destination = RequestLogger.Logger $ env^.logger }
187 --logWare <- mkRequestLogger def { destination = RequestLogger.Logger "/tmp/logs.txt" }
188 -- let checkOriginAndHost app req resp = do
189 -- blocking <- fireWall req (env ^. menv_firewall)
191 -- True -> app req resp
192 -- False -> resp ( responseLBS status401 []
193 -- "Invalid Origin or Host header")
195 let corsMiddleware = cors $ \_ -> Just CorsResourcePolicy
196 -- { corsOrigins = Just ([env^.settings.allowedOrigin], False)
197 { corsOrigins = Nothing -- == /*
198 , corsMethods = [ methodGet , methodPost , methodPut
199 , methodDelete, methodOptions, methodHead]
200 , corsRequestHeaders = ["authorization", "content-type"]
201 , corsExposedHeaders = Nothing
202 , corsMaxAge = Just ( 60*60*24 ) -- one day
203 , corsVaryOrigin = False
204 , corsRequireOrigin = False
205 , corsIgnoreFailures = False
208 --let warpS = Warp.setPort (8008 :: Int) -- (env^.settings.appPort)
209 -- $ Warp.defaultSettings
211 --pure (warpS, logWare . checkOriginAndHost . corsMiddleware)
213 Prod -> pure $ logStdout . corsMiddleware
214 _ -> pure $ logStdoutDev . corsMiddleware
216 ---------------------------------------------------------------------
218 ---------------------------------------------------------------------
219 -- | Server declarations
220 server :: forall env. EnvC env => env -> IO (Server API)
222 -- orchestrator <- scrapyOrchestrator env
223 pure $ schemaUiServer swaggerDoc
224 :<|> hoistServerWithContext
225 (Proxy :: Proxy GargAPI)
226 (Proxy :: Proxy AuthContext)
231 transform :: forall a. GargServerM env GargError a -> Handler a
232 transform = Handler . withExceptT showAsServantErr . (`runReaderT` env)
234 showAsServantErr :: GargError -> ServerError
235 showAsServantErr (GargServerError err) = err
236 showAsServantErr a = err500 { errBody = BL8.pack $ show a }
238 ---------------------------
240 serverGargAPI :: GargServerT env err (GargServerM env err) GargAPI
241 serverGargAPI -- orchestrator
244 :<|> serverPrivateGargAPI
248 gargVersion :: GargServer GargVersion
249 gargVersion = pure (cs $ showVersion PG.version)
251 serverPrivateGargAPI :: GargServerT env err (GargServerM env err) GargPrivateAPI
252 serverPrivateGargAPI (Authenticated auser) = serverPrivateGargAPI' auser
253 serverPrivateGargAPI _ = throwAll' (_ServerError # err401)
254 -- Here throwAll' requires a concrete type for the monad.
257 -- TODO-SECURITY admin only: withAdmin
258 -- Question: How do we mark admins?
260 serverGargAdminAPI :: GargServer GargAdminAPI
261 serverGargAdminAPI = roots
265 ---------------------------------------------------------------------
266 --gargMock :: Server GargAPI
267 --gargMock = mock apiGarg Proxy
268 ---------------------------------------------------------------------
269 makeApp :: EnvC env => env -> IO Application
270 makeApp env = serveWithContext api cfg <$> server env
272 cfg :: Servant.Context AuthContext
273 cfg = env ^. settings . jwtSettings
274 :. env ^. settings . cookieSettings
278 --appMock :: Application
279 --appMock = serve api (swaggerFront :<|> gargMock :<|> serverStatic)
280 ---------------------------------------------------------------------
284 apiGarg :: Proxy GargAPI
286 ---------------------------------------------------------------------
287 schemaUiServer :: (Server api ~ Handler Swagger)
288 => Swagger -> Server (SwaggerSchemaUI' dir api)
289 schemaUiServer = swaggerSchemaUIServer
291 ---------------------------------------------------------------------
292 -- Type Family for the Documentation
293 type family TypeName (x :: *) :: Symbol where
295 TypeName Text = "Text"
296 TypeName x = GenericTypeName x (Rep x ())
298 type family GenericTypeName t (r :: *) :: Symbol where
299 GenericTypeName t (D1 ('MetaData name mod pkg nt) f x) = name
301 type Desc t n = Description (AppendSymbol (TypeName t) (AppendSymbol " | " n))