# Login Middle ware

**URL:** https://discourse.slimframework.com/t/login-middle-ware/4159
**Category:** Questions
**Created:** [May 14, 2020, 1:11pm UTC](https://discourse.slimframework.com/t/login-middle-ware/4159 "2020-05-14T13:11:03Z")
**Posts on this page:** 11
**Page:** 1

<div class="post-metadata">

### Author: ![Vino](https://avatars.discourse-cdn.com/v4/letter/v/c2a13f/32.png) [@Vino](https://discourse.slimframework.com/u/Vino)
#### Post date: [May 14, 2020, 1:11pm UTC](https://discourse.slimframework.com/t/login-middle-ware/4159/1 "2020-05-14T13:11:03Z")

</div>

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:**

```auto
<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:**

```auto
<?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();
?>

```

---

<div class="post-metadata">

### Author: ![odan](https://avatars.discourse-cdn.com/v4/letter/o/9de053/32.png) [@odan](https://discourse.slimframework.com/u/odan)
#### Post date: [May 14, 2020, 1:34pm UTC](https://discourse.slimframework.com/t/login-middle-ware/4159/2 "2020-05-14T13:34:51Z")

</div>

Hi!

This looks suspicious to me:

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

```

---

<div class="post-metadata">

### Author: ![Vino](https://avatars.discourse-cdn.com/v4/letter/v/c2a13f/32.png) [@Vino](https://discourse.slimframework.com/u/Vino)
#### Post date: [May 14, 2020, 1:42pm UTC](https://discourse.slimframework.com/t/login-middle-ware/4159/3 "2020-05-14T13:42:20Z")

</div>

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.

---

<div class="post-metadata">

### Author: ![odan](https://avatars.discourse-cdn.com/v4/letter/o/9de053/32.png) [@odan](https://discourse.slimframework.com/u/odan)
#### Post date: [May 14, 2020, 2:20pm UTC](https://discourse.slimframework.com/t/login-middle-ware/4159/4 "2020-05-14T14:20:39Z")

</div>

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

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

---

<div class="post-metadata">

### Author: ![Vino](https://avatars.discourse-cdn.com/v4/letter/v/c2a13f/32.png) [@Vino](https://discourse.slimframework.com/u/Vino)
#### Post date: [May 14, 2020, 2:32pm UTC](https://discourse.slimframework.com/t/login-middle-ware/4159/5 "2020-05-14T14:32:37Z")

</div>

HI Odan,

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

---

<div class="post-metadata">

### Author: ![odan](https://avatars.discourse-cdn.com/v4/letter/o/9de053/32.png) [@odan](https://discourse.slimframework.com/u/odan)
#### Post date: [May 14, 2020, 3:07pm UTC](https://discourse.slimframework.com/t/login-middle-ware/4159/6 "2020-05-14T15:07:27Z")

</div>

Removing this line was not my point 🙂  
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.

---

<div class="post-metadata">

### Author: ![Vino](https://avatars.discourse-cdn.com/v4/letter/v/c2a13f/32.png) [@Vino](https://discourse.slimframework.com/u/Vino)
#### Post date: [May 14, 2020, 3:34pm UTC](https://discourse.slimframework.com/t/login-middle-ware/4159/7 "2020-05-14T15:34:32Z")

</div>

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**

```auto
<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**

```auto
<?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**

```auto
**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

```

---

<div class="post-metadata">

### Author: ![odan](https://avatars.discourse-cdn.com/v4/letter/o/9de053/32.png) [@odan](https://discourse.slimframework.com/u/odan)
#### Post date: [May 14, 2020, 3:52pm UTC](https://discourse.slimframework.com/t/login-middle-ware/4159/8 "2020-05-14T15:52:03Z")

</div>

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

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.

---

<div class="post-metadata">

### Author: ![Vino](https://avatars.discourse-cdn.com/v4/letter/v/c2a13f/32.png) [@Vino](https://discourse.slimframework.com/u/Vino)
#### Post date: [May 14, 2020, 4:01pm UTC](https://discourse.slimframework.com/t/login-middle-ware/4159/9 "2020-05-14T16:01:28Z")

</div>

Hi Odan,

Even after changing the suggested line as below, no luck

```auto
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;

```

---

<div class="post-metadata">

### Author: ![Vino](https://avatars.discourse-cdn.com/v4/letter/v/c2a13f/32.png) [@Vino](https://discourse.slimframework.com/u/Vino)
#### Post date: [May 14, 2020, 7:14pm UTC](https://discourse.slimframework.com/t/login-middle-ware/4159/10 "2020-05-14T19:14:30Z")

</div>

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’);  
}

````auto
**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();
?>

````

---

<div class="post-metadata">

### Author: ![Vino](https://avatars.discourse-cdn.com/v4/letter/v/c2a13f/32.png) [@Vino](https://discourse.slimframework.com/u/Vino)
#### Post date: [May 18, 2020, 1:21pm UTC](https://discourse.slimframework.com/t/login-middle-ware/4159/11 "2020-05-18T13:21:31Z")

</div>

HI Odan,

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

```auto
$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');

```
