Skip to content

Instantly share code, notes, and snippets.

@dannevang
Created September 26, 2016 19:38
Show Gist options
  • Save dannevang/0e025077d297e88a42c4a17c0ff8e789 to your computer and use it in GitHub Desktop.
Save dannevang/0e025077d297e88a42c4a17c0ff8e789 to your computer and use it in GitHub Desktop.
MODX UserIsLoggedin - Checks whether or not a user is logged in and does something with it
<?php
/**
* UserIsLoggedin
* Checks whether or not a user is logged in or not and does something with it
*
* Examples (top-down):
* [[!UserIsLoggedin? &redirectToOnNotAuthorized=`id-of-page`]]
* OR
* [[!UserIsLoggedin? &sendUnauthorized=`1`]]
* OR
* [[!UserIsLoggedin? &memberOf=`Usergroup1,Usergroup2` &outputTrue=`<p>You're allowed to see this!</p>`]]
* OR
* [[!UserIsLoggedin? &outputTrue=`<p>You're logged in!</p>` &outputFalse=`<p>You're not logged in!</p>`]]
* [[!UserIsLoggedin? &userAgainst=`id-of-user` &outputTrue=`<p>You may see this!</p>` &outputFalse=`<p>You may not see this!</p>`]]
* [[!UserIsLoggedin? &userNotAgainst=`id-of-user` &outputTrue=`<p>You're not yourself, you may see this</p>` &outputFalse=`...`]]
*/
// properties
$redirectToOnNotAuthorized = (integer) $modx->getOption('redirectToOnNotAuthorized', $scriptProperties, 0);
$sendUnauthorized = (boolean) $modx->getOption('sendUnauthorized', $scriptProperties, 0);
$memberOf = $modx->getOption('memberOf', $scriptProperties, '');
if(!empty($memberOf)) { $memberOf = explode(',', $memberOf); }
$userAgainst = $modx->getOption('userAgainst', $scriptProperties, 0);
if(!empty($userAgainst)) { $userAgainst = explode(',', $userAgainst); }
$userNotAgainst = $modx->getOption('userNotAgainst', $scriptProperties, 0);
if(!empty($userNotAgainst)) { $userNotAgainst = explode(',', $userNotAgainst); }
$outputTrue = $modx->getOption('outputTrue', $scriptProperties, '');
$outputFalse = $modx->getOption('outputFalse', $scriptProperties, '');
$user =& $modx->user;
if(!$user->hasSessionContext($modx->context->get('key'))) {
if(!empty($redirectToOnNotAuthorized) && is_numeric($redirectToOnNotAuthorized)) {
$url = $modx->makeUrl($redirectToOnNotAuthorized, '', 'full');
$modx->sendRedirect($url);
} else if(!empty($sendUnauthorized) && $sendUnauthorized === true) {
$modx->sendUnauthorizedPage();
}
return $outputFalse;
}
$userId = $user->get('id');
if(
(!empty($userAgainst) && is_array($userAgainst) && !in_array($userId, $userAgainst)) ||
(!empty($userNotAgainst) && is_array($userNotAgainst) && in_array($userId, $userNotAgainst)) ||
(!empty($memberOf) && !$user->isMember($memberOf))
) {
return $outputFalse;
}
return $outputTrue;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment