{-| Module : Gargantext.API.GraphQL.Utils Description : Utils for GraphQL API Copyright : (c) CNRS, 2017-Present License : AGPL + CECILL v3 Maintainer : team@gargantext.org Stability : experimental Portability : POSIX -} {-# Language TypeFamilies #-} {-# Language DeriveAnyClass #-} module Gargantext.API.GraphQL.Utils where import Data.Morpheus () import Data.Morpheus.Types import Data.Text (Text) import Gargantext.Core.Utils.Prefix (unCapitalize, dropPrefix) import Gargantext.Prelude import Data.Function (id) import Data.Text.Encoding (encodeUtf8) import Gargantext.API.Admin.Types (jwtSettings, HasSettings (settings)) import Servant.Auth.Server (verifyJWT, JWTSettings) import Control.Lens.Getter (view) import Gargantext.Database.Prelude (Cmd') import Gargantext.API.Admin.Auth.Types (AuthenticatedUser (AuthenticatedUser, _authUser_id)) import Data.ByteString (ByteString) import Gargantext.Database.Admin.Types.Node (NodeId) import GHC.Generics (Generic) import qualified Data.Text as T -- DOC: https://morpheusgraphql.com/server#directives data RemovePrefix = RemovePrefix {prefix :: Text} deriving (Generic, GQLType) instance GQLDirective RemovePrefix where type DIRECTIVE_LOCATIONS RemovePrefix = '[ 'LOCATION_OBJECT, 'LOCATION_INPUT_OBJECT ] instance VisitType RemovePrefix where visitTypeName (RemovePrefix {prefix}) _ = T.pack . unCapitalize . dropPrefix (T.unpack prefix) . T.unpack visitTypeDescription _ = id data AuthStatus = Valid | Invalid authUser :: (HasSettings env) => NodeId -> Text -> Cmd' env err AuthStatus authUser ui_id token = do let token' = encodeUtf8 token jwtS <- view $ settings . jwtSettings u <- liftBase $ getUserFromToken jwtS token' case u of Nothing -> pure Invalid Just au -> if nId au == ui_id then pure Valid else pure Invalid where nId AuthenticatedUser {_authUser_id} = _authUser_id getUserFromToken :: JWTSettings -> ByteString -> IO (Maybe AuthenticatedUser) getUserFromToken = verifyJWT