If($this->request->is('post')) {} Always returns false

Hello, I can not login, it seems like the post, never comes, I’m not sure if it’s a problem with the AJAX or Cakephp

Let’s see if you can help me.

Thanks, then I put the code of the different files:

AppController:

public function initialize()    {
        parent::initialize();

        $this->loadComponent('RequestHandler', [
            'enableBeforeRedirect' => false,
        ]);
        $this->loadComponent('Flash');
        $this->loadComponent('Auth',[
          'authorize' => ['Controller'],
          'authenticate' => [
            'Form' => [
              'fields' => [
                'username' => 'email',
                'password' => 'password'
              ],
              'userModel' => 'Users'
            ]
          ],
          'loginAction' => [
            'controller' => 'Users',
            'action' => 'login'
          ],          
          'loginRedirect' => [
              'controller' => 'Historia',
              'action' => 'historia'
          ],
          'logoutRedirect' => [
            'controller' => 'Users',
            'action' => 'login'
          ]
        ]);        
    }
  public function beforeFilter(Event $event) {
        $this->Auth->allow(['index', 'view', 'display']);
    }

    public function isAutorized($user) {      
      return true;
    }

UsersController:

public function beforeFilter(Event $event) {
        parent::beforeFilter($event);
        $this->Auth->allow('add','logout');
     }

      public function login() {
        $isPost = $this->request->is('post');
        if($isPost) {          
         $user = $this->Auth->identify();        
         if($user) {
           $this->Auth->setUser($user);
           return $this->redirect($this->Auth->redirectUrl());
         }
         else {
           $this->Flash->error(__('Email o contraseña incorrecta.'));
         }
       }
      }
 public function logout() {
       return $this->redirect($this->Auth->logout());
     }

     public function home() {
 $this->render();
     }

login.ctp:

<div id="login">
  <?= $this->Flash->render('auth') ?>
  <?= $this->Form->create('Usuario',['id' => 'loginform', 'class' => 'form loginform']); ?>
    <fieldset>
        <legend><?= __('Por favor entra tu email y contraseña') ?></legend>
        <?= $this->Form->control('email', ['placeholder' => 'E-mail', 'size' => '30', 'maxlength' => '30']) ?>
        <?= $this->Form->control('password', ['type' => 'password', 'placeholder' => 'Contraseña', 'maxlength' => '255']) ?>
    </fieldset>
  <?= $this->Form->button(__('Acceder', ['id' => 'submit', 'class' => 'submit'])); ?>
  <?= $this->Html->link('Registrarse', ['controller' => 'Users', 'action' => 'add'], ['id' => 'registro', 'class' => 'registro']) ?>
  <?= $this->Form->end() ?>
</div>

routes:
$routes->connect(’/’, [‘controller’ => ‘Users’, ‘action’ => ‘login’]);

User.php:
protected function _setPassword($password)
{
if (strlen($password) > 0) {
return (new DefaultPasswordHasher)->hash($password);
}
}

    protected $_hidden = [
        'password'
    ];

UsersTable.php:

  public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->isUnique(['email']));

        return $rules;
    }

jquery.js:

$(document).ready(function() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
		} else {
  			alert('Si esta viendo esto por favor dimelo.');
		}

		$("body").on("change", "#files", function(event) {
			var files = event.target.files[0];


      	var reader = new FileReader();

	    	reader.onload = (function(theFile) {
	      	return function(e) {
$(datos).html('<img class="thumb" src="' + e.target.result + '" title="' + escape(theFile.name) + '"/>');
	};
	    	})(files);

			reader.readAsDataURL(files);
  		});

		$("body").on("submit", "form", function(event) {
event.stopPropagation();
      event.preventDefault();
var loginform = "." + $(this,"form").prop("class");
  var type = "POST";
		  var url = $(this, "form").prop("action");
		  var cache = false;
		  var contentType = 'application/x-www-form-urlencoded';
		  var processData = true;

      if(event.target.files) {
      	var data = new FormData(this);
		   	contentType = false;
		    processData = false;
		  }
		  else {
		  	var data = $(this).serialize();
		  }
$.ajax({
		  	url: url,
		    data: data,
		    type: type,
		    cache: cache,
		    contentType: contentType,
		    processData: processData
			})
			.done(function(data) {
	if(loginform === ".form loginform") {
					$(".section").html(data);
				}
	else {
					$(".section").html(data);
				}
    	})
			.fail(function(jqXHR, textStatus, errorThrown) {
					if(jqXHR.status === 0) {
					alert('Not connect: Verify Network.');

				} else if(jqXHR.status == 404) {

					alert('Requested page not found [404]');

				} else if(jqXHR.status == 500) {

					alert('Internal Server Error [500].');

				} else if(textStatus === 'parsererror') {

					alert('Requested JSON parse failed.');

				} else if(textStatus === 'timeout') {

					alert('Time out error.');

				} else if(textStatus === 'abort') {

					alert('Ajax request aborted.');

				} else {

					alert('Uncaught Error: ' + jqXHR.responseText);
				}
			})
			.always(function(result) {
			});
	});
	});

add debug($this->request) and maybe exit() or die() after that in controller and watch your self what you get from browser.

Hello this is what returns me:

object(Cake\Http\ServerRequest) { trustProxy =&gt; false [protected] params =&gt; [ 'pass' =&gt; [], 'controller' =&gt; 'Users', 'action' =&gt; 'login', 'plugin' =&gt; null, '_matchedRoute' =&gt; '/', '_ext' =&gt; null, 'isAjax' =&gt; false ] [protected] data =&gt; [] [protected] query =&gt; [] [protected] cookies =&gt; [] [protected] _environment =&gt; [

.....
'REQUEST_METHOD' =&gt; 'GET',
....

] [protected] url =&gt; false [protected] base =&gt; '' [protected] webroot =&gt; '/' [protected] here =&gt; '/' [protected] _input =&gt; null [protected] _detectors =&gt; [ 'get' =&gt; [ 'env' =&gt; 'REQUEST_METHOD', 'value' =&gt; 'GET' ], 'post' =&gt; [ 'env' =&gt; 'REQUEST_METHOD', 'value' =&gt; 'POST' ], 'put' =&gt; [ 'env' =&gt; 'REQUEST_METHOD', 'value' =&gt; 'PUT' ], 'patch' =&gt; [ 'env' =&gt; 'REQUEST_METHOD', 'value' =&gt; 'PATCH' ], 'delete' =&gt; [ 'env' =&gt; 'REQUEST_METHOD', 'value' =&gt; 'DELETE' ], 'head' =&gt; [ 'env' =&gt; 'REQUEST_METHOD', 'value' =&gt; 'HEAD' ], 'options' =&gt; [ 'env' =&gt; 'REQUEST_METHOD', 'value' =&gt; 'OPTIONS' ], 'ssl' =&gt; [ 'env' =&gt; 'HTTPS', 'options' =&gt; [ (int) 0 =&gt; (int) 1, (int) 1 =&gt; 'on' ] ], 'ajax' =&gt; [ 'env' =&gt; 'HTTP_X_REQUESTED_WITH', 'value' =&gt; 'XMLHttpRequest' ], 'flash' =&gt; [ 'env' =&gt; 'HTTP_USER_AGENT', 'pattern' =&gt; '/^(Shockwave|Adobe) Flash/' ], 'requested' =&gt; [ 'param' =&gt; 'requested', 'value' =&gt; (int) 1 ], 'json' =&gt; [ 'accept' =&gt; [ (int) 0 =&gt; 'application/json' ], 'param' =&gt; '_ext', 'value' =&gt; 'json' ], 'xml' =&gt; [ 'accept' =&gt; [ (int) 0 =&gt; 'application/xml', (int) 1 =&gt; 'text/xml' ], 'param' =&gt; '_ext', 'value' =&gt; 'xml' ], 'mobile' =&gt; object(Closure) { }, 'tablet' =&gt; object(Closure) { } ] [protected] _detectorCache =&gt; [ 'ajax' =&gt; false ] [protected] stream =&gt; object(Zend\Diactoros\PhpInputStream) { [protected] resource =&gt; resource [protected] stream =&gt; 'php://input' [private] cache =&gt; '' [private] reachedEof =&gt; false } [protected] uri =&gt; object(Zend\Diactoros\Uri) { base =&gt; '' webroot =&gt; '/' [protected] allowedSchemes =&gt; [ 'http' =&gt; (int) 80, 'https' =&gt; (int) 443 ] [private] scheme =&gt; 'https' [private] userInfo =&gt; '' [private] port =&gt; null [private] path =&gt; '/' [private] query =&gt; '' [private] fragment =&gt; '' [private] uriString =&gt; null } [protected] session =&gt; object(Cake\Http\Session) { [protected] _engine =&gt; null [protected] _started =&gt; null [protected] _lifetime =&gt; '1440' [protected] _isCLI =&gt; false } [protected] attributes =&gt; [] [protected] emulatedAttributes =&gt; [ (int) 0 =&gt; 'session', (int) 1 =&gt; 'webroot', (int) 2 =&gt; 'base', (int) 3 =&gt; 'params', (int) 4 =&gt; 'here' ] [protected] uploadedFiles =&gt; [] [protected] protocol =&gt; null [protected] requestTarget =&gt; null [private] deprecatedProperties =&gt; [ 'data' =&gt; [ 'get' =&gt; 'getData()', 'set' =&gt; 'withData()' ], 'query' =&gt; [ 'get' =&gt; 'getQuery()', 'set' =&gt; 'withQueryParams()' ], 'params' =&gt; [ 'get' =&gt; 'getParam()', 'set' =&gt; 'withParam()' ], 'cookies' =&gt; [ 'get' =&gt; 'getCookie()', 'set' =&gt; 'withCookieParams()' ], 'url' =&gt; [ 'get' =&gt; 'getPath()', 'set' =&gt; 'withRequestTarget()' ], 'base' =&gt; [ 'get' =&gt; 'getAttribute("base")', 'set' =&gt; 'withAttribute("base")' ], 'webroot' =&gt; [ 'get' =&gt; 'getAttribute("webroot")', 'set' =&gt; 'withAttribute("webroot")' ], 'here' =&gt; [ 'get' =&gt; 'getAttribute("here")', 'set' =&gt; 'withAttribute("here")' ] ] }

The REQUEST_METHOD says it is GET, but that is not possible, apart from that I am not able to see anything else.

I’ve been doing tests and seen that returns the user data, but then does not redirect to history, gives an error 500, I mean if it seems to work the login, but it just does not work.

if($user) {          
           $this->Auth->setUser($user);
           debug($user);           
           return $this->redirect($this->Auth->redirectUrl());

I found the problem, in each controller, I have to verify that the user is explicitly authorized.

public function isAuthorized($ user) {
if($ this->request->getParam ('action') === 'history') {
         return true;
}
1 Like

I’m glad that you find it, debug() is very nice function in Cake. I use in my one project CakeDC Users plugin, but lot of config was doing by my friend. We also fing bug, that we reported on gitHub. When I try to use built-in auth in next project I just give up and it is accessible only form my home network :wink:
Maybe, someday…