Skip to content

Instantly share code, notes, and snippets.

@immutef
Created October 27, 2010 09:58
Show Gist options
  • Save immutef/648762 to your computer and use it in GitHub Desktop.
Save immutef/648762 to your computer and use it in GitHub Desktop.
Symfony2 Security Form Login
# app/config/config.yml
security.config:
providers:
default:
password_encoder: sha1
entity: { class: UserBundle:User, property: username }
firewalls:
public:
pattern: /.*
anonymous: true
form_login: { provider: default }
logout: true
access_control:
- { path: /.*, role: IS_AUTHENTICATED_ANONYMOUSLY }
# src/Application/UserBundle/Resources/views/Security/login.twig
{% extends "UserBundle::layout.twig" %}
{% block content %}
{% if error %}
<div>{{ error }}</div>
{% endif %}
<form action="{% route "_security_check" %}" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="_username" value="{{ last_username }}" />
<label for="password">Password:</label>
<input type="password" id="password" name="_password" />
<input type="submit" name="login" />
</form>
{% endblock %}
# src/Application/UserBundle/Resources/config/routing.yml
_security_login:
pattern: /login
defaults: { _controller: UserBundle:Security:login }
_security_check:
pattern: /login_check
_security_logout:
pattern: /logout
<?php // src/Application/UserBundle/Controller/SecurityController.php
namespace Application\UserBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller,
Symfony\Component\Security\SecurityContext;
class SecurityController extends Controller
{
public function loginAction()
{
// get the error if any (works with forward and redirect -- see below)
if ($this['request']->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $this['request']->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
} else {
$error = $this['request']->getSession()->get(SecurityContext::AUTHENTICATION_ERROR);
}
return $this->render('UserBundle:Security:login.twig', array(
// last username entered by the user
'last_username' => $this['request']->getSession()->get(SecurityContext::LAST_USERNAME),
'error' => $error,
));
}
}
<?php // src/Application/UserBundle/Entity/User.php
namespace Application\UserBundle\Entity;
use Symfony\Component\Security\User\AccountInterface,
Symfony\Component\Security\Encoder\MessageDigestPasswordEncoder;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @orm:Entity(repositoryClass="Application\UserBundle\Entity\UserRepository")
* @orm:Table(name="user",
* uniqueConstraints={
* @orm:UniqueConstraint(name="username_idx", columns={"username"}),
* @orm:UniqueConstraint(name="email_idx", columns={"email"})
* }
* )
* @orm:HasLifecycleCallbacks
*/
class User implements AccountInterface
{
/**
* @orm:Column(name="id", type="integer")
* @orm:Id
* @orm:GeneratedValue(strategy="AUTO")
* @var integer
*/
protected $id;
/**
* @orm:Column(name="username", type="string", length="32")
* @validation:Min(3)
* @validation:Max(32)
* @validation:NotBlank
* @var string
*/
protected $username;
/**
* @orm:Column(name="email", type="string", length="256")
* @validation:Email
* @validation:NotBlank
* @var string
*/
protected $email;
/**
* @orm:Column(name="salt", type="string", length="32")
* @var string
*/
protected $salt;
/**
* @orm:Column(name="password", type="string", length="40")
* @validation:NotBlank
* @var string
*/
protected $password;
/**
* @orm:Column(name="activation_key", type="string", length="32", nullable="true")
* @var \DateTime
*/
protected $activationKey;
/**
* @orm:Column(name="activation", type="datetime", nullable="true")
* @var \DateTime
*/
protected $activation;
/**
* @orm:Column(name="last_login", type="datetime", nullable="true")
* @var \DateTime
*/
protected $lastLogin;
/**
* @orm:Column(name="created", type="datetime")
* @validation:NotBlank
* @var \DateTime
*/
protected $created;
/**
* @orm:Column(name="updated", type="datetime")
* @validation:NotBlank
* @var \DateTime
*/
protected $updated;
/**
* Constructor.
*/
public function __construct()
{
$this->created = $this->updated = new \DateTime('now');
}
/**
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function __toString()
{
return $this->getUsername();
}
/**
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* @param string $username
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* @param string $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* @param string $password
*/
public function setPassword($password)
{
$encoder = new MessageDigestPasswordEncoder('sha1');
$password = $encoder->encodePassword($password, $this->getSalt());
$this->password = $password;
}
/**
* @return string
*/
public function getActivationKey()
{
if (null === $this->activationKey) {
$this->activationKey = md5(sprintf(
'%s_%d_%s_%f_%s_%d',
uniqid(),
rand(0, 99999),
$this->getUsername(),
microtime(true),
$this->getEmail(),
rand(99999, 999999)
));
}
return $this->activationKey;
}
/**
* @return \DateTime
*/
public function getActivation()
{
return $this->activation;
}
/**
* @param \DateTime $activation
*/
public function setActivation(\DateTime $activation)
{
$this->activation = $activation;
}
/**
* @return \DateTime
*/
public function isActivated()
{
return (boolean) $this->activation;
}
/**
* @return \DateTime
*/
public function getLastLogin()
{
return $this->lastLogin;
}
/**
* @param \DateTime $lastLogin
*/
public function setLastLogin(\DateTime $lastLogin)
{
$this->lastLogin = $lastLogin;
}
/**
* @return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* @return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* @orm:PreUpdate
*/
public function update()
{
$this->updated = new \DateTime('now');
}
// AccountInterface
/**
* @return string
*/
public function getSalt()
{
if (null === $this->salt) {
$this->salt = md5(sprintf(
'%s_%d_%f',
uniqid(),
rand(0, 99999),
microtime(true)
));
}
return $this->salt;
}
/**
* @return array
*/
public function getRoles()
{
return array('ROLE_USER', 'ROLE_ADMIN');
}
/**
* @return void
*/
public function eraseCredentials()
{
$this->roles = null;
}
}
<?php // src/Application/UserBundle/Entity/UserRepository.php
namespace Application\UserBundle\Entity;
use Symfony\Component\Security\User\UserProviderInterface;
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository implements UserProviderInterface
{
/**
* @param string $username
* @return \Application\UserBundle\Entity\User
*/
public function loadUserByUsername($username)
{
return $this->findOneBy(array('username' => $username));
}
}
<?php // src/Application/UserBundle/Tests/Entity/UserRepositoryTest.php
namespace Application\UserBundle\Tests\Entity;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class UserRepositoryTest extends WebTestCase
{
/**
* @var \Application\UserBundle\Entity\UserRepository
*/
protected $repository;
protected function setUp()
{
$kernel = $this->createKernel();
$kernel->boot();
$this->repository = $kernel
->getContainer()
->get('doctrine.orm.entity_manager')
->getRepository('UserBundle:User');
}
public function testLoadUserByUsername()
{
$user = $this->repository->loadUserByUsername('pminnieur');
$this->assertEquals('example', $user->getUsername());
}
}
<?php // src/Application/UserBundle/Tests/Entity/UserTest.php
namespace Application\UserBundle\Tests\Entity;
use Application\UserBundle\Entity\User;
class UserTest extends \PHPUnit_Framework_TestCase
{
public function testConstructorSetsTimestamps()
{
$user = new User();
$dateTime = new \DateTime('now');
$this->assertEquals($dateTime, $user->getCreated());
$this->assertEquals($dateTime, $user->getUpdated());
}
public function testLifecycleCallbacks()
{
$user = new User();
$dateTime = new \DateTime('now');
sleep(1);
$user->update();
$this->assertGreaterThan($dateTime, $user->getUpdated());
}
public function testToString()
{
$user = new User();
$user->setUsername('example');
$this->assertEquals('example', (string) $user);
}
public function testUsername()
{
$user = new User();
$user->setUsername('example');
$this->assertEquals('example', $user->getUsername());
}
public function testEmail()
{
$user = new User();
$user->setEmail('mail@example.org');
$this->assertEquals('mail@example.org', $user->getEmail());
}
public function testPassword()
{
$user = new User();
$this->assertNull($user->getPassword());
$encoder = new \Symfony\Component\Security\Encoder\MessageDigestPasswordEncoder('sha1');
$password = $encoder->encodePassword('example', $user->getSalt());
$user->setPassword('example');
$this->assertEquals($password, $user->getPassword());
}
public function testActivation()
{
$user = new User();
$this->assertFalse($user->isActivated());
$dateTime = new \DateTime('now');
$user->setActivation($dateTime);
$this->assertEquals($dateTime, $user->getActivation());
$this->assertTrue($user->isActivated());
}
public function testActivationKeyIsOnlyGeneratedOnce()
{
$user = new User();
$key = $user->getActivationKey();
$this->assertEquals($key, $user->getActivationKey());
}
public function testLastLogin()
{
$user = new User();
$this->assertNull($user->getLastLogin());
$dateTime = new \DateTime('now');
$user->setLastLogin($dateTime);
$this->assertEquals($dateTime, $user->getLastLogin());
}
public function testSaltIsOnlyGeneratedOnce()
{
$user = new User();
$salt = $user->getSalt();
$this->assertEquals($salt, $user->getSalt());
}
}
@Kokil
Copy link

Kokil commented Feb 24, 2014

it gives error like
FileLoaderLoadException: Cannot import resource "/var/www/Symfony/app/config/config.yml" from "/var/www/Symfony/app/config/config_dev.yml". (There is no extension able to load the configuration for "Security.config" (in /var/www/Symfony/app/config/config.yml). Looked for namespace "Security.config", found "framework", "security", "twig", "monolog", "swiftmailer", "assetic", "doctrine", "sensio_framework_extra", "application_user", "acme_demo", "web_profiler", "sensio_distribution")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment