Ya tengo mas o menos encaminada la practica.
Esta empezó gestionando una tabla de usuarios(User), mas adelante se relaciono con otras tablas, las cuales también se gestionaban, ampliándose el proyecto, poco a poco.
Quiero cerrarlo con la gestión de usuarios y sesiones. En principio, por ahora, solo quería que se loguearan los administradores, en todas las direcciones.
He probado como 5 login distintos y ya no me aclaro.
La configuración de los ficheros es:
security.yml
Código PHP:
# To get started with security, check out the documentation:
# http://symfony.com/doc/current/book/security.html
security:
# http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
providers:
in_memory:
memory: ~
main:
entity: { class: inventariouserBundleEntityUser, property: username }
firewalls:
# disables authentication for assets and the profiler, adapt it according to your needs
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/login$
security: false
secured_area:
pattern: ^/
anonymous: ~
form_login:
login_path: user_login
check_path: user_login
logout:
path: user_logout
target: /
# activate different ways to authenticate
# http_basic: ~
# http://symfony.com/doc/current/book/security.html#a-configuring-how-your-users-will-authenticate
# form_login: ~
# http://symfony.com/doc/current/cookbook/security/form_login_setup.html
providers:
our_db_provider:
entity:
class: userBundle:User
property: username
# if you're using multiple entity managers
# manager_name: customer
firewalls:
main:
pattern: ^/
http_basic: ~
provider: our_db_provider
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, roles: ROLE_ADMIN }
encoders:
inventariouserBundleEntityUser:
algorithm: bcrypt
cost: 12
Código PHP:
user_homepage:
path: /
defaults: { _controller: userBundle:Default:login}
user_login:
path: /login
defaults: { _controller: userBundle:Default:login }
user_check:
path: /check
user_logout:
path: /logout
defaults: { _controller: userBundle:Default:logout }
user_prueba:
path: /prueba
defaults: { _controller: userBundle:Default:prueba }
user_index:
path: /user/index
defaults: { _controller: userBundle:User:index }
user_add:
path: /user/add
defaults: { _controller: userBundle:User:add }
user_create:
.....................
Código PHP:
{% extends '::frontend.html.twig' %}
{% block body %}
{% for flashMessage in app.session.flashbag.get('mensaje') %}
<span class="alert-success">
{{ flashMessage }}
<hr />
</span>
{% endfor %}
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<h1>Ingrese sus datos</h1>
</div>
<div class="col-sm-4"></div>
</div>
<form class="form-horizontal" role="form" method="POST" action="{{path('user_check')}}">
<div class="row">
<div class="col-sm-4"></div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-1 control-label">{{'Username'|trans}}</label>
<div class="col-sm-3">
<input type="text" name="_username" class="form-control" id="inputEmail3" value="{{ last_username }}" />
/>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4"></div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-1 control-label">Password</label>
<div class="col-sm-3">
<input type="password" name="_password" class="form-control" id="inputPassword3" placeholder="Password" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4"></div>
<div class="form-group">
<div class="col-sm-3">
<button type="submit" class="btn btn-default">{{'Sign in'|trans}}</button>
</div>
</div>
</form>
<div class="col-sm-4"></div>
</div>
{% endblock %}
Código PHP:
<?php
namespace inventariouserBundleController;
use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentSecurityCoreSecurityContext;
use SymfonyComponentSecurityCoreExceptionAuthenticationException;
use SymfonyComponentDependencyInjectionContainerAware;
use SymfonyBridgeDoctrineFormTypeEntityType;
use inventariouserBundleEntityUser;
use inventariouserBundleFormUserType;
use DoctrineORMEntityRepository;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilder;
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentFormExtensionCoreTypeChoiceType;
use SymfonyComponentFormExtensionCoreTypeButtonType;
class DefaultController extends Controller
{
public function loginAction()
{
$request = $this->getRequest();
$session = $request->getSession();
// get the login error if there is one
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(
SecurityContext::AUTHENTICATION_ERROR
);
} else {
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
return $this->render(
'userBundle:Default:login.html.twig',
array(
// last username entered by the user
'last_username' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
)
);
}
public function checkAction()
{
throw new RuntimeException('You must configure the check path to be handled by the firewall using form_login in your security firewall configuration.');
}
............
Cuando ejecuto el programa se va al login y aparece
UndefinedMethodException in DefaultController.php line 49:
Attempted to call an undefined method named "getRequest" of class "inventario\userBundle\Controller\DefaultControlle r".
De alguna forma es lógico porque el objeto todavía no se ha creado, pero he visto montones de ejemplos y todos empiezan con:
Código PHP:
$request = $this->getRequest();
¿Alguien tiene un ejemplo pequeño que funcione y que pueda ver?.
Saludos Luis.