Slim framework の hook機能でログイン判定を行う

const SESSION_NAME="secretsecret";

session_cache_limiter(false);
session_name(SESSION_NAME);
session_start();

\Slim\Slim::registerAutoloader();

$app->hook('slim.before.dispatch', function() use ($app) {
    $publicRoutes = array('/login');

    function url_match($url, $arr){
        foreach($arr as $v) {
            $w = preg_quote(rtrim($v, '/'), '/');
            if (preg_match('/'.$w.'(\/.*)?/', $url)) {
                return true;
            }
        }
    }

    if(!url_match($app->request->getPath(), $publicRoutes)){
        if( isset($_SESSION['username']) ){
            return true;
        } else {
            $app->redirect('/login');
        }
    } 
    session_name(\lib\Constants::SESSION_NAME);
});

$app->get('/', function () use ($app) {
    $app->render('index.phtml');
});

/** ログイン */
$app->get('/login', function () use ($app) {
    $app->render('login.phtml');
});

$app->post(
    '/login',
    function () use ($app) {
        if(is_auth($app->request->post('inputUsername'), $app->request->post('inputPassword'))){
            session_regenerate_id();
            $_SESSION['username'] = $app->request->post('inputUsername');
            $app->redirect('/');
        } else {
            $app->redirect('/login?invalid=true');
        }
    }
);

function is_auth($user, $pass) {
    //ここに認証処理を書く
}

/** ログアウト */
$app->get('/logout', function () use ($app) {
    $app->deleteCookie(\lib\Constants::SESSION_NAME);
    session_destroy();
    $app->redirect('/');
});

$app->run();