Accessing controller authorization through template View

That doesn’t make sense to me. If you:

$id = $this->request->getAttribute('identity');

at the top of your template. The later in the template do:

$identity->can(‘edit’, $article)

how do you imagine $identity will be set? You would have to do:

$id->can(‘edit’, $article)

or at the beginning do:

$identity = $this->request->getAttribute('identity');

This seems to be a simple problem of not keeping track of your variable names; setting one then using a different one and expecting it to be set.

Haha, sorry, that was not the case :sweat_smile: I adapted $identity to $id, but I quoted your original. Otherwise I would have had an easy unknown variable error, I assume :upside_down_face:

You can access the Identity object in either place. The line I wrote to get the object onto a variable:

$identity = $this->request->getAttribute('identity');

was written assuming you are in the Controller. Possibly the request property is available in the template also. (I typically use $this->getRequest() which I know is common to both locations).

At any rate, whichever place you acquire the object, it will be the same object. So, as long as you get it in a valid way the rest of the code will work.

Have you verified your are properly logged in? The request attributes array should have several keys on it that were written by the Authentication process:

[
	(int) 0 => 'csrfToken',
	(int) 1 => 'identity',
	(int) 2 => 'authentication',
	(int) 3 => 'authenticationResult',
	(int) 4 => 'authorization',
	(int) 5 => 'isAjax',
	(int) 6 => 'params',
	(int) 7 => 'webroot',
	(int) 8 => 'base',
	(int) 9 => 'here'
]

You should see 1, 2, and 3 and they should be loaded with objects. I believe the authenticationResult object has a method to report the result of the login attempt and what strategy succeeded.

The identity should, of course, have your identity object in it.

1 Like

If it’s a page that unauthenticated people can access, then your code needs to be along the lines of

if ($identity && $identity->can(...

Because $identity will be null when there is no user logged in, and you need to handle that scenario.

Simple confirmations can be surprisingly useful :flushed:. This was indeed the issue, so I have quickly resolved it (and applied it for delete as well):
<?php if($identity) { if ($identity->can('edit', $article)){echo $this->Html->link(__('Edit'), ['action' => 'edit', $article->id]);} } ?>

Thanks for all the help and additional insights !