Skip to content

Commit

Permalink
- Forward HTTP Error Codes correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
afabiani committed Feb 1, 2019
1 parent f9418dd commit 53aa10c
Show file tree
Hide file tree
Showing 3 changed files with 131 additions and 68 deletions.
1 change: 1 addition & 0 deletions requirements/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ graphene-django-extras==0.3.7
graphene-file-upload==1.2.2
graphql-core==2.1
graphql-relay==0.4.5
django-graphql-extensions==0.0.6
idna==2.6
jsonfield==2.0.2
Markdown==2.6.11
Expand Down
157 changes: 90 additions & 67 deletions strt/serapide_core/api/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
from graphene_django.filter import DjangoFilterConnectionField
from graphene_file_upload.scalars import Upload

from graphql_extensions.exceptions import GraphQLError

from strt_users.models import (
AppUser, Organization, OrganizationType
)
Expand Down Expand Up @@ -374,13 +376,18 @@ class Input:

@classmethod
def mutate_and_get_payload(cls, root, info, **input):
if info.context.user and info.context.user.is_authenticated and info.context.user.is_superuser:
_data = input.get('fase')
_fase = Fase()
nuova_fase = update_create_instance(_fase, _data)
return cls(nuova_fase=nuova_fase)
else:
return cls(nuova_fase=None, errors=[_("Forbidden")])
try:
if info.context.user and info.context.user.is_authenticated and info.context.user.is_superuser:
_data = input.get('fase')
_fase = Fase()
nuova_fase = update_create_instance(_fase, _data)
return cls(nuova_fase=nuova_fase)
else:
return GraphQLError(_("Forbidden"), code=403)
except BaseException as e:
tb = traceback.format_exc()
logger.error(tb)
return GraphQLError(e, code=500)


class UpdateFase(relay.ClientIDMutation):
Expand All @@ -394,17 +401,22 @@ class Input:

@classmethod
def mutate_and_get_payload(cls, root, info, **input):
if info.context.user and info.context.user.is_authenticated and info.context.user.is_superuser:
try:
_instance = Fase.objects.get(codice=input['codice'])
if _instance:
_data = input.get('fase')
fase_aggiornata = update_create_instance(_instance, _data)
return cls(fase_aggiornata=fase_aggiornata)
except ValidationError as e:
return cls(fase_aggiornata=None, errors=get_errors(e))
else:
return cls(fase_aggiornata=None, errors=[_("Forbidden")])
try:
if info.context.user and info.context.user.is_authenticated and info.context.user.is_superuser:
try:
_instance = Fase.objects.get(codice=input['codice'])
if _instance:
_data = input.get('fase')
fase_aggiornata = update_create_instance(_instance, _data)
return cls(fase_aggiornata=fase_aggiornata)
except ValidationError as e:
return cls(fase_aggiornata=None, errors=get_errors(e))
else:
return GraphQLError(_("Forbidden"), code=403)
except BaseException as e:
tb = traceback.format_exc()
logger.error(tb)
return GraphQLError(e, code=500)


class CreatePiano(relay.ClientIDMutation):
Expand All @@ -416,44 +428,49 @@ class Input:

@classmethod
def mutate_and_get_payload(cls, root, info, **input):
if is_RUP(info.context.user):
_piano_data = input.get('piano_operativo')
# Ente (M)
_data = _piano_data.pop('ente')
_ente = Organization.objects.get(usermembership__member=info.context.user, code=_data['code'])
_piano_data['ente'] = _ente
# Codice (M)
if 'codice' in _piano_data:
_data = _piano_data.pop('codice')
_codice = _data
else:
_year = str(datetime.date.today().year)[2:]
_month = datetime.date.today().month
_piano_id = Piano.objects.filter(ente=_ente).count() + 1
_codice = '%s%02d%02d%05d' % (_ente.code, int(_year), _month, _piano_id)
_piano_data['codice'] = _codice
# Fase (O)
if 'fase' in _piano_data:
_data = _piano_data.pop('fase')
_fase = Fase.objects.get(codice=_data['codice'])
try:
if is_RUP(info.context.user):
_piano_data = input.get('piano_operativo')
# Ente (M)
_data = _piano_data.pop('ente')
_ente = Organization.objects.get(usermembership__member=info.context.user, code=_data['code'])
_piano_data['ente'] = _ente
# Codice (M)
if 'codice' in _piano_data:
_data = _piano_data.pop('codice')
_codice = _data
else:
_year = str(datetime.date.today().year)[2:]
_month = datetime.date.today().month
_piano_id = Piano.objects.filter(ente=_ente).count() + 1
_codice = '%s%02d%02d%05d' % (_ente.code, int(_year), _month, _piano_id)
_piano_data['codice'] = _codice
# Fase (O)
if 'fase' in _piano_data:
_data = _piano_data.pop('fase')
_fase = Fase.objects.get(codice=_data['codice'])
else:
_fase = Fase.objects.get(codice='FP255')
_piano_data['fase'] = _fase
# Descrizione (O)
if 'descrizione' in _piano_data:
_data = _piano_data.pop('descrizione')
_piano_data['descrizione'] = _data[0]
_piano_data['user'] = info.context.user
_piano = Piano()
nuovo_piano = update_create_instance(_piano, _piano_data)
_procedura_vas = ProceduraVAS()
_procedura_vas.piano = nuovo_piano
_procedura_vas.ente = nuovo_piano.ente
_procedura_vas.tipologia = TIPOLOGIA_VAS.semplificata
_procedura_vas.save()
return cls(nuovo_piano=nuovo_piano)
else:
_fase = Fase.objects.get(codice='FP255')
_piano_data['fase'] = _fase
# Descrizione (O)
if 'descrizione' in _piano_data:
_data = _piano_data.pop('descrizione')
_piano_data['descrizione'] = _data[0]
_piano_data['user'] = info.context.user
_piano = Piano()
nuovo_piano = update_create_instance(_piano, _piano_data)
_procedura_vas = ProceduraVAS()
_procedura_vas.piano = nuovo_piano
_procedura_vas.ente = nuovo_piano.ente
_procedura_vas.tipologia = TIPOLOGIA_VAS.semplificata
_procedura_vas.save()
return cls(nuovo_piano=nuovo_piano)
else:
return cls(nuovo_piano=None, errors=[_("Forbidden")])
return GraphQLError(_("Forbidden"), code=403)
except BaseException as e:
tb = traceback.format_exc()
logger.error(tb)
return GraphQLError(e, code=500)


class UpdatePiano(relay.ClientIDMutation):
Expand Down Expand Up @@ -496,10 +513,12 @@ def mutate_and_get_payload(cls, root, info, **input):
_piano.descrizione = _data[0]
piano_aggiornato = update_create_instance(_piano, _piano_data)
return cls(piano_aggiornato=piano_aggiornato)
except ValidationError as e:
return cls(piano_aggiornato=None, errors=get_errors(e))
except BaseException as e:
tb = traceback.format_exc()
logger.error(tb)
return GraphQLError(e, code=500)
else:
return cls(piano_aggiornato=None, errors=[_("Forbidden")])
return GraphQLError(_("Forbidden"), code=403)


class CreateProceduraVAS(relay.ClientIDMutation):
Expand Down Expand Up @@ -536,9 +555,9 @@ def mutate_and_get_payload(cls, root, info, **input):
except BaseException as e:
tb = traceback.format_exc()
logger.error(tb)
return cls(nuova_procedura_vas=None, errors=get_errors(e))
return GraphQLError(e, code=500)
else:
return cls(nuova_procedura_vas=None, errors=[_("Forbidden")])
return GraphQLError(_("Forbidden"), code=403)


class UpdateProceduraVAS(relay.ClientIDMutation):
Expand Down Expand Up @@ -582,10 +601,12 @@ def mutate_and_get_payload(cls, root, info, **input):
_procedura_vas.note = _data[0]
procedura_vas_aggiornata = update_create_instance(_procedura_vas, _procedura_vas_data)
return cls(procedura_vas_aggiornata=procedura_vas_aggiornata)
except ValidationError as e:
return cls(procedura_vas_aggiornata=None, errors=get_errors(e))
except BaseException as e:
tb = traceback.format_exc()
logger.error(tb)
return GraphQLError(e, code=500)
else:
return cls(procedura_vas_aggiornata=None, errors=[_("Forbidden")])
return GraphQLError(_("Forbidden"), code=403)


"""
Expand Down Expand Up @@ -653,11 +674,11 @@ def mutate(self, info, file, **input):
_full_path = os.path.join(settings.MEDIA_ROOT, _file_path)
# Remove original uploaded/temporary file
os.remove(_destination.name)

return UploadFile(risorse=resources, success=True)
except BaseException:
except BaseException as e:
tb = traceback.format_exc()
logger.error(tb)
return GraphQLError(e, code=500)

# Something went wrong
return UploadFile(success=False)
Expand Down Expand Up @@ -687,9 +708,10 @@ def mutate(self, info, **input):
_risorsa.delete()

return DeleteRisorsa(success=True, uuid=_id)
except BaseException:
except BaseException as e:
tb = traceback.format_exc()
logger.error(tb)
return GraphQLError(e, code=500)

return DeleteRisorsa(success=False)

Expand Down Expand Up @@ -746,9 +768,10 @@ def mutate(self, info, file, **input):
os.remove(_destination.name)

return UploadRisorsaVAS(risorse=resources, success=True)
except BaseException:
except BaseException as e:
tb = traceback.format_exc()
logger.error(tb)
return GraphQLError(e, code=500)

# Something went wrong
return UploadRisorsaVAS(success=False)
Expand Down
41 changes: 40 additions & 1 deletion strt/serapide_core/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,49 @@
#
#########################################################################

import json

from django.http import HttpResponse
from django.contrib.auth.mixins import LoginRequiredMixin
from graphene_django.views import HttpError
from graphene_file_upload.django import FileUploadGraphQLView

class PrivateGraphQLView(LoginRequiredMixin,
from graphql_extensions.views import GraphQLView


class HTTPErrorAwareMixin:

def dispatch(self, request, *args, **kwargs):
data = self.parse_body(request)
show_graphiql = self.graphiql and self.can_display_graphiql(request, data)
if self.batch:
responses = [self.get_response(request, entry) for entry in data]
result = "[{}]".format(
",".join([response[0] for response in responses])
)
status_code = (
responses
and max(responses, key=lambda response: response[1])[1]
or 200
)
else:
result, status_code = self.get_response(request, data, show_graphiql)
_res = json.loads(result)
if 'errors' in _res and _res['errors'] and len(_res['errors']) > 0:
_error = _res['errors'][0]
e = HttpError(HttpResponse(status=_error['code'], content_type='application/json'), _error['message'])
response = e.response
# response.content = self.json_encode(request, {'errors': [self.format_error(e)]})
response.content = self.json_encode(request, _res)
return response

return super().dispatch(request, *args, **kwargs)


class PrivateGraphQLView(HTTPErrorAwareMixin,
LoginRequiredMixin,
GraphQLView,
FileUploadGraphQLView):

login_url = '/accounts/login/'
redirect_field_name = 'next'

0 comments on commit 53aa10c

Please sign in to comment.