2 Module : Gargantext.API.Admin.Auth
3 Description : Server API Auth Module
4 Copyright : (c) CNRS, 2017-Present
5 License : AGPL + CECILL v3
6 Maintainer : team@gargantext.org
7 Stability : experimental
10 Main authorization of Gargantext are managed in this module
12 -- 1: Implement the Server / Client JWT authentication
13 -> Client towards Python Backend
14 -> Server towards Purescript Front-End
16 -- 2: Implement the Auth API backend
17 https://github.com/haskell-servant/servant-auth
23 {-# LANGUAGE ScopedTypeVariables #-}
24 {-# LANGUAGE TemplateHaskell #-}
26 module Gargantext.API.Admin.Auth
29 import Control.Lens (view)
30 import Data.Aeson.TH (deriveJSON)
32 import Data.Text (Text)
33 import Data.Text.Lazy (toStrict)
34 import Data.Text.Lazy.Encoding (decodeUtf8)
35 import GHC.Generics (Generic)
37 import Servant.Auth.Server
38 import Test.QuickCheck (elements, oneof)
39 import Test.QuickCheck.Arbitrary (Arbitrary, arbitrary)
40 import qualified Gargantext.Prelude.Crypto.Auth as Auth
42 import Gargantext.API.Admin.Types
43 import Gargantext.API.Prelude (HasJoseError(..), joseError, HasServerError, GargServerC)
44 import Gargantext.Core.Types.Individu (User(..), Username, GargPassword(..), arbitraryUsername, arbitraryPassword)
45 import Gargantext.Core.Utils.Prefix (unPrefix, unPrefixSwagger)
46 import Gargantext.Database.Query.Tree (isDescendantOf, isIn)
47 import Gargantext.Database.Query.Tree.Root (getRoot)
48 import Gargantext.Database.Schema.Node (NodePoly(_node_id))
49 import Gargantext.Database.Admin.Types.Node (NodeId(..), UserId, ListId, DocId)
50 import Gargantext.Database.Prelude (Cmd', CmdM, HasConnectionPool, HasConfig)
51 import Gargantext.Prelude hiding (reverse)
52 import Gargantext.Database.Query.Table.User
54 ---------------------------------------------------
56 -- | Main types for AUTH API
57 data AuthRequest = AuthRequest { _authReq_username :: Username
58 , _authReq_password :: GargPassword
62 -- TODO: Use an HTTP error to wrap AuthInvalid
63 data AuthResponse = AuthResponse { _authRes_valid :: Maybe AuthValid
64 , _authRes_inval :: Maybe AuthInvalid
68 data AuthInvalid = AuthInvalid { _authInv_message :: Text }
71 data AuthValid = AuthValid { _authVal_token :: Token
72 , _authVal_tree_id :: TreeId
79 -- | Main functions of authorization
81 -- | Main types of authorization
82 data CheckAuth = InvalidUser | InvalidPassword | Valid Token TreeId
85 makeTokenForUser :: (HasSettings env, HasJoseError err)
86 => NodeId -> Cmd' env err Token
87 makeTokenForUser uid = do
88 jwtS <- view $ settings . jwtSettings
89 e <- liftBase $ makeJWT (AuthenticatedUser uid) jwtS Nothing
90 -- TODO-SECURITY here we can implement token expiration ^^.
91 either joseError (pure . toStrict . decodeUtf8) e
92 -- TODO not sure about the encoding...
94 checkAuthRequest :: (HasSettings env, HasConnectionPool env, HasJoseError err, HasConfig env)
97 -> Cmd' env err CheckAuth
98 checkAuthRequest u (GargPassword p) = do
99 candidate <- head <$> getUsersWith u
101 Nothing -> pure InvalidUser
102 Just (UserLight _id _u _email h) ->
103 case Auth.checkPassword (Auth.mkPassword p) (Auth.PasswordHash h) of
104 Auth.PasswordCheckFail -> pure InvalidPassword
105 Auth.PasswordCheckSuccess -> do
106 muId <- head <$> getRoot (UserName u)
107 case _node_id <$> muId of
108 Nothing -> pure InvalidUser
110 token <- makeTokenForUser uid
111 pure $ Valid token uid
113 auth :: (HasSettings env, HasConnectionPool env, HasJoseError err, HasConfig env)
114 => AuthRequest -> Cmd' env err AuthResponse
115 auth (AuthRequest u p) = do
116 checkAuthRequest' <- checkAuthRequest u p
117 case checkAuthRequest' of
118 InvalidUser -> pure $ AuthResponse Nothing (Just $ AuthInvalid "Invalid user")
119 InvalidPassword -> pure $ AuthResponse Nothing (Just $ AuthInvalid "Invalid password")
120 Valid to trId -> pure $ AuthResponse (Just $ AuthValid to trId) Nothing
122 newtype AuthenticatedUser = AuthenticatedUser
123 { _authUser_id :: NodeId
126 $(deriveJSON (unPrefix "_authUser_") ''AuthenticatedUser)
128 instance ToSchema AuthenticatedUser where
129 declareNamedSchema = genericDeclareNamedSchema (unPrefixSwagger "_authUser_")
131 instance ToJWT AuthenticatedUser
132 instance FromJWT AuthenticatedUser
134 --type instance BasicAuthCfg = BasicAuthData -> IO (AuthResult AuthenticatedUser)
136 -- TODO-SECURITY why is the CookieSettings necessary?
137 type AuthContext = '[JWTSettings, CookieSettings] -- , BasicAuthCfg
140 instance FromBasicAuthData AuthenticatedUser where
141 fromBasicAuthData authData authCheckFunction = authCheckFunction authData
143 authCheck :: forall env. env
145 -> IO (AuthResult AuthenticatedUser)
146 authCheck _env (BasicAuthData login password) = pure $
147 maybe Indefinite Authenticated $ TODO
151 $(deriveJSON (unPrefix "_authReq_") ''AuthRequest)
152 instance ToSchema AuthRequest where
153 declareNamedSchema = genericDeclareNamedSchema (unPrefixSwagger "_authReq_")
155 instance Arbitrary AuthRequest where
156 arbitrary = elements [ AuthRequest u p
157 | u <- arbitraryUsername
158 , p <- arbitraryPassword
161 $(deriveJSON (unPrefix "_authRes_") ''AuthResponse)
162 instance ToSchema AuthResponse where
163 declareNamedSchema = genericDeclareNamedSchema (unPrefixSwagger "_authRes_")
164 instance Arbitrary AuthResponse where
165 arbitrary = oneof [ AuthResponse Nothing . Just <$> arbitrary
166 , flip AuthResponse Nothing . Just <$> arbitrary ]
168 $(deriveJSON (unPrefix "_authInv_") ''AuthInvalid)
169 instance ToSchema AuthInvalid where
170 declareNamedSchema = genericDeclareNamedSchema (unPrefixSwagger "_authInv_")
171 instance Arbitrary AuthInvalid where
172 arbitrary = elements [ AuthInvalid m
173 | m <- [ "Invalid user", "Invalid password"]
176 $(deriveJSON (unPrefix "_authVal_") ''AuthValid)
177 instance ToSchema AuthValid where
178 declareNamedSchema = genericDeclareNamedSchema (unPrefixSwagger "_authVal_")
179 instance Arbitrary AuthValid where
180 arbitrary = elements [ AuthValid to tr
181 | to <- ["token0", "token1"]
185 data PathId = PathNode NodeId | PathNodeNode ListId DocId
187 withAccessM :: (CmdM env err m, HasServerError err)
192 withAccessM uId (PathNode id) m = do
193 d <- id `isDescendantOf` NodeId uId
194 if d then m else m -- serverError err401
196 withAccessM uId (PathNodeNode cId docId) m = do
197 _a <- isIn cId docId -- TODO use one query for all ?
198 _d <- cId `isDescendantOf` NodeId uId
203 withAccess :: forall env err m api.
204 (GargServerC env err m, HasServer api '[]) =>
205 Proxy api -> Proxy m -> UserId -> PathId ->
206 ServerT api m -> ServerT api m
207 withAccess p _ uId id = hoistServer p f
209 f :: forall a. m a -> m a
210 f = withAccessM uId id
212 {- | Collaborative Schema
213 User at his root can create Teams Folder
214 User can create Team in Teams Folder.
215 User can invite User in Team as NodeNode only if Team in his parents.
216 All users can access to the Team folder as if they were owner.