Skip to content

Instantly share code, notes, and snippets.

@henrikbjorn
Created December 29, 2011 20:42
Show Gist options
  • Save henrikbjorn/1536107 to your computer and use it in GitHub Desktop.
Save henrikbjorn/1536107 to your computer and use it in GitHub Desktop.
security:
encoders:
Diveshare\DiveshareBundle\Document\User: plaintext
providers:
default:
diveshare: ~
firewalls:
default:
pattern: ^/
# autologin: ~
form_login:
use_forward: true
post_only: true
check_path: /login
login_path: diveshare_session_new
username_parameter: "diveshare_session[username]"
password_parameter: "diveshare_session[password]"
csrf_parameter: "diveshare_session[_token]"
csrf_provider: form.csrf_provider
logout:
path: diveshare_session_delete
target: homepage
anonymous: ~
access_control:
- { path: ^/login, roles: IS_ANONYMOUS }
- { path: ^/user/new, roles: IS_ANONYMOUS }
<?php
namespace Diveshare\DiveshareBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\Event\FilterDataEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContext;
/**
* Generic LoginType that provides abstraction for the Security component and lets
* the form framework be used to templating and errors.
*
* @author Henrik Bjornskov <[email protected]>
*/
class SessionType extends AbstractType
{
/**
* @var Request
*/
protected $request;
/**
* @param Request $request
*/
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* @param FormBuilder $builder
* @param array $options
*/
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('username', 'text')
->add('password', 'password')
->add('remember_me', 'checkbox')
;
$session = $this->request->getSession();
$builder->addEventListener(FormEvents::SET_DATA, function (FilterDataEvent $event) use ($session) {
// If the Session have the AUTHENTICATION_ERROR constant we need to already
// set the error here because the Security Component will intercept any post
// request and the form will never be bound
if ($error = $session->get(SecurityContext::AUTHENTICATION_ERROR)) {
$event->getForm()->addError(new FormError($error->getMessage()));
}
// Set the last used username for the same reason as stated about. The form
// is never really bound.
$event->setData(array_replace((array) $event->getData(), array(
'username' => $session->get(SecurityContext::LAST_USERNAME),
)));
});
}
/**
* @return array
*/
public function getDefaultOptions(array $options)
{
return array(
'intention' => 'authenticate',
);
}
/**
* @return string
*/
public function getName()
{
return 'diveshare_session';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment