0

Let's explain my problem... I have been reading how to build a session system with syfmfony in a lot of posts and the official documentation for a while.

I have no problem to crear tthe forms neededs to create users and I can check them in the db, the password is encrypted too... but actually, I am trying to build a "typical log in" so, username and password and I have some issues with this

PD: I am trying to do an ADMIN_ROLE and an USER_ROLE

INFO: I am doing using the security.yml file so I'm going to write all the files I think you need and if I didn't, ask for it.

Thank you so much in advance!

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

# Learn more about services, parameters and containers at
# http://symfony.com/doc/current/book/service_container.html
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 }

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);
    }
}

SecurityController

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>
  • 1
    So what is your problem? You need to be more specific. – Yoshi Sep 14 '16 at 09:43
  • Actually I can create users (signup) but I cannot login, the server returns me: No data received ERR_EMPTY_RESPONSE So There is no way to do the login so I cannot set the session... I am just stuck in here and I did all I could and I don't know the reason why it doesn't work! – Victor Ribero Guasch Sep 14 '16 at 09:52
  • Are you testing in dev mode (app_dev.php)? If not try that and see if you get a better error description. If this does not help, check the log file for fatal errors (in app/logs/dev.log). – Yoshi Sep 14 '16 at 09:54
  • @Yoshi I am going to try it! Anyway... I don't remember how install it, do you? To do it faster, if not I am going to look for it! Because in app doesn't appear me any directory called logs xD – Victor Ribero Guasch Sep 14 '16 at 10:08
  • If this is symfony v3+, check for `var/logs/dev.log`. If the log file is very long, just delete it, and rerun your page. It will be recreated and only include the newest log-messages. – Yoshi Sep 14 '16 at 10:10
  • It is symfony v3+ but, there isn't a /var/logs directory... its /var/log and it doesn't contain a /var/log/dev.log... :/ @Yoshi – Victor Ribero Guasch Sep 14 '16 at 10:14
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/123336/discussion-between-yoshi-and-victor-ribero-guasch). – Yoshi Sep 14 '16 at 10:15
  • Why `login_path` and `check_path` pointing both to `login_user`? You have to create a `check_login` action in your controller and leave it empty because symfony's security system will handle it automatically. – gp_sflover Sep 14 '16 at 10:39
  • @gp_sflover with newer symfony versions this is no longer the case. Even the docs use the same setup: https://symfony.com/doc/current/security/form_login_setup.html – Yoshi Sep 14 '16 at 10:58
  • @Yoshi Good to know. I just started to upgrade a large project and I missed that part because I've used guard to manage authentication. – gp_sflover Sep 14 '16 at 11:52
  • @Yoshi Finally I got an error : Authentication request could not be processed due to a system problem. I read many posts like: [this](http://stackoverflow.com/questions/28135572/deploying-symfony2-app-getting-fosuserbundle-errors) and [this too](http://stackoverflow.com/questions/31519901/failed-user-login-on-production-server-using-symfony-framework-authentication-r) but nothing helped... Do you have any idea? – Victor Ribero Guasch Sep 14 '16 at 18:41
  • The last time I had that error it was to a fatal error in the code. Can you get a stack trace? – Yoshi Sep 14 '16 at 18:58
  • If you're just learning the system, thats great. Carry on. However if you need a solution to get you going, you may consider a look at the FOS User Bundle. It does everything you're trying to accomplish. It's well maintained, easy to extend and the set up and config is minimal. https://symfony.com/doc/master/bundles/FOSUserBundle/index.html – Robert Wade Sep 15 '16 at 10:41
  • @RobertWade I am going to take a look! really thank you! – Victor Ribero Guasch Sep 15 '16 at 11:50
  • @RobertWade Actually I'm going to use this UserBundle but, it means so that it's not needed to implement the interfaces and this stuff? just the parameters that I want on my Entity:User and that's it? thanks! – Victor Ribero Guasch Sep 16 '16 at 15:33
  • Your best approach to that bundle or any bundle, is read thru the documentation. Start from scratch, and don't try and go retrofit existing classes if you're really not sure what's going on. follow the documentation. – Robert Wade Sep 16 '16 at 16:37
  • I think It's more complicate to addapt the Bundle than configure the security... actually I have some issues because the Bundle works with services only... right? – Victor Ribero Guasch Sep 17 '16 at 14:09

0 Answers0