Login Middle ware

Hi All,

Request your help, on the below code as the below code is going in circles

Environment:
Slim 3.12.1
PHP 7.2

HTML page:

<html lang="en">
<head>
<! -- Basic  CSS and JS Scripts -->
    <link rel="stylesheet" href="/static/css/bootstrap/bootstrap.min.css">
    <script type="text/javascript" src="/static/js/jquery/jquery-3.4.1.min.js"></script>
    <script type="text/javascript" src="/static/js/jquery/popper.min.js"></script>
    <script type="text/javascript" src="/static/js/bootstrap/bootstrap.min.js"></script>
<! -- ############################################### -->
<script type="text/javascript">
$(document).ready(function(){
$('#Ulogin').submit(function(e){
    e.preventDefault();
    $.ajax({
        url: '/admin/login',
        type: 'post',
        data:$('#Ulogin').serialize(),
        datatype: 'json',
        success: function(data){ $('#PStatus').html(data); }
    });
});
});
</script>
<! -- ############################################### -->
</head>
    <div class="container-fluid">
        <div class="form-group">
            <div class="row">
               <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 mt-5 px-10" align="center">
                  <form class="form-control-sm px-15 w-100 mx-auto" style="max-width: 330px" id="Ulogin">
                     <h1 class="h3 mb-3 font-weight-bold text-white">Please sign in</h1>
                     <label for="inputUsername" class="sr-only">Username</label>
                        <input type="username" id="username" name="Username" class="form-control" placeholder="-sysop-bpntid" required autofocus>
                     <label for="inputPassword" class="sr-only">Password</label>
                        <input type="password" id="password" name="Password" class="form-control mt-1" placeholder="password" required>
                           <button class="btn btn-lg btn-primary btn-block mt-3" type="submit">Sign in</button>
                  </form>
               </div>
            </div>
        </div>
    </div>

<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 mt-5 px-10" align="center"><p id="PStatus"></p></div>
</body>
</html>

PHP Code:

<?php
session_start();
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
################################################################
# Class Files
################################################################
require '../includes/vendor/autoload.php';
require_once('../config/credentials.php');
require_once('../config/parameters.php');

$conf = ['settings' => [
    'addContentLengthHeader' => false,
    'displayErrorDetails' => true,
    'determineRouteBeforeAppMiddleware' => true,
]];

$app = new \Slim\App($conf);
$container = $app->getContainer();
$container['view'] = function ($container) {
$view = new \Slim\Views\Twig('../admintpl');
$router = $container->get('router');
$uri = \Slim\Http\Uri::createFromEnvironment(new \Slim\Http\Environment($_SERVER));
$view->addExtension(new \Slim\Views\TwigExtension($router, $uri));
return $view;
};
################################################################
# Start Page
################################################################
$loggedInMiddleware = function ($request, $response, $next) {
    $route = $request->getAttribute('route');
    if (empty($route)) { throw new \Slim\Exception\NotFoundException($request, $response); }
    $routeName = $route->getName();
    $groups = $route->getGroups();
    $methods = $route->getMethods();
    $arguments = $route->getArguments();
    $publicRoutesArray = array('login');
    if (!isset($_SESSION['USER']) && !in_array($routeName, $publicRoutesArray)) { return $response->withRedirect('/admin/login'); }
    return $next($request, $response);
};

$app->add($loggedInMiddleware);

$app->get('/', function($request, $response) use($app) {
      $homeController = new HomeController($request, $response, $args);
      return $homeController->index();
      #return $this->view->render($response, 'page_login.html');
})->setName('home');

$app->get('/login', function($request, $response) use($app) {
      return $this->view->render($response, 'page_login.html');
})->setName('login');

$app->post('/login', function ($request, $response, $args) {
      if(!$_POST['username'] || !$_POST['password']) {
         $res = "Login Required";
         return $res;
      }
      $user = $request->getParam('Username');
      $pass = $request->getParam('Password');
      return $user;
      $_SESSION['user']['username'] = $user['username'];
});

$app->run();
?>

Hi!

This looks suspicious to me:

return $user;
$_SESSION['user']['username'] = $user['username'];

Hi Odan,

That line is just to set whether the post paramater are reaching the Middle ware or not, in practical, the validation would be done via ldap.

Fine, but the code after this return statement is not executed.

$_SESSION[‘user’][‘username’] = $user[‘username’];

HI Odan,

Even if we remove this line $_SESSION[‘user’][‘username’] = $user[‘username’]; the code is going in circle.

Removing this line was not my point :slight_smile:
I mean you should move it above the return statement.
Your POST login/ route should set the user into the session when the credentials are valid.

Also note, that this $_SESSION['USER'] and this $_SESSION['user'] is not the same.

Hi Odan,

Made the changes as requested as below , the issue is when we enter the username and password and hit the submit button another login page appers below the current page rather than returning the username in the HTML code

HTML Code

<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 mt-5 px-10" align="center"><p id="PStatus"></p></div>

Modified PHP Code

<?php
session_start();
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
################################################################
# Class Files
################################################################
require '../includes/vendor/autoload.php';
require_once('../config/credentials.php');
require_once('../config/parameters.php');

$conf = ['settings' => [
    'addContentLengthHeader' => false,
    'displayErrorDetails' => true,
    'determineRouteBeforeAppMiddleware' => true,
]];

$app = new \Slim\App($conf);
$container = $app->getContainer();
$container['view'] = function ($container) {
$view = new \Slim\Views\Twig('../admintpl');
$router = $container->get('router');
$uri = \Slim\Http\Uri::createFromEnvironment(new \Slim\Http\Environment($_SERVER));
$view->addExtension(new \Slim\Views\TwigExtension($router, $uri));
return $view;
};
################################################################
# Start Page
################################################################
$loggedInMiddleware = function ($request, $response, $next) {
    $route = $request->getAttribute('route');
    if (empty($route)) { throw new \Slim\Exception\NotFoundException($request, $response); }
    $routeName = $route->getName();
    $groups = $route->getGroups();
    $methods = $route->getMethods();
    $arguments = $route->getArguments();
    $publicRoutesArray = array('login');
    if (!isset($_SESSION['username']) && !in_array($routeName, $publicRoutesArray)) { return $response->withRedirect('/admin/login'); }
    return $next($request, $response);
};

$app->add($loggedInMiddleware);

$app->get('/', function($request, $response) use($app) {
      $homeController = new HomeController($request, $response, $args);
      return $homeController->index();
      #return $this->view->render($response, 'page_login.html');
})->setName('home');

$app->get('/login', function($request, $response) use($app) {
      return $this->view->render($response, 'page_login.html');
})->setName('login');

$app->post('/login', function ($request, $response, $args) {
      if(!$_POST['username'] || !$_POST['password']) {
         $res = "Login Required";
         return $res;
      }
      $user = $request->getParam('Username');
      $pass = $request->getParam('Password');
      **if($pass == "Test") { $_SESSION['user']['username'] = $user['username']; }**
      return $user;
      
});

$app->run();
?>

Log

**Initial Login Page**
http://abc.com/admin/login
Password: Test
Username: Test

POST http://abc.com/admin/login
Accept: */*
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8

HTTP/1.1 302 Found
 Redirect to: http://abc.com/admin/login
Date: Thu, 14 May 2020 15:27:55 GMT
Server: Apache
X-Powered-By: PHP/7.2.5
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Location: /admin/login
Content-Length: 0
Keep-Alive: timeout=15, max=99
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8

**Another Login Page after hitting the subbmit button**
GET http://abc.com/admin/login
Accept: */*
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36

HTTP/1.1 200 OK
Date: Thu, 14 May 2020 15:27:55 GMT
Server: Apache
X-Powered-By: PHP/7.2.5
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Keep-Alive: timeout=15, max=98
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

Please try to format / style your code with phpcs or PhpStorm. I’ts hard to read :wink:

This:

if($pass == "Test") { $_SESSION['user']['username'] = $user['username']; }

and this:

if (!isset($_SESSION['username']) && !in_array($routeName, $publicRoutesArray)) { return $response->withRedirect('/admin/login'); }

is not correct. Because the index user and username is not the same.

Hi Odan,

Even after changing the suggested line as below, no luck

if (!isset($_SESSION['user']) && !in_array($routeName, $publicRoutesArray)) { return $response->withRedirect('/admin/login'); }

$app->post('/login', function ($request, $response, $args) {
$user = $request->getParam('Username');
$pass = $request->getParam('Password');
if($pass == "Test") { $_SESSION['user']['username'] = $user; }
return $user;

Hi Odan,

Made soem changes as below and now every time when I access the URL it directtely takes us to the “page_dashboard.html” and not to the login page "page_login.html"

Changes Made:
``
if(!isset($_SESSION) && !in_array($routeName, $publicRoutesArray)) {
return $response->withRedirect(ROOT_PATH.‘login’);
}

**PHP Code**
```<?php
session_start();
define( "BASE_URL", "/admin/");
define("ROOT_PATH", 'http://'.$_SERVER['HTTP_HOST'].'/admin/');

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
################################################################
# Class Files
################################################################
require '../includes/vendor/autoload.php';
require_once('../config/credentials.php');
require_once('../config/parameters.php');

$conf = ['settings' => [
    'addContentLengthHeader' => false,
    'displayErrorDetails' => true,
    'determineRouteBeforeAppMiddleware' => true,
]];

$app = new \Slim\App($conf);
$container = $app->getContainer();
$container['view'] = function ($container) {
$view = new \Slim\Views\Twig('../admintpl');
$router = $container->get('router');
$uri = \Slim\Http\Uri::createFromEnvironment(new \Slim\Http\Environment($_SERVER));
$view->addExtension(new \Slim\Views\TwigExtension($router, $uri));
return $view;
};
################################################################
# Start Page
################################################################
$loggedInMiddleware = function ($request, $response, $next) {
    $route = $request->getAttribute('route');
    if (empty($route)) { throw new \Slim\Exception\NotFoundException($request, $response); }
    $routeName = $route->getName();
    $groups = $route->getGroups();
    $methods = $route->getMethods();
    $arguments = $route->getArguments();
    $publicRoutesArray = array('login');
    if(!isset($_SESSION) && !in_array($routeName, $publicRoutesArray)) { return $response->withRedirect(ROOT_PATH.'login'); }
    else { return $next($request, $response); }
    return $response;
};

$app->add($loggedInMiddleware);

$app->get('/', function($request, $response) use($app) {
      return $this->view->render($response, 'page_dashboard.html');
})->setName('home');

$app->get('/login', function($request, $response) use($app) {
      return $this->view->render($response, 'page_login.html');
})->setName('login');

$app->post('/login', function ($request, $response, $args) {
      $user = $request->getParam('Username');
      $pass = $request->getParam('Password');
      if($pass == "Test") {
         $_SESSION['user']['username'] = $user;
         return $user;
      }
});

$app->run();
?>

HI Odan,

Was able to resolve the issue, the solution was to set the rout name for /post login to setName(‘login’)

$app->post('/login', function ($request, $response, $args) {
      $user = $request->getParam('Username');
      $pass = $request->getParam('Password');
      if($pass == "Test") {
         $_SESSION['user']['username'] = $user;
         return $user;
      }
})->setName('login');