Replace content from login/register page with dashboard content

I am working on a community portal. When arriving on the site there is a login/registration page. When login in the user should be redirected to the dashboard with out adding an extention to the ur In other words. When arriving on the site the url is for example www. community. com after login in the user should be redirected to the dashboard, but the url should still read www. community. com and not for example www. community .com/dashboard.

It probably has to do with the routes but don’t know where to look at. Thank you in advange

You’d need to configure the route for / based on if someone is logged in or not.

High level:

if ($loggedIn) {
   Router::add('/', 'dashboard');
} else {
   Router::add('/', 'homepage');
}

@rpkamp Thanks for the reply. Based on my current routes (no AltoRouter in this case):

return [
    'default' => '/page',
    'errors'  => '/error/:code',
    'routes'  => [
	
	    // Front-end			
        '/page(/:action(/:id))' => [
            'controller' => 'Controller_Page',
            'action' => 'index',
        ],
		
        '/login(/:action(/:id))' => [
            'controller' => 'Controller_Page',
            'action' => 'index',
        ],		
		
		'/error(/:code)' => [      
            'controller' => 'Controller_Error',
            'action' => 'index',
        ],
		
        '/(:action(/:id))' => [
            'controller' => 'Controller_Page',
            'action' => 'index',
        ], 
		   		
    ]
];

Where do I add this?

Edit: And this is the Router class to be complete:

class Router
{
    public function start($route)
    {
        $this->config = Config::get('routes');

        if (empty($route) || $route == '/') {
            if (isset($this->config['default'])) {
                $route = $this->config['default'];
            } else {
                $this->error();
            }
        }

        try {
            foreach ($this->config['routes'] as $path => $defaults) {
                $regex = '@^' . preg_replace(
                    '@:([\w]+)@',
                    '(?P<$1>[^/]+)',
                    str_replace(')', ')?', (string) $path)
                ) . '@';
                $matches = [];

                if ( ! preg_match($regex, $route, $matches)) {
                    continue;
                }
                    
                $options = $defaults;
                foreach ($matches as $key => $value) {
                    if (is_numeric($key)) {
                        continue;
                    }

                    if ($key == 'controller') {
                        $value = ucfirst($value);
                    }

                    $options[$key] = $value;

                    if (isset($defaults[$key]) && strpos($defaults[$key], ":$key") !== false) {
                        $options[$key] = str_replace(":$key", $value, $defaults[$key]);
                    }
                }

                return $this->dispatch($options);
            }
        } catch (\Suggestotron\Controller\Exception $e) {
            $this->error();
        }
    }

    public function dispatch($options)
    {
        if (isset($options['controller']) && isset($options['action'])) {
            $callable = [$options['controller'], $options['action'] . 'Action'];
            if (is_callable($callable)) {
                $callable = [new $options['controller'], $options['action'] . 'Action'];
                $callable($options);
            } else {
                $this->error();
            }
        } else {
            $this->error();
        }
    }

    public function error()
    {
        if (isset($this->config['errors'])) {
            $route = $this->config['errors'];
            $this->start($route);
        } else {
            echo "An unknown error occurred, please try again!";
        }

        exit;
    }
}

Quick and dirty: Modify Router::start() to modify $this->config just after it was assigned when a user was logged in.

Correct solution: Create two configs, routes_unauthorized and routes_authorized and select which one to load in Router::start based on whether the user is logged in or not.

@rpkamp. Sorry for the late reaction. I wasn’t arround any longer when you wrote this responce.

I am a bit confused. Where / how do I implement this. And then my preference would go to the correct solution :wink:

Well, instead of setting routes in your config, you set two arrays; routes_unauthorized and routes_authorized.

And then in the router read the session to see if the user is logged in.

So instead of

$this->config = Config::get('routes');

You would do

$this->config = Config::get($isUserLoggedIn ? 'routes_authorized' : 'routes_unauthorized');

@rpkamp This is going a bit over my head :banghead:. In Router class I replaced

$this->config = Config::get('routes');

With what you just suggested. But then? Where do I set $isUserLoggedIn. I’m really confused. Based on what I showed you in post #3. What will stay and what do I not need any longer.

Thank you in advance

I don’t know how to set isUserLoggedIn because I don’t know how your authentication system works. Usually you get it from the session somehow.

@rpkamp. Fair enough. That has indeed nothing to do with the actual question. But what about the routes:

return [
    'default' => '/page',
    'errors'  => '/error/:code',
    'routes'  => [

    // routes

As shown in post #3. Should I adjust those as well?

Edit: When working on a basic site with CMS i have this in my routes file:

        '/admin/login' => [
            'controller' => 'Controller_Auth',
            'action' => 'login',
        ],

and in Controller_Auth:

class Controller_Auth extends Controller
{
    public function loginAction()
    {
        $admin = new Model_Admin(Db::getInstance());
        $error = null;

        if ($admin->is_admin()) {
            $admin->redirect('index.php');
        }
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if ($admin->attempt_login($_POST['email'], $_POST['password'])) {
                $admin->redirect('/admin/');
            }
            $error = 'Wrong e-mail and/or password';
        }
        $view = new View('admin/login.php', compact('error'));
        echo $view;
    }
}

Thinking about this more I think it would be easier to just change the route map at runtime instead of duplicating the entire thing.

So basically this:

class Router
{
    public function start($route)
    {
        $this->config = Config::get('routes');
        
        if ($userIsLoggedIn) {
            // override default homepage with dashboad for logged in users
            $this->config['default'] = '/dashboard';
        }

        // etc
    }
}

(assuming there is a /dashboard route to be used of course)

1 Like

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