{-|
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 Data.Morpheus.App.Internal.Resolving (LiftOperation)
import Data.Morpheus.Types (ResolverO)
import Gargantext.API.Admin.Auth.Types ( AuthenticatedUser )
import Gargantext.API.Auth.PolicyCheck ( BoolExpr, AccessCheck, AccessPolicyManager(..), AccessResult(..))
import Gargantext.API.Errors.Types ( BackendInternalError(..) )
import Gargantext.API.GraphQL.Types (GqlLogger)
import Gargantext.API.Prelude (GargM)
import Gargantext.Core.Config (HasConfig)
import Gargantext.Database.Prelude (HasConnectionPool)

withPolicy :: (HasConnectionPool env, HasConfig env, LiftOperation op, GqlLogger env)
           => 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

