tournasdim
5/20/2014 - 3:44 PM

Basic Authentication and Session Setup with Silex

Basic Authentication and Session Setup with Silex

<?php

use Silex\Application;
use Symfony\Component\HttpFoundation\Response;
use Silex\Provider\SessionServiceProvider;

/* include the silex autoload */
require_once __DIR__.'/../vendor/autoload.php';
 
$app = new Application();
$app->register(new SessionServiceProvider());

$app->get('/login', function () use ($app) {
    $username = $app['request']->server->get('PHP_AUTH_USER', false);
    $password = $app['request']->server->get('PHP_AUTH_PW');

    if ('admin' === $username && 'admin' === $password) {
        $app['session']->set('user', array('username' => $username));
        return $app->redirect('/account');
    }

    $response = new Response();
    $response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', 'site_login'));
    $response->setStatusCode(401, 'Please sign in.');
    return $response;
});

$app->get('/account', function () use ($app) {


    if (null === $user = $app['session']->get('user')) {
        return $app->redirect('/login');
    }

    return "Welcome {$user['username']}!";
});

$app->run();