Vengo a exponeros mi problema pues ya no se que hacer.. llevo casi dos semanas leyendo la documetación oficial de Symfony como otros que no son oficiales para intentar hacer un sistema de sesión de usuarios con Symfony.
No tengo ningún tipo a la hora de crear los usuarios e insertarlos a la base de datos pero, estoy intentando crear un 'login típico', es decir, de nombre de usuario y contraseña y tengo ciertos problemas con ello pues no me encuentra el usuario en la 'Base de datos' y ya no se a que se debe...
INFORMACIÓN: Estoy realizandolo mediante el fichero security.yml así que os pondre a continuación todo lo que creo que es necesario para ver el error. En cuyo necesitéis algo no tenéis que hacer más que pedirlo!
PD: En caso de que la duda sea solucionada, me gustaría saber el porque para poder entender en que estaba fallando...
Muchísimas gracias por adelantado!
security.yml:
# To get started with security, check out the documentation:
# http://symfony.com/doc/current/book/security.html
security:
encoders:
AppBundle\Entity\Users: bcrypt
AppBundle\Entity\Admin: bcrypt
# http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
providers:
chain_provider:
chain:
providers: [admin, users]
users:
entity:
class: AppBundle:Users
property: username
admin:
entity:
class: AppBundle:Admin
property: username
firewalls:
# disables authentication for assets and the profiler, adapt it according to your needs
user_secured_area:
pattern: ^/
anonymous: ~
provider: chain_provider
form_login:
login_path: login_user
check_path: login_user
csrf_token_generator: security.csrf.token_manager
default_target_path: /
logout:
path: /logout
target: /
access_control:
# require ROLE_ADMIN for /admin*
- { path: ^/admin, roles: ROLE_ADMIN }
services.yml
parameters:
# parameter_name: value
services:
# service_name:
# class: AppBundle\Directory\ClassName
# arguments: ["@another_service_name", "plain_value", "%parameter_name%"]
app.user_locale_listener:
class: AppBundle\EventListener\UserLocaleListener
arguments: ['@session']
tags:
- { name: kernel.event_listener, event: security.interactive_login, method: onInteractiveLogin }
routes.yml
app:
resource: "@AppBundle/Controller/"
type: annotation
logout:
path: /logout
** Entity: Users**
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @ORM\Table(name="users")
* @ORM\Entity(repositoryClass="UsersRepository")
* @UniqueEntity("username")
* @UniqueEntity("email")
*/
class Users implements UserInterface, \Serializable
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="text")
* @Assert\NotBlank()
*/
private $name;
/**
* @ORM\Column(type="text")
* @Assert\NotBlank()
*/
private $lastname;
/**
* @ORM\Column(type="text")
* @Assert\NotBlank()
*/
private $username;
/**
* @ORM\Column(type="string", length=255, unique=true)
* @Assert\NotBlank()
* @Assert\Email()
*/
private $email;
/**
*
* @Assert\Length(max=4096)
*/
private $plainPassword;
/**
*
* @ORM\Column(type="string", length=64)
*/
private $password;
/**
* @ORM\Column(type="text")
* @Assert\NotBlank()
*/
private $language;
/**
* @ORM\Column(type="boolean")
*/
private $isActive;
/*****************
* Users constructor.
*/
public function __construct() {
$this->language = 'es';
$this->isActive = true;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getLastname()
{
return $this->lastname;
}
/**
* @param mixed $lastname
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
}
/**
* @return mixed
*/
public function getUsername()
{
return $this->username;
}
/**
* @param mixed $username
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* @return mixed
*/
public function getEmail()
{
return $this->email;
}
/**
* @param mixed $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* @return mixed
*/
public function getPlainPassword()
{
return $this->plainPassword;
}
/**
* @param mixed $plainPassword
*/
public function setPlainPassword($plainPassword)
{
$this->plainPassword = $plainPassword;
}
/**
* @return mixed
*/
public function getPassword()
{
return $this->password;
}
/**
* @param mixed $password
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* @return mixed
*/
public function getLanguage()
{
return $this->language;
}
/**
* @param mixed $language
*/
public function setLanguage($language)
{
$this->language = $language;
}
/**
* @return mixed
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* @param mixed $isActive
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
//implementaciones de la interface
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
public function getRoles()
{
return array('ROLE_USER');
}
public function eraseCredentials()
{
}
/** @see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
$this->isActive,
));
}
/** @see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
$this->isActive,
) = unserialize($serialized);
}
}
security controller
<?php
/**
* Created by PhpStorm.
* User: tureey
* Date: 05/09/16
* Time: 13:35
*/
namespace AppBundle\Controller;
use AppBundle\Entity\Admin;
use AppBundle\Entity\Users;
use AppBundle\Form\AdminFormType;
use AppBundle\Form\UserFormType;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use AppBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\JsonResponse;
class SecurityController extends BaseController
{
/**
* @Route("/signup", name="signup")
* @param Request $request
* @return response
*/
public function guardarUser(Request $request)
{
$user = new Users();
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$form = $this->createForm(UserFormType::class, $user);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$password = $this->get('security.password_encoder')->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
$em = $this->getDoctrine()->getManager();
$em->flush();
return $this->redirectToRoute('signup');
}
$this->addData('formUser', $form->createView());
return $this->render('AppBundle:signup:signup.html.twig', $this->getData());
}
/**
* @Route("/login", name="login_user")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function showLogin(Request $request)
{
$authenticationUtils = $this->get('security.authentication_utils');
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
$this->addData('last_username', $lastUsername);
$this->addData('error', $error);
return $this->render('AppBundle:login:login.html.twig', $this->getData());
}
}
Login view
<div id="signupForm" class="row">
{% if error %}
<div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
{% if last_username %}
{{ last_username }}
{% endif %}
<!-- Formulario para iniciar sesión -->
<form action="{{ path('login_user') }}" method="post">
<div class="row">
<div class="input-field col s12">
<input type="text" id="username" name="_username" value="{{ last_username }}" />
<label for="username">Nombre usuario</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input type="password" id="password" name="_password" />
<label for="password">Constraseña</label>
</div>
</div>
<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
<input type="submit" value="Accede">
</form>
<!-- ¿Has olvidado el password? -->
<p id="forgotPassword"><a href="/login">¿Se te ha olvidado el nombre de usuario o la contraseña?</a></p>
<!-- Redirige a /signup -->
<p id="tienesCuenta">¿No tienes cuenta? <a href="/signup">Registrate</a></p>
<!-- Linia gris que divide -->
<div class="divider"></div>
<!-- Aceptas los terminos y politicas de privacidad -->
<p id="terminos">Si haces click en iniciar sesión con Facebook/Gmail y no eres usuario de My appLibrary, pasarás a estar registrado y aceptas los <a href="/terminos">Términos y condiciones</a>
y la <a href="politicas">Política de privacidad</a>de My appLibrary.</p>
</div>