0
votes

I am in the process of building a website (via MODx), and I don't want "non-logged in" users to be able to see the home page, but instead be redirected to an "under construction" page.

In my snippet, this is what I have so far:

<?php
if (! $modx->user->hasSessionContext($modx->context->get('key')) ) {
   $modx->sendRedirect('https://google.com');
} else {
    return '';
}

Sadly, this appears to not do anything, regardless of whether or not the user is logged in. (It apppears to be a problem with the second line, the actual redirect worked fine when I tested it) I am unable to figure out what is wrong, and any help is greatly appreciated!

The snippet that is in the page is [[!notloggedin]]

2

2 Answers

3
votes

These are right out of Bob's guides, but basically what you want to do is check to see if the user has an ID or username, if not, they are not logged in.

You probably want to do a bit of digging and see if you can implement your redirect in a plugin rather than a snippet possibly an onRequest event - so you are not rendering the page/resource before you discover that the user needs to be redirected.

There are various methods. One easy method is to use this code:
if ($modx->user->get('username') == '(anonymous)') {
    /* user is not logged in */
}    
Here is the official method for seeing if the user is logged in to the current context:

if ($modx->user->hasSessionContext($modx->context->get('key'))) {
    /* user is logged in */
}    
If you know the name of the current context (e.g., web), you can use this method. The name of the context is required:
if $modx->user->isAuthenticated('web') {
    /* user is logged in to web context */
} 
1
votes

If your site is simply not yet ready to be publicly available, MODX already allows for this.

See the following System Settings:

site_status
site_unavailable_message
site_unavailable_page

Alternatively, just set all your resources to 'unpublished', except for your custom error page. Logged in users will still be able to view all resources.