Show different message for first login / unauthorized access


#1

Hi, when a user tries to load my website, he is automatically redirected to the login page (this is OK), with the message “You are not authorized to access that location”; this is the same message that is shown when the user is already logged, but is not allowed to access certain locations.

Is it possible to change this message when the user is not logged in? For example, “You need to login to access this site”.

Thanks!


#2

Hi,
You can redifine Auth component property “authError”

$this->Auth->authError = “You need to login to access this site”.
Check a user logged or not and set authError.


#3

Ummmm, thanks, but that option changes the two messages (when the user is not authenticated and when the user is authenticated but is not allowed to access a certain page). What I need is to show different messages for each of those situations.


#4

disable message if the user is not authenticated in AppController.php

public function beforeFilter(Event $event)
    {
        if (!$this->Auth->user()) {
            $this->Auth->setConfig('authError', false);
            return null;
        }

    }

#5

Thanks all. The last option is not valid because when the user is not logged, or he is not allowed to access a page, the beforeFilter method is not executed. Finally I got it creating a custom AuthComponent.

In src/Controller/Component/CustomAuthComponent.php:

<?php

namespace App\Controller\Component;

use Cake\Event\Event;

class CustomAuthComponent extends \Cake\Controller\Component\AuthComponent {

    public function authCheck(Event $event)
    {
        if ($this->user()) {
            $this->setConfig('authError', null);
        }
        parent::authCheck($event);
    }
}

And in AppController.php:

$this->loadComponent(
    'Auth',
    [
        'className' => 'CustomAuth',
        // .....
        'authError' => __('You need to login to access this site')
    ]
);

Regards.