How to get Joomla login form url for redirection

2019-06-04 21:01发布

问题:

I have custom component. For now everyone can access the page with this component. I want to redirect user to login page if he is not loged in. How to get login page url?

In my components view I write:

if($user->id != 0) {
    ..
}
else {
    $link = JRoute::_(???????);
    $this->setRedirect($link);  
}

Another question - is it ok to put into view or should I put it somwhere else? I am using Joomla 2.5.

回答1:

Try this ,

In that component view you have to restrict only for logged in users then,

$user = JFactory::getUser();
if($user->id != 0){

 // show your view
}
else{

$mainframe = JFactory::getApplication();
$mainframe->redirect('index.php?option=com_users&view=login');
}

You can use this code any where inside view.html.php,layouts etc.



回答2:

You don't specify, so I'm presuming Joomla 2.5.x.

In you view class seems to be the standard place... e.g. com_content checks in it's article/view.html.php file, with the following:

// Check the view access to the article (the model has already computed the values).
if ($item->params->get('access-view') != true && (($item->params->get('show_noauth') != true &&  $user->get('guest') ))) {
    JError::raiseWarning(403, JText::_('JERROR_ALERTNOAUTHOR'));

    return;
}

As you can see, com_content doesn't redirect the user, it simply raises a blocking warning message.

com_users can be called with a redirect parameter that contain the URL you want the user sent to after they login. The parameter should be base64 encoded and escaped with urlendcode. You can read about the redirect after login mechanism on docs.joomla.org.

To achieve a redirect to the login and then return to the original request after a successful login you can use something similar to this in your else block:

// Redirect to login
$uri        = JFactory::getURI();
$return     = $uri->toString();

$url  = 'index.php?option=com_users&view=login&return=' . urlencode(base64_encode($return));

$jAp->redirect($url, JText::_('Message_about_this_view_requiring_login'));


回答3:

This is ideally placed in the controller: but you could do much the same in the view.

first, encode your return link:

$link = base64_encode(JRoute::_("index.php?option=com_yourcomponent&view=someview&tmpl=somelayout", false));

then, build the route to the login page:

$rlink = JRoute::_("index.php?option=com_users&view=login&return=$link", false);
$msg = JText::_("COM_YOURCOMPONENT_LOGIN_TO_ACCESS");
$app = JFactory::getApplication();
$app->redirect($rlink, $msg);


标签: joomla