shield icon indicating copy to clipboard operation
shield copied to clipboard

fix: redirect()->withInput() or withErrors() causes ValidationException

Open kenjis opened this issue 3 years ago • 3 comments

Fixes https://github.com/codeigniter4/shield/discussions/381

redirect()->withInput() or withErrors() saves validation errors in the Session. And the check of the validation errors in Model (checkQueryReturn()), $this->validation->getErrors() returns the errors in the Session.

How to Test

--- a/app/Config/Filters.php
+++ b/app/Config/Filters.php
@@ -36,6 +36,7 @@ class Filters extends BaseConfig
             // 'honeypot',
             // 'csrf',
             // 'invalidchars',
+            'session' => ['except' => 'login*'],
         ],
         'after' => [
             'toolbar',
--- a/app/Controllers/Home.php
+++ b/app/Controllers/Home.php
@@ -2,10 +2,22 @@
 
 namespace App\Controllers;
 
+use Config\Services;
+
 class Home extends BaseController
 {
     public function index()
     {
-        return view('welcome_message');
+        $this->validation = Services::validation();
+
+        $this->validation->setRules([
+            'email' => 'required|valid_email|unique_email[{user_id}]',
+        ]);
+
+        if (! $this->validation->withRequest($this->request)->run()) {
+            return redirect()
+                ->to('logout')
+                ->withInput();
+        }
     }
 }

kenjis avatar Aug 15 '22 22:08 kenjis

@kenjis, I think we should merge this PR. The number of people involved in PR seems to be high. according to what you did recently for hotfix CI, we can proceed to write the test after the merge.

datamweb avatar Aug 16 '22 06:08 datamweb

+1 for merge now, It's breaking app at all.

jozefrebjak avatar Aug 16 '22 07:08 jozefrebjak

To merge, we need reviews.

kenjis avatar Aug 16 '22 08:08 kenjis

@kenjis For me this PR solved validation in forms.

jozefrebjak avatar Aug 16 '22 09:08 jozefrebjak

I don't like the production use of reflection. It's hard to trace this back in mobile, but couldn't this be solved by handling our validations from a clean instance?

// Validate the registration
if (! single_service('validation')->setRules($this->registrationRules)->run($event)) {
...

MGatner avatar Aug 16 '22 10:08 MGatner

couldn't this be solved by handling our validations from a clean instance?

No, because the session data ($_SESSION) is global.

See https://github.com/codeigniter4/CodeIgniter4/pull/6381 It helps your understanding.

kenjis avatar Aug 16 '22 10:08 kenjis

That helps! Okay I am on board with the Reflection solution. It's a hack but we have a fix in framework at least. Maybe add a note that if the minimum CI4 version is ever increased past 4.2.4 then it can be refactored. Or alternatively, check the actual version and have Reflection be the fallback solution.

MGatner avatar Aug 16 '22 11:08 MGatner