Search code examples
phpcakephpcakephp-1.2

Opposite of requireSecure in CakePHP


CakePHP has a requireSecure function in the SecurityComponent. I'm using this to force SSL when passing sensitive information such as a credit card number.

Questions:

  • Is there a requireNonSecure function?
  • If there's no requireNonSecure function is it possible to extend/add a function to CakePHP's core file without modifying the original file?

I want a requireNonSecure function because some of my pages have embedded videos that can only be played on our domain name. When using SSL the video hosting service does not recognize our domain name and cannot play the videos.

This is some of the code in the beforeFilter of a controller:

function beforeFilter() {
    parent::beforeFilter();

    $this->Security->validatePost = false; // disable CSRF protection
    $this->Security->blackHoleCallback = 'forceSSL';
    $this->Security->requireSecure('pay', 'index');

    $this->Auth->allow('index');
}

This is the callback in app_controller.php

function forceSSL() {
    $redirect = '';
    if (!empty($this->params['url']['redirect'])) {
        $redirect = '?redirect=' . $this->params['url']['redirect'];
    }

    $this->redirect('https://' . rtrim(env('SERVER_NAME'), '/') . $this->here . $redirect);
}

Solution

  • A solution would be to append a function to beforeFilter like this:

    In a controller:

    function beforeFilter() {
        parent::beforeFilter();
    
        // Require non secure (http) for video action
        $this->requireNonSecure('video');
    
        // ... other code here
    
    }
    

    In app_controller.php:

    function requireNonSecure() {
        $requireNonSecure = array_map('strtolower', func_get_args());
    
        if (in_array(strtolower($this->action), $requireNonSecure) || $requireNonSecure == array('*')) {
            if ($this->RequestHandler->isSSL()) {
                $this->redirect('http://' . rtrim(env('SERVER_NAME'), '/') . $this->here);
                return;
            }
        }
    }