Oliv
Oliv

Reputation: 256

How to check (in template) if $user->can('access', $request) in CakePHP 4?

I've created a RequestPolicy in src/Policy/RequestPolicy.php to allow access to all actions of my SuperRubriquesController only to a "super-admin" user :

namespace App\Policy;

use Authorization\Policy\RequestPolicyInterface;
use Cake\Http\ServerRequest;
use Authorization\IdentityInterface;

class RequestPolicy implements RequestPolicyInterface
{
    /**
     * Method to check if the request can be accessed
     *
     * @param \Authorization\IdentityInterface|null $identity Identity
     * @param \Cake\Http\ServerRequest $request Server Request
     * @return bool
     */
    public function canAccess($identity, ServerRequest $request)
    {
        if ($request->getParam('controller') === 'SuperRubriques' && $identity) {
            return $identity->role === 'super-admin';
        }

        return true;
    }
}

It works fine when I go to "/super-rubriques/index" or others actions of SuperRubriquesController but I'm wondering if there's a way to check if a user can access to a request from a template. For example, I'd like to check if user can access to action index of SuperRubriquesController before to display the link.

if ($this->request->getAttribute('identity')->can('access', $requestToSuperRubriquesIndex)) {
    echo $this->Html->link('Super Rubriques', ['controller' => 'SuperRubriques', 'action' => 'index']);
}

How can I build $requestToSuperRubriquesIndex ?

Upvotes: 0

Views: 422

Answers (1)

ndm
ndm

Reputation: 60453

One way would be to use the with* methods of the current request object to create a clone with modified data:

$requestToSuperRubriquesIndex = $this->request
    ->withParam('controller', 'SuperRubriques')
    ->withParam('action', 'index');

See also

Upvotes: 1

Related Questions