I want to turn on the debug mode for particualr controller in cakephp . Now I am doing this in config/core.php ,it working fine . But it is easy to enable /disable in controller ,we can avoid probelms with working in live sites ,otherwise the log will messed up users
its actually security critical to do anything wild like that in the core.php, it has to be and stay always 0 for ALL user frontend sites.
If you want to enable it for some admin backend action, you can do that inside the action at the very beginning with
Configure::write('debug', 2);
I'm late to the party on this one but just in case anyone else needs this
$skdebug = 0;
if ($_SERVER["REMOTE_ADDR"]== '121.75.33.244') $skdebug = 2;
Configure::write('debug', $skdebug);
I work offsite so I'm the only user on the IP, can be a pain to have to keep updating the IP when the router decides to bounce but it's a small price to pay.
It does mean debug is on for all controllers but that's not a problem.
It work for me in cakephp 3.4.
Use the below code in top of your controller in cakephp 3+:
use Cake\Core\Configure;
Then your beforeFilter() code should be something like below:
public function beforeFilter(\Cake\Event\Event $event){
parent::beforeFilter($event);
$this->loadComponent('RequestHandler');
// allow the function to public access
$this->Auth->allow(['index','logout','register','saveOrders']);
$actions = [
'saveOrders','save-orders',
];
// change the debug mode for a particular action
if (in_array($this->request->params['action'], $actions)) {
Configure::write('debug', false); // off debug mode
}
}
Related
I'm using Laravel 5.1 and trying to set different logging logic for a development and production environment.
Throughout my application I am using the Log facade with most of the following different methods:
Log::emergency($error);
Log::alert($error);
Log::critical($error);
Log::error($error);
Log::warning($error);
Log::notice($error);
Log::info($error);
Log::debug($error);
However, in my production environment, I would like to only log anything that is an Error, Critical, Alert or Emergency priority and ignore log requests with lower priority.
I couldn't find anything in the documentation or by exploring the code (both Log facade and the Monolog class).
My current thought is to create a custom wrapper around the Log facade that simply checks the environment and ignores anything below 400 (Monolog level for Error). Basically I would create a threshold variable in the environment file and anything below it will simply not be logged to the files.
Before I do so, I wanted to ask the community if there is an existing method/configuration for that which I could use, so that I don't re-invent the wheel.
If not - what would be the best approach?
This gist shows a more comfortable answer, as is not dependent on the
chosen handler.
I'm just providing the essential part in an answer here in case the above link gets deleted in some time.
In the AppServiceProviders' register method:
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
$monolog = Log::getMonolog();
foreach($monolog->getHandlers() as $handler) {
$handler->setLevel(Config::get('app.log-level'));
}
}
Then just add an additional key to your config/app.php:
'log-level' => 'info', // or whatever minimum log level you would like.
Add the following code to your AppServiceProvider::register():
$this->app->configureMonologUsing(function ($monolog) {
$monolog->pushHandler(
$handler = new RotatingFileHandler(
$this->app->storagePath() . '/logs/laravel.log',
$this->app->make('config')->get('app.log_max_files', 5),
$this->app->make('config')->get('app.level', 'debug')
)
);
$handler->setFormatter(new LineFormatter(null, null, true, true));
});
This recreates the logic that Laravel does when setting up the daily handler, but adds passing level to the handler.
You can set your minimum logging level by setting level value in your config/app.php:
'level' => 'debug', //debug, info, notice, warning, error, critical, alert, emergency
This is a bit of a workaround and each type of handler would need to be set up separately. I'm currently working on a pull-request to Laravel that would add setting minimum debug level from the config file without writing a line of code in your AppServiceProvider.
The code above hasn't been tested, so let me know if you see any typos or something doesn't work properly and I'll be more than happy to make that work for you.
We have recently shifted our application from http to https due to plain password logins via the API.
However, since doing so we are having real issues with Blackholes. Cake seems to black hole any 'POST' to the API function within our controller, despite
$this->Security->validatePost = false;
being set in AppController.php
We are using CakePHP version 2.1.3
Example of the code is as follows:
AppController.php:
function beforeFilter()
{
$this->Security->validatePost = false;
$this->Security->requireSecure();
}
SaleOrderController.php:
function beforeFilter()
{
parent::beforeFilter();
$this->Auth->allow('addApi'); // Allow access to the API without logging in.
}
POSTing to this URL gives back the following message:
"The request has been black-holed"
Once we can get this working (without being blackholed) we will adjust it so that only certain actions may be performed with validatePost = false. However, for now we just want to get the system working.
Note: 'GET' requests to the action work fine (are not blackholed).
Am I missing some simple configuration here or is there some deeper issue at work? The security module seems a little scant on documentation and from my google searches it looks like most people have avoided blackholing by performing the same steps I have.
Turns out the following has no effect in CakePHP 2.X:
$this->Security->enabled = false;
To disable components you need to follow this doc:
http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html
My issue was related to CSRF protection which I believe may be new in CakePHP 2.X?
Anyway, All I needed to do was add the following line within my SaleOrderController beforeFilter function:
$this->Security->csrfCheck = false;
My whole BeforeFilter function is now:
function beforeFilter()
{
parent::beforeFilter();
$this->Auth->allow('addApi'); // Allow access to the API without logging in.
if (isset($this->Security) && $this->action == 'addApi') {
$this->Security->csrfCheck = false;
$this->Security->validatePost = false;
}
}
See below URL
CakePHP: Disable Security Component site wide
Disabling input elements in a CakePHP form that uses Security component and jQuery
http://life.mysiteonline.org/archives/175-Disable-the-Security-Component-in-CakePHP-only-for-Certain-Actions.html
http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html
http://api.cakephp.org/class/security-component
Or try it:-
Even if you disable it in your app_controller your individual controller may have that security enabled.As my wild guess says this is what you want to do.If not let me know more about it
function beforeFilter(){
parent::beforeFilter();
if(isset($this->Security) && $this->RequestHandler->isAjax() && $this->action = 'add'){
$this->Security->enabled = false;
}
}
I want my users to redirect to a custom URL after they successfully register in Joomla .
I can't find any option for that !
How can I achieve this ?
If you are using Joomla!'s built-in menu to load the registration page, or getting there from the Login module there isn't a way to redirect (which is odd because you can set a redirect after login in the login module).
The best place to start would be to look at existing solutions in the "Authentication" section of the Joomla! Extension Directory. It appears there are several listed that support both the old 1.5 style sites and the new 1.7/2.5 sites.
(By the way if you are still on 1.7 you should update to the latest 2.5 as there are serious security issues in the 1.7 line.)
In your code set do the following;
$app=JFactory::getapplication();
$app->redirect('index.php?option=com_users&view=login'));
You can achieve this with a plugin (at least in Joomla 3.x - not sure how far back this will work off-hand). Key here is the onUserAfterSave event, which tells you whether the user is new or existing.
I wrote the code below some time ago, so can't recall the exact reason the redirect could not be done from within the onUserAfterSave event handler, but I think the redirect is subsequently overridden elsewhere in the core Joomla user management code if you try to do it from there, hence saving a flag in the session and checking it in a later event handler.
class PlgUserSignupRedirect extends JPlugin
{
public function onUserAfterSave($user, $isnew, $success, $msg)
{
$app = JFactory::getApplication();
// If the user isn't new we don't act
if (!$isnew) {
return false;
}
$session = JFactory::getSession();
$session->set('signupRedirect', 1);
return true;
}
function onAfterRender() {
$session = JFactory::getSession();
if ($session->get('signupRedirect')) {
JFactory::getApplication()->redirect('/my-post-signup-url');
$session->clear('signupRedirect');
}
}
}
I'm building a monitoring solution for logging PHP errors, uncaught exceptions and anything else the user wants to log to a database table. Kind of a replacement for the Monitoring solution in the commercial Zend Server.
I've written a Monitor class which extends Zend_Log and can handle all the mentioned cases.
My aim is to reduce configuration to one place, which would be the Bootstrap. At the moment I'm initializing the monitor like this:
protected function _initMonitor()
{
$config = Zend_Registry::get('config');
$monitorDb = Zend_Db::factory($config->resources->db->adapter, $config->resources->db->params);
$monitor = new Survey_Monitor(new Zend_Log_Writer_Db($monitorDb, 'logEntries'), $config->projectName);
$monitor->registerErrorHandler()->logExceptions();
}
The registerErrorHandler() method enables php error logging to the DB, the logExceptions() method is an extension and just sets a protected flag.
In the ErrorController errorAction I add the following lines:
//use the monitor to log exceptions, if enabled
$monitor = Zend_Registry::get('monitor');
if (TRUE == $monitor->loggingExceptions)
{
$monitor->log($errors->exception);
}
I would like to avoid adding code to the ErrorController though, I'd rather register a plugin dynamically. That would make integration into existing projects easier for the user.
Question: Can I register a controller plugin that uses the postDispatch hook and achieve the same effect? I don't understand what events trigger the errorAction, if there are multiple events at multiple stages of the circuit, would I need to use several hooks?
Register your plugin with stack index 101. Check for exceptions in response object on routeShutdown and postDispatch.
$response = $this->getResponse();
if ($response->isException()) {
$exceptions = $response->getException();
}
to check if exception was thrown inside error handler loop you must place dispatch() in a try-catch block
The accepted answer by Xerkus got me on the right track. I would like to add some more information about my solution, though.
I wrote a Controller Plugin which looks like that:
class Survey_Controller_Plugin_MonitorExceptions extends Zend_Controller_Plugin_Abstract
{
public function postDispatch(Zend_Controller_Request_Abstract $request)
{
$response = $this->getResponse();
$monitor = Zend_Registry::get('monitor');
if ($response->isException())
{
$monitor->log($response);
}
}
}
Note that you get an Array of Zend_Exception instances if you use $response->getException(). After I had understood that, I simply added a foreach loop to my logger method that writes each Exception to log separately.
Now almost everything works as expected. At the moment I still get two identical exceptions logged, which is not what I would expect. I'll have to look into that via another question on SO.
I'm using symfony 1.4 with Doctrine.
I'm trying to find a way to enable debug mode only if the current sfUser has a special debugger credential.
I already created a filter that deactivates the symfony debug bar if the sfUser has not this credential (the web_debug is set to true in my settings.yml file):
class checkWebDebugFilter extends sfFilter
{
public function execute($filterChain)
{
if(!$this->getContext()->getUser()->hasCredential('debugger'))
{
sfConfig::set('sf_web_debug', false);
}
$filterChain->execute();
}
}
The code of my index.php file is:
require_once(dirname(__FILE__).'/../config/ProjectConfiguration.class.php');
$configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'prod', false));
sfContext::createInstance($configuration)->dispatch();
The problem is, as the debug mode is hardcoded to false in my index.php, it is also disabled for debuggers; therefore the Web debug bar does not show Doctrine statements nor timing indications.
Is there a way to enable debug mode only if the current sfUser has a precise credential?
I tried to add sfConfig::set('sf_debug', true); to my checkWebDebugFilter::execute() method but as the filter is executed after Doctrine statements, they are not recorded.
I also tried to add session_start(); in my index.php file, then browsing through the $_SESSION variable to check whether the current user has the debugger credential, but it did not work (and it was not in the spirit of symfony either).
Thanks in advance for your answers.
When you pass the debug parameter in the index.php file, it actually is passed down to the sfApplicationConfiguration class of your application. In your case it can be found in the /apps/frontend/config/frontendConfiguration.class.php file. frontendConfiguration class extends sfApplicationConfiguration, and here you can add your code.
Debug parameter is stored in a protected variable of this class, so you wont be able to change it from filter, but you can create a function for example:
setDebug($mode) {
$this->debug = $mode;
}
And call it in your filter:
$this->context->getConfiguration()->setDebug(true);
You also could override isDebug() function in frontendConfiguration class, because that is used in the initConfiguration() function to initialize timing indicators and other debugging stuff.
if ($this->isDebug() && !sfWebDebugPanelTimer::isStarted())
{
sfWebDebugPanelTimer::startTime();
}
But you won't be able to check user permissions here, as sfUser class won't be initialized in this stage yet. But you can check $_COOKIES or $_SESSION global variables for a value that you can set when user is logging in. Or you can call sfWebDebugPanelTimer::startTime() in your Filter, but will miss a few microseconds.
I have not tested this, but that's how I would do it.
Try this
if you want to enable web_debug panel (dev) mode then
http://host_url/frontend_dev.php
or
write in your index.php 'frontend','dev',true.
require_once(dirname(FILE).'/../config/ProjectConfiguration.class.php');
$configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'dev', true));
sfContext::createInstance($configuration)->dispatch();