From ba683a107c72095270eb3223d2a12dcc58a491bc Mon Sep 17 00:00:00 2001 From: Paul Chavard Date: Thu, 22 Nov 2018 18:43:53 +0100 Subject: [PATCH] Add authorizations to root queries --- app/graphql/types/base_object.rb | 21 +++++++++++++++++++++ app/graphql/types/demarche_type.rb | 4 ++++ app/graphql/types/dossier_type.rb | 4 ++++ 3 files changed, 29 insertions(+) diff --git a/app/graphql/types/base_object.rb b/app/graphql/types/base_object.rb index 40a81ccd2..d4dc9aaba 100644 --- a/app/graphql/types/base_object.rb +++ b/app/graphql/types/base_object.rb @@ -1,4 +1,25 @@ module Types class BaseObject < GraphQL::Schema::Object + def self.authorized_demarche?(demarche, context) + # We are caching authorization logic because it is called for each node + # of the requested graph and can be expensive. Context is reset per request so it is safe. + context[:authorized] ||= {} + if context[:authorized][demarche.id] + return true + end + + administrateur = demarche.administrateurs.find do |administrateur| + if context[:token] + administrateur.valid_api_token?(context[:token]) + else + administrateur.id == context[:administrateur_id] + end + end + + if administrateur + context[:authorized][demarche.id] = true + true + end + end end end diff --git a/app/graphql/types/demarche_type.rb b/app/graphql/types/demarche_type.rb index 2f561b052..92633d67d 100644 --- a/app/graphql/types/demarche_type.rb +++ b/app/graphql/types/demarche_type.rb @@ -46,5 +46,9 @@ module Types dossiers end + + def self.authorized?(object, context) + authorized_demarche?(object, context) + end end end diff --git a/app/graphql/types/dossier_type.rb b/app/graphql/types/dossier_type.rb index 9d44f1f69..14da77748 100644 --- a/app/graphql/types/dossier_type.rb +++ b/app/graphql/types/dossier_type.rb @@ -38,5 +38,9 @@ module Types def instructeurs Loaders::Association.for(object.class, :followers_instructeurs).load(object) end + + def self.authorized?(object, context) + authorized_demarche?(object.procedure, context) + end end end