diff --git a/app/controllers/users/carte_controller.rb b/app/controllers/users/carte_controller.rb index f41d55bf2..258299254 100644 --- a/app/controllers/users/carte_controller.rb +++ b/app/controllers/users/carte_controller.rb @@ -12,17 +12,18 @@ class Users::CarteController < UsersController end def save + safe_json_latlngs = clean_json_latlngs(params[:json_latlngs]) dossier = current_user_dossier dossier.quartier_prioritaires.each(&:destroy) dossier.cadastres.each(&:destroy) - if params[:json_latlngs].present? - ModuleApiCartoService.save_qp! dossier, params[:json_latlngs] - ModuleApiCartoService.save_cadastre! dossier, params[:json_latlngs] + if safe_json_latlngs.present? + ModuleApiCartoService.save_qp! dossier, safe_json_latlngs + ModuleApiCartoService.save_cadastre! dossier, safe_json_latlngs end - dossier.update(json_latlngs: params[:json_latlngs]) + dossier.update(json_latlngs: safe_json_latlngs) redirect_to modifier_dossier_path(dossier) end @@ -62,4 +63,18 @@ class Users::CarteController < UsersController api_carto: true } end + + private + + def clean_json_latlngs(json_latlngs) + # a polygon must contain at least 4 points + # https://tools.ietf.org/html/rfc7946#section-3.1.6 + if json_latlngs.present? + multipolygone = JSON.parse(json_latlngs) + multipolygone.reject! { |polygone| polygone.count < 4 } + if multipolygone.present? + multipolygone.to_json + end + end + end end diff --git a/spec/controllers/users/carte_controller_shared_example.rb b/spec/controllers/users/carte_controller_shared_example.rb index 229d2d3a3..b517ad8c4 100644 --- a/spec/controllers/users/carte_controller_shared_example.rb +++ b/spec/controllers/users/carte_controller_shared_example.rb @@ -59,6 +59,45 @@ shared_examples 'carte_controller_spec' do end describe 'POST #save' do + context 'it cleans json_latlngs' do + let(:dossier) { create(:dossier, state: 'en_construction') } + let(:json_latlngs) { multipolygon.to_json } + + before do + post :save, params: { dossier_id: dossier.id, json_latlngs: json_latlngs } + dossier.reload + end + + context 'when json_latlngs is invalid' do + let(:multipolygon) do + [ + [ + { lat: 1, lng: 1 }, + { lat: 1, lng: 2 }, + { lat: 1, lng: 1 } + ] + ] + end + + it { expect(dossier.json_latlngs).to be_nil } + end + + context 'when json_latlngs is valid' do + let(:multipolygon) do + [ + [ + { lat: 1, lng: 1 }, + { lat: 1, lng: 2 }, + { lat: 2, lng: 2 }, + { lat: 1, lng: 1 } + ] + ] + end + + it { expect(dossier.json_latlngs).to eq(json_latlngs) } + end + end + context 'En train de modifier la localisation' do let(:dossier) { create(:dossier, state: 'en_construction') } before do