Symfony problem z logowaniem

0

Robię skrypt rejestracji tak to wygląda:

entity/user.php

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Table(name="app_users")
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User implements UserInterface, \Serializable
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=25, unique=true)
     */
    private $username;


    /**
     * @ORM\Column(type="string", length=4096)
     */
    private $plainPassword;

    /**
     * @ORM\Column(type="string", length=64)
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=254, unique=true)
     */
    private $email;

    /**
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive;

    /**
     * @ORM\Column(type="string", length=255, options={"default":"ROLE_USER"})
     */
    private $role;

    public function __construct()
    {
        $this->isActive = true;
        //$this->roles = "ROLE_USER";
        // may not be needed, see section on salt below
        // $this->salt = md5(uniqid('', true));
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function setUsername($username)
    {
        $this->username = $username;
    }

    public function getPlainPassword()
    {
        return $this->plainPassword;
    }

    public function setPlainPassword($password)
    {
        $this->plainPassword = $password;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function setPassword($password)
    {
        $this->password = $password;
    }

    public function getSalt()
    {
        // The bcrypt and argon2i algorithms don't require a separate salt.
        // You *may* need a real salt if you choose a different encoder.
        return null;
    }

    public function getRoles()
    {
        return $this->roles;
    }

    public function eraseCredentials()
    {
    }


    /** @see \Serializable::serialize() */
    public function serialize()
    {
        return serialize(array(
            $this->id,
            $this->username,
            $this->password,
            // see section on salt below
            // $this->salt,
        ));
    }

    /** @see \Serializable::unserialize() */
    public function unserialize($serialized)
    {
        list (
            $this->id,
            $this->username,
            $this->password,
            // see section on salt below
            // $this->salt
            ) = unserialize($serialized, array('allowed_classes' => false));
    }

    public function getRole(): ?string
    {
        return $this->role;
    }

    public function setRole(string $role): self
    {
        $this->role = $role;

        return $this;
    }
}

register controller

   /**
     * @Route("/register", name="user_registration")
     */
    public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder)
    {
        // 1) build the form
        $user = new User();
        $form = $this->createForm(UserType::class, $user);

        // 2) handle the submit (will only happen on POST)
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            // 3) Encode the password (you could also do this via Doctrine listener)
            $password = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
            $user->setPassword($password);

            // 4) save the User!
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();

            // ... do any other work - like sending them an email, etc
            // maybe set a "flash" success message for the user

            return $this->redirectToRoute('replace_with_some_route');
        }

        return $this->render(
            'security/register.html.twig',
            array('form' => $form->createView())
        );
    }

Form/UserType.php

<?php
namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('email', EmailType::class)
        ->add('username', TextType::class)
        ->add('plainPassword', RepeatedType::class, array(
        'type' => PasswordType::class,
        'first_options'  => array('label' => 'Password'),
        'second_options' => array('label' => 'Repeat Password'),
        ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
        'data_class' => User::class,
        ));
    }
}

Według tego poradnika: https://symfony.com/doc/master/doctrine/registration_form.html

Jednak wcześniej dodałem do tabeli kolumnę "role" i przy tworzeniu występuje błąd, że tam jest wartość null więc co zrobić, żeby przy rejestracji dodawało do tej kolumny wartość "ROLE_USER".

taki błąd:

Captu3re.PNG

Proszę o poradę.

0

Coś mi się nie zgadza.

  • masz return $this->roles; ale nie masz $roles,
  • masz to w konstruktorze: //$this->roles = "ROLE_USER";

Jeśli chcesz wartość domyślą dodaj ją prawidłowo w konstruktorze. Jeśli się mylę/coś przeoczyłem - pisz.

0

Myślę, że możesz rozważyć taki kod:

        $user->setRoles( array('ROLE_ADMIN') );
        $userManager->updateUser($user, true);

po prostu nigdzie my tej roli nie ustawiałeś :)

Co więcej, w konstrukturze, w tym tutorialu, oni ustawiają rolę taką jak chcesz

    public function __construct()
    {
        $this->roles = array('ROLE_USER');
    }
0

@ccwrc dzięki za pomoc, to przez to, że część skopiowałem z dokumentacji a część sam pisałem. Problem z roles udało mi się rozwiązać. Dałem setRole() w kontrolerze od rejestracji.

  1. Rejestracja działa(lub działała) Teraz działa ale za to przy logowaniu pojawia się kolejny błąd:
    Capture.PNG

  2. Była kolumna plain password która zawierała hasło nie hashowane! To skrajna nie odpoiwedzialność więc ją usunąlem, oczywiście w entity a później migrations:diff, żeby nie było. Czy to w ogóle tak ma być? Że hasło jest trzymane bez hasha? Dla mnie to coś dziwnego.

0

Jeśli korzystasz z FOSUserBundle, role muszą być zawarte w stringu po przecinku.
Jeśli masz własny mechanizm uwierzytelniania, możesz role zrobić tak, jak tylko Ci się podoba.

1 użytkowników online, w tym zalogowanych: 0, gości: 1