{-|
Module      : Gargantext.API.GraphQL.PolicyCheck
Description : 
Copyright   : (c) CNRS, 2017-Present
License     : AGPL + CECILL v3
Maintainer  : team@gargantext.org
Stability   : experimental
Portability : POSIX

-}


module Gargantext.API.GraphQL.PolicyCheck where

import Prelude

import Control.Monad.Except (MonadError(..))
import Control.Monad.Trans.Class (lift)
import Gargantext.API.Admin.Auth.Types ( AuthenticatedUser )
import Gargantext.API.Auth.PolicyCheck ( BoolExpr, AccessCheck, AccessPolicyManager(..), AccessResult(..))
import Gargantext.API.Errors.Types ( BackendInternalError(..) )
import Gargantext.Core.Config (HasConfig)
import Gargantext.Database.Prelude (HasConnectionPool)
import Data.Morpheus.Types (ResolverO)
import Data.Morpheus.App.Internal.Resolving (LiftOperation)
import Gargantext.API.Prelude (GargM)

withPolicy :: (HasConnectionPool env, HasConfig env, LiftOperation op)
           => AuthenticatedUser
           -> AccessPolicyManager
           -> BoolExpr AccessCheck
           -> ResolverO op e (GargM env BackendInternalError) a
           -> ResolverO op e (GargM env BackendInternalError) a
withPolicy ur mgr checks m = case mgr of
  AccessPolicyManager{runAccessPolicy} -> do
    res <- lift $ runAccessPolicy ur checks
    case res of
      Allow     -> m
      Deny err  -> lift $ throwError $ AccessPolicyError err

