JmJ
JmJ

Reputation: 2098

Auth not working in view

I'm trying to make certain buttons appear only to certain user types, I was adding this code around buttons in my view:

<li><?php
        if($this->Auth->user('role_id')==8){
                echo $this->Html->link(__('New Consumer Product'), array('action' => 'add'));
        }
    ?>
</li>

But that just gave me the error Error: AuthHelper could not be found. so I added the following in my AppController:

public $helpers = array('Auth');

However this just gave me the following error:

Helper class AuthHelper could not be found.
Error: An Internal Error Has Occurred.

What's happening here? Shouldn't it have worked when I added the Auth helper into my AppController?

I'd previously been using Auth in my UsersController with no problems at all.

Upvotes: 0

Views: 3364

Answers (4)

gmponos
gmponos

Reputation: 2277

Auth is a component not a helper. There is no Auth helper.

You can read the Authenticated user from the following command

$user = $this->Session->read("Auth.User");

Upvotes: -3

Daniel Jordi
Daniel Jordi

Reputation: 323

in cake 3.x I found the only thing that worked is to set the variable in AppController.php as so:

public function beforeRender(\Cake\Event\Event $event) {
     $this->set(['userData'=> $this->Auth->user(),
     ]);
}

the key difference being you have to pass in $event...

Upvotes: 1

rjdown
rjdown

Reputation: 9227

You can't use Auth in the view. That's only for controllers.

There are actually a few options such as setting/passing a variable for it, but this is the correct way as per the manual

    if((AuthComponent::user('role_id') == 8) {
        ...
    }

Upvotes: 3

floriank
floriank

Reputation: 25698

In your AppControllers beforeRender() or beforeFilter() just set the active user to the view:

public function beforeRender() {
    $this->set('userData', $this->Auth->user());
}

And work with that variable in the view. I prefer to not use the static method calls on the component inside a view, it's the wrong place for a component and also static calls aren't something you want to introduce a lot because of tight coupling.

My BzUtils plugin comes with a helper that can deal with this variable or can be configured to read the user data from session and offers some convenience methods.

Upvotes: 1

Related Questions