Protecting Pages On Your MODX Site — The Easy Way

Suppose you want to make a section of your site private so that only logged-in users can see the Resources. As with most things in MODX, there are several ways to protect Resources.

Update: 01/27/2014 — The original version of the full snippet at the end of this article did not work under certain circumstances. If you had trouble with the snippet, try the new code below.

Contexts

One method is to put all the private Resources in a separate context and protect it by creating a Context Access ACL entry that links the private Context to one or more User Groups. Once you do that, the Resources in the Context will be hidden from everyone who is not a member of the specified group or groups. I try to keep from using Contexts if I can, because they are difficult to set up correctly and they introduce complexities that I’d rather avoid. Links to Resources in other Contexts, for example, can be tricky to implement and users often get sent to the error (page-not-found) page rather than the unauthorized page when trying to access a forbidden resource.

Resource Groups

This is probably the most commonly used method. It involves putting the private Resources in a Resource Group and protecting them with a Resource Group Access ACL entry linking the Resource Group to the User Group(s) of the members who should have access to them. The down side of this method is that you have to remember to put all new private Resources in the Resource Group, and by default, users still get sent to the error page when trying to access private Resources.

The Easy Way — A Custom Snippet

This method is my favorite for simple situations where you want to protects a section of your site, either from users who are not logged in, or from users who don’t belong to one or more User Groups. It’s quick and easy, and it allows you to send the user wherever you like when they try to access a forbidden page.

The heart of this method is to put a snippet tag for a very simple snippet in the Template used by the private pages. The snippet checks the user’s status, and redirects them as necessary. Let’s call the snippet "PrivatePage."

This is the snippet tag for the Template:

[[!PrivatePage]]

This is the code of the PrivatePage snippet:

<?php
/* PrivatePage snippet */
/* Redirect anyone who is not logged in */

$key = $modx->context->get('key');
if (! $modx->user->hasSessionContext($key)) {
   $modx->sendUnauthorizedPage();
}
return '';

For users who are logged in to the current Context (usually ‘web’), the snippet does nothing at all. Users who are not logged in, however, get sent to the unauthorized page. You can set the ID of that page in the unauthorized_page System Setting. Just go to System | System Settings on the Top Menu and put "unauthorized" in the search box at the upper right and press the "Enter" key. Fine the unauthorized_page setting and double-click in the value field. Change the ID to the page you want to send user’s to. By default, it’s the home page, but it can be any page on your site.

Suppose you want to restrict the private pages to members of a particular User Group. This version of the snippet will do that. Just change "SomeUserGroup" to the name of an actual User Group.

<?php
/* PrivatePage snippet */
/* Redirect anyone who is not a member of a particular user group */

if (! $modx->user->isMember('SomeUserGroup')) {
$modx->sendUnauthorizedPage();
}
return '';

What if the private pages should be available to users in more than one User Group? Just change the test line to this:

if (! $modx->user->isMember(array('SomeUserGroup','SomeOtherUserGroup'))) {

You can list as many User Groups here as you like, just make sure that each group name is surrounded by single quotes and note that there is an extra set of parentheses in this version.

Send Them Somewhere Else

You might already be using the unauthorized page for something else or maybe you just feel like sending the users to some other page. That’s easy enough to do. Just change the sendUnauthorized() line to this (Change 12 to the ID of the page you want to send them to):

$url = $modx->makeUrl(12, "", "", "full");
$modx->sendRedirect($url);

Putting It All Together

Our snippet isn’t very flexible. The actions it takes, the group names, and the page to redirect to are all hard-coded into the snippet. It would be nice if this were configurable in the snippet tag so you could use it in different ways on different sites or different pages (the tag can go in the page content rather than the Template). Here’s a more generic version

<?php
/* PrivatePage snippet */
/* Redirect users who shouldn't see this page */

/** @param $redirectTo string -- (optional) ID of page to redirect to;
 *      default: unauthorized page
 *  @param $userGroups string -- (optional) Comma-separated list of
 *      User Groups that are authorized;
 *      if not set, users who are not logged in are redirected
 * */

$output = '';

function forward($id, &$modx) {

    if (empty($id)) {
        $modx->sendUnauthorizedPage();
    }
    $url = $modx->makeUrl((integer) $id, "", "", "full");
    if (empty($url)) {
        die('MakeUrl failed. ID: ' . $id);
    }
    $modx->sendRedirect($url);
}

$redirectTo = $modx->getOption('redirectTo', $scriptProperties, '');
$userGroups = $modx->getOption('userGroups', $scriptProperties, '');

if ((!empty($userGroups)) && strpos($userGroups, ',') !== false) {
    $userGroups = explode(',', $userGroups);
}

if (empty($userGroups)) {
    /* Redirect anyone who is not logged in */
    $key = $modx->context->get('key');
    if (!$modx->user->hasSessionContext($key)) {
        forward($redirectTo, $modx);
    }
} else {
    /* redirect if not a member of specified group(s) */
    if (!$modx->user->isMember($userGroups)) {
        forward($redirectTo, $modx);
    }
}

return $output;

This version has two properties for the snippet tag. Both are optional. If no properties are sent, users who are not logged in will be sent to the unauthorized page. The &userGroups property can contain a single User Group name or a comma-separated list of User Groups. Users who are not members will be forwarded. If the &redirectTo property is not set, they’ll go to the unauthorized page. If it’s set, they’ll go to the ID set in that property.

Examples

All versions of the tag will redirect users who are not logged in.

/* Redirect anyone who is not logged in to the unauthorized page */
[[!PrivatePage]]

/* Redirect anyone who is not logged in to Resource 12 */
[[!PrivatePage? &redirectTo=`12`]]

/* Redirect anyone who is not a member of the Subscribers user group
   to the unauthorized page */
[[!PrivatePage? &userGroups=`Subscribers`]]

/* Redirect anyone who is not a member of the Subscribers or Administrator
   user group to Resource 12 */
[[!PrivatePage? &userGroups=`Subscribers,Administrator` &redirectTo=`12`]]

Important: be sure the unauthorized page (or any other page you forward to) is published, and make sure the PrivatePage snippet will not execute on that page!

For more information on how to use MODX to create a web site, see my web site Bob’s Guides, or better yet, buy my book: MODX: The Official Guide.

Looking for quality MODX Web Hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , , , , , , , | Posted under MODX | RSS 2.0

Author Spotlight

Bob Ray

Bob Ray

I am the author of MODX: The Official Guide and over 30 MODX add-on components. I host Bob's Guides, a source of valuable information for MODX users, and I've been very active in the MODX Forums with over 14,000 posts.

Leave a Reply

Your email address will not be published. Required fields are marked *


− 2 = 1

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>