I have a problem regarding my Symfony4 App.
What is happening?
I want to build a "Change Password" function for the currently logged in user. So far everything is fine imo. When I submit the form everything seems to have worked fine (redirect to correct page, page is displayed, .. ). But when I want to navigate to another page I get redirected to my login page due to no authentication. There I found out, that the password was not changed either.
I am very thankful for any kind of help!
EDIT
The log out is happening any time the form is submitted, regardles of errors or not.
Controller
/**
* @Route("/user/change-password", name="_user_change_password", methods={"GET","POST"})
* @Template("admin/change_password.html.twig")
*/
public function changePasswordAction(Request $request, UserPasswordEncoderInterface $encoder)
{
/**
* @var $user User
*/
$user = $this->getUser();
$form = $this->createForm(ChangeOwnPasswordFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$oldPassword = $form->get("oldPassword")->getData();
$checkPass = $encoder->isPasswordValid($user, $oldPassword);
if(!$checkPass) {
$this->addFlash("error", "user.wrong_old_password");
return array(
"form" => $form->createView()
);
}
$entityManager = $this->getDoctrine()->getManager();
$newPassword = $form->get("password")->getData();
$user->setPassword($encoder->encodePassword($user, $newPassword));
$user->setUpdatedAt(new \DateTime());
$entityManager->flush();
$this->addFlash("success", "user.password_changed");
return $this->redirectToRoute("_user_change_password");
}
return array(
"form" => $form->createView()
);
}
Form Type
class ChangeOwnPasswordFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('oldPassword', PasswordType::class, array(
'label' => 'user.old_password',
'mapped' => false,
'attr' => array(
'autocomplete' => 'current-password',
),
))
->add('password', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array(
'constraints' => array(
new NotBlank([
'message' => 'password_reset.password.blank',
]),
new Length([
'min' => 6,
'minMessage' => 'password_reset.password.short',
'max' => 4096,
'maxMessage' => 'password_reset.password.short',
]),
),
'label' => 'user.password'
),
'second_options' => array('label' => 'user.password_confirmation'),
'invalid_message' => 'user.password_mismatch',
'options' => array(
'attr' => array(
'autocomplete' => 'new-password',
),
)
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => User::class,
'validation_groups' => array("Create")
));
}
}
Twig
{% extends "base.html.twig" %}
{% block body %}
<h1>{{ ("user.change_password.title")|trans }}</h1>
{{ form_start(form) }}
{{ form_widget(form) }}
<button type="submit" class="btn btn-success">
{{ ("button.save")|trans }}
</button>
{{ form_end(form) }}
{% endblock %}