Search code examples
phpauthenticationurl-routing

How do I implement a login/register system in a route based mvc correctly?


I started a little project where i have a router, that is going to return views, depending on the url you fill in (if it exists).

<?php

require_once 'page.php';

class Route
{
     private $_uri = array();
     private $_method = array();

/*
 * Builds a collection of internal URL's to look for
 * @param type $uri
 */
public function add($uri, $method = null)
{
    $this->_uri[] = '/' . trim($uri, '/');

    if($method != null){
        $this->_method[] = $method;
    }
}

public function submit()
{

    $uriGetParam = isset($_GET['uri']) ? '/' . $_GET['uri'] : '/';

    $page = new Page('index.twig');
}

}

For now the template is hardcoded, but i want to get the page name from the database later on, so i can have dynamic pages. That's why i need to know how i can make a proper login system with this code. I want that '/login' links to a login page that redirects me to a dashboard where i can manage data, like wordpress, creating pages etc. In case i missed data, ask me in the comments.


Solution

  • If you are going to create a login system then you'll most likely want to have a set of URLs that can only be accessed by logged int users.

    private $_logged_in_uris = [];
    

    Next, you'll want to modify your add() function to recognize URLs that need to be authenticated.

    /*
     * Builds a collection of internal URL's to look for
     * @param type $uri
     */
    public function add($uri, $method = null,$authenticated=false)
    {
        $this->_uri[] = '/' . trim($uri, '/');
        if($authenticated){
           $this->_logged_in_uris[] = '/' . trim($uri,'/');
        }
        if($method != null){
            $this->_method[] = $method;
        }
    }
    

    Can I ask why you are using $_GET['uri']? It's best to just grab the URI directly from the superglobals that PHP exposes to you. $_SERVER['REQUEST_URI'] is handy in this case.

    To figure out if a user is authenticated you'll need to setup a session variable once the user has logged in with a user name and password. You can then compare the uri with the uris within $_logged_in_uris and then check the session variable. If the session variable is set then they can access that portion of your website.