MODX Community

Best way to check if user is currently logged in to the current context using tag syntax

I’m working on a site that needs to detect whether a user is logged on or not to the current context (or a specific named context, if that’s easier) and print data based on that (e.g., “Log In” vs. “Log Out”). Specifically, I need to be able to do this via tag syntax (for use in chunks).

Here are a couple ways to detect this that I have seen, but they don’t work exactly as I need them to (relative to the context). I was wondering if there is a “best” way somewhere:

[[!+modx.user.id:is=`0`:then=`...not logged in...`:else=`...logged in...`]]

[[!If?
&subject=`[[+modx.user.id]]`
&operator=`EQ`
&operand=`0`
&then=`...not logged in...`
&else=`...logged in...`
]]

Note, if a user is logged in to the manager context, but not the main website context, modx.user.id is set to the user’s ID on the manager context, which is the issue that I have with the above code examples.

You might be better served with a small utility snippet:

// snippet name: CheckLogin
if ($modx->user->hasSessionContext($modx->context->get('key'))) {
    $output = 'Logged in';
} else {
    $output = 'Not logged in';
}

return $output;

Use this snippet wherever you need the message posted:
[[CheckLogin]]

I agree with treigh.

If you have the snippet return true of false, you could use if as an output modifier or with the If snippet.

BTW, another approach is the Personalize extra, a snippet that will load different chunks depending on whether the user is logged in or not. You can put whatever you want in the two chunks.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.