MODX resource group - hiding content if user does not have rights

Hello,

I’m coding a snippet/plugin that will check if given resource (with access group) can be viewed by the current user on the front end:

<?php
$resource = $modx->getObject('modResource', $id);
if ($resource) {
    $hasPermission = $resource->checkPolicy('view');
    if ($hasPermission) {
        return true;
    } else {
        return false;
    }
} else {
    return false;
}

I found this function checkPolicy() pointed by Bob Ray in the article below:
Determine if a user can access a resource in a snippet | MODX Community Forums and just want to confirm if this function does what i think…

according to documentation: checkPolicy() - Determine if the current user attributes satisfy the object policy.

and i have tested that and seems to be working. Resource is without any group then anybody can see it (even annoymos vistor), then if i have add user group then only these user that have access to the group can view it.
NOTE: I’m using Load, List and View Access policy for this user group. I want to user only be able to see the resource on the front end - nothing else.

Could somebody please tell that this is good approach and its safe to use it like that?

Also, a question related to that: is there any permission check for pdoResource snippet? I’m asking because the resource group check modx is handling by default:
In the code above i have provided i have noticed that:
“if ($resource)” check already can tell if user has access to the resource, because i have been testing that and if resource was protected and user was not in the resource group this:
$resource = $modx->getObject(‘modResource’, $id); was null

What I’m seeking is an explanation as everything seems to be working as i want but i have a few guesses and would like to be sure that i know what I’m doing…

thanks guys!

I believe when you call getObject(), only the load permission is checked.
(And usually you give the “anonymous” group load permission, so that MODX shows the “Unauthorized Page” and not the “Error Page”.)


Not by default. But there is a property &checkPermissions that you can use.


MODX uses the same function (checkPolicy()) when a resource is requested (on the front-end), pdoResources uses the same function when you use the &checkPermissions property, so I reckon your code is fine.

1 Like

oo wow! Thank you so much for this! That is very clear now.

This topic was automatically closed 2 days after discussion ended and a solution was marked. New replies are no longer allowed. You can open a new topic by clicking the link icon below the original post or solution and selecting “+ New Topic”.