Brought to you with tenderness by the Knp team
KnpIpsum

A Symfony2 Tutorial Application

Ipsum Bundle

Login

Choose between two default users: user/userpass (ROLE_USER) or admin/adminpass (ROLE_ADMIN)

Code behind this page

User Story

src/Knp/IpsumBundle/Features/Secured.feature
Feature: Security
  In order to hide admin tools from anonymous users
  As a Symfony2 developer
  I need to be able to use security component

  Scenario: User clicks "Security" link on home page
    Given I am on homepage
    When I follow "Security"
    Then I should see "Simple page only for authenticated users"

  Scenario Outline: User logins
    Given I am not logged in
    And I am on Secured page
    When I follow "Secured page for admins only"
    And I fill in "Username" with "<username>"
    And fill in "Password" with "<password>"
    And press "LOGIN"
    Then I should see "<response>"

    Examples:
      | username | password  | response                          |
      | user     | userpass  | Access Denied                     |
      | admin    | adminpass | This page only viewable by Admins |

Controller Code

src/Knp/IpsumBundle/Controller/SecuredController.php:21
public function loginAction()
{
    if ($this->get('request')->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
        $error = $this->get('request')->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
    } else {
        $error = $this->get('request')->getSession()->get(SecurityContext::AUTHENTICATION_ERROR);
    }
     return $this->render('KnpIpsumBundle:Secured:login.html.twig', array(
        'last_username' => $this->get('request')->getSession()->get(SecurityContext::LAST_USERNAME),
        'error'         => $error,
    ));
}

Template Code

src/Knp/IpsumBundle/Resources/views/Secured/login.html.twig
{% extends 'KnpIpsumBundle::layout.html.twig' %}

{% block content %}
    <h1>Login</h1>

    <p>
        Choose between two default users: <em>user/userpass</em> <small>(ROLE_USER)</small> 
        or <em>admin/adminpass</em> <small>(ROLE_ADMIN)</small>
    </p>

    {% if error %}
        <div class="error">{{ error.message }}</div>
    {% endif %}

    <form action="{{ path("_security_check") }}" method="post" id="login">
        <div>
            <label for="username">Username</label>
            <input type="text" id="username" name="_username" value="{{ last_username }}" />
        </div>

        <div>
            <label for="password">Password</label>
            <input type="password" id="password" name="_password" />
        </div>

        <input type="submit" class="symfony-button-grey" value="LOGIN" />
    </form>
{% endblock %}