0

I am using a middleware to redirect to login page if session is not set.

$app->get('/dashboard', function (Request $request, Response $response, $args) {
include_once('employee-portal/dashboard.php');
return $response;})->add(new AuthMiddleware('counter', true, $app->getContainer()));

and my middleware:

class AuthMiddleware implements MiddlewareInterface{
private $min_role = 'counter';
private $redirect = true;
private $container = null;
public function __construct($role_required, $login_redirect, $container)
{
    $this->min_role = $role_required;
    $this->redirect = $login_redirect;
    $this->container = $container;
}
public function __invoke($request, $response, $next)
{
    if ($this->userIsAuthorised()) {
        return $next($request, $response);
    } else {
        if ($this->redirect) {
            /**
             * @var \Slim\Router router`
             */
            return $response->withRedirect(Details::getBaseUrl() . '/login' . '?ref=' . $request->getUri());
        }

        return $response->withStatus(401)->write("Sorry boss you are not authorised to see my secret");
    }

}

private function userIsAuthorised()
{
    if ($this->min_role == 'counter') {
        return true;
    } else if (SessionManager::isLoggedIn()) {
        if ($_SESSION['user_type']=='counter') {
            return true;
        }
    }
    return false;
}  }

but this doesn't works. i can even see the dashboard page without login. and even after login i cannot access the $_SESSION['user_type'] session variable.

any help would be appriciated. thanks in advance.

Saikat Bepari
  • 121
  • 1
  • 14

1 Answers1

0

You are passing 'counter' into your AuthMiddleware constructor, causing it to always return true in the first if() statement of userIsAuthorised() method.

if ($this->min_role == 'counter') 

will always be true because you set $this->min = 'counter' in your constructor. Try rewriting the new AuthMiddleware() and constructor so that you just pass in the container. Before calling the new AuthMiddleware() you can do the following: $container['min_role'] = 'counter' if you need it elsewhere in your app.

turtlechief
  • 100
  • 1
  • 7