CakePHP Auth error message

Today is just going to be a quick post. It is Labor Day here in the States and that means a whole heap of people are not going to be working, including me. So I am just messing around with some stuff in CakePHP as I am doing a side project for a local church to put up a calendar. Most of it is complete, but there was one thing that I wanted to change.

I am using the Auth component in my User model. I have allowed register, resetpass, and index. So when I go to view a user’s detailed profile, there is that message: “You are not authorized to access that location.” Which is a fine message and all, but I want it to be site specific, and also controller specific. So the Users controller will have a separate Auth error message than the Calendars controller. So here is what I did.

In the Users controller, I built a beforeFilter function. I set my authorized actions, set redirect to false. I also set a session level variable with the Auth, then I set the error message. There are a couple of messages you can set for the Users controller. You can set the loginError and the authError. The loginError will be the error when the user logs in and is unable to for whatever reason. The authError is what the user will see when they try to perform an action that is not allowed by them, whether it is because they are not logged in (as in my case) or you are using Auth to “authorize” an action.

So here is what it would look like:

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

	$this->Auth->allow('register', 'index', 'resetpass');
	$this->Auth->autoRedirect = false;
	$this->Auth->authorize = 'controller';
	$this->set('my_id', $this->Auth->user('user_id'));	
	$this->Auth->authError = "Please log in first in order to preform that action.";
}

So when you want to change the standard Auth error message, just remember to set the “authError” to whatever message you would like. Happy Labor Day!

One thought on “CakePHP Auth error message”

Comments are closed.