Redirecting when user is logged in?

31 views
Skip to first unread message

Mike Pearl

unread,
Sep 20, 2016, 2:13:30 PM9/20/16
to Joomla! General Development
I'm writing a component in Joomla 3.6.  This component includes a several-view "onboard" process - essentially account creation.  Once logged in the user will see a "dashboard" view, and have access to several other views.

I want to enforce access to these views based on whether the user is logged in or not. So:
  • If they're trying to view one of the onboard views, and are already logged in I want to redirect them to the "dashboard" view.
  • If they're not logged in and accessing one of the member views (e.g., the dashboard), I want to prompt them to log in.
Here are my questions:
  1. Where do I add the code to enforce this?  In the main controller (/components/com_mycomponent/controller.php), subcontrollers for each of the views (e.g., /components/com_mycomponent/controllers/dashboard.php), the view (view.html.php)???

  2. Can you please give me  a code sample, or point me to somewhere that explains how to do this?
Thanks!

Mike Pearl

unread,
Sep 20, 2016, 2:50:34 PM9/20/16
to Joomla! General Development
I have it working, but don't know if this is the right way of doing it.  Please let me know if this is the right way to do it:

in the main controller:

$onboard_views = array('home', 'foo', 'bar');
$user
= JFactory::getUser();

if($user->get('id'))
{
        // User is logged in, send them to dashboard if they're asking for an onboard view.
        $view = $this->input->get('view', 'dashboard');
        if(in_array($view, $onboard_views)
        {
        $this->input->set('view', 'dashboard');
}
} else {
// User is not logged in, if they're NOT looking for an onboard view, send them to the login page
$view
= $this->input->get('view', 'home');

if(!in_array($view, $onboard_views)
{
$this
->setRedirect(JRoute::_('indexphp?option=com_user&view=login'));
}
}
parent
::display($cachable, $urlparams);
         

Reply all
Reply to author
Forward
0 new messages