8

I'm developing new MVC custom Joomla component (com_helpdesk) and need to verify if user is logged in to site. If not then it should redirect to the login page with "return" parameter. Could someone help me with it?

14

You can use Joomla's user object for this.

$user = JFactory::getUser();        // Get the user object
$app  = JFactory::getApplication(); // Get the application

if ($user->id != 0)
{
    // you are logged in
}
else 
{
    // Redirect the user
    $app->redirect(JRoute::_('index.php?option=com_users&view=login'));
}

If you would like to display a message when they get redirected, you can use the following:

$msg = 'You must be logged in to view this content';
$app->redirect(JRoute::_('index.php?option=com_users&view=login'), $msg);
0
4

Althugh Lodder have answered my questions, Here's what I did which I feel more sophisticated way to deal with custom component. It adds return parameter to com_users component.

In Main Controller, (components/com_mycomponent/controller.php)

I override following method:

public function display($cachable = false, $urlparams = array()) {

        $user = JFactory::getUser();

        if ($user->get('guest') == 1) {
            $this->setRedirect(JRoute::_('index.php?option=com_users&view=login&return=' . base64_encode(JUri::current()), "You must be logged in to view this content"));
            return;
        }

        parent::display($cachable, $urlparams);
    }
1

Let me try a third solution:

use Joomla\CMS\Factory;
...



public function display($cachable = false, $urlparams = array()) {

    $user = Factory::getUser();

    if ($user->guest) {
        $this->setRedirect(JRoute::_('index.php?option=com_users&view=login&return=' . base64_encode(JUri::current()), "You must be logged in to view this content"));
        return;
    }

    parent::display($cachable, $urlparams);
}

This example gets rid of the old JFactory class. Please note that with Joomla4 you can get the user with $app->getIdentity(). Factory::getUser() is deprecated but you still need to use it if you build a component for Joomla3 and Joomla4.

0

First assigned user object to $user variable

$user = JFactory::getUser();

Method 1

Check guest property of the user object, if it is 1 then user not logged in Joomla

if ($user->guest) {
    echo "Please login in site .";
} else {
    echo "welcome  ". $user->name ;
}

Method 2

Check user id is zero, if it is zero means user not logged in Joomla

if ($user->id == 0) {
    echo "Please login in site . ";
} else {
    echo "welcome " . $user->name ;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.