I am currently following the Silex tutorial on Security Service Provider.
I have the login form working, with my check_path set to /login_check using this code:
$app->register(new Silex\Provider\SecurityServiceProvider(), array(
'security.firewalls' => array(
'admin' => array(
'pattern' => '^/contacts/add',
'form' => array('login_path' => '/login', 'check_path' => '/login_check'),
'users' => array(
'admin' => array('ROLE_ADMIN', '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg=='),
),
)
)
));
However, I do not know how to validate a user login in silex as there is no example code for login_check:
$app->post('/login_check', function(Request $request) use ($app) {
// What now??
});
Silex/Symfony will process the authentication check for you so you will get no hook at the route /login_check
, but you can add a handler which will be called by Silex after a successfull login:
$app['security.authentication.success_handler.admin'] =
$app->share(function() use ($app) {
return new CustomAuthenticationSuccessHandler($app['security.http_utils'],
array(), $app);
});
The CustomAuthenticationSuccessHandler extends the DefaultAuthenticationSuccessHandler (Example):
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Silex\Application;
class CustomAuthenticationSuccessHandler extends DefaultAuthenticationSuccessHandler
{
protected $app = null;
public function __construct(HttpUtils $httpUtils, array $options, Application $app)
{
parent::__construct($httpUtils, $options);
$this->app = $app;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
$user = $token->getUser();
$data = array(
'last_login' => date('Y-m-d H:i:s')
);
// save the last login of the user
$this->app['account']->updateUserData($user->getUsername(), $data);
return $this->httpUtils->createRedirectResponse($request, $this->determineTargetUrl($request));
}
}
in this example onAuthenticationSuccess()
update the user data and log the datetime of the last login - you can perform any other action there.
There exists also handler for authentication failure and logout.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With