Symfony, crud dostępny po zalogowaniu, inny dla admina

0

Cześć, utworzyłem w composerze crud, ale dostęp do dodawania postów i edycji jest dla każdego, chcę to zmienić. Chcę aby zwykły użytkownik mógł edytować tylko swoje posty. Mam tam też pole input autor i chciałbym to zmienić aby automatycznie pobierało id zalogowanego użytkownika.

0

Uprawnienia: https://symfony.com/doc/current/security/voters.html

Pobieranie id usera: https://stackoverflow.com/questions/10537879/symfony-getting-logged-in-users-id. Potem sobie po prostu przypisujesz to do wartości inputa. Jeśli używasz symfonowych formularzy, to możesz to ID wrzucić do constructora encji używanej w formularzu.

0

Mam taki błąd:

1/1) LogicException
AppBundle\Security\InformationsVoter must implement the Symfony\Component\Security\Core\Authorization\Voter\VoterInterface when used as a voter.

in AddSecurityVotersPass.php line 55
at AddSecurityVotersPass->process(object(ContainerBuilder))
in Compiler.php line 95
at Compiler->compile(object(ContainerBuilder))
in ContainerBuilder.php line 748
at ContainerBuilder->compile()
in Kernel.php line 544
at Kernel->initializeContainer()
in Kernel.php line 133
at Kernel->boot()
in Kernel.php line 193
at Kernel->handle(object(Request))
in index.php line 25
<?php

namespace App\Controller;

use App\Entity\Informations;
use App\Form\InformationsType;
use App\Repository\InformationsRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/informations")
 */
class InformationsController extends AbstractController
{
    /**
     * @Route("/", name="informations_index", methods={"GET"})
     */
    public function index(InformationsRepository $informationsRepository): Response
    {
        return $this->render('informations/index.html.twig', [
            'informations' => $informationsRepository->findAll(),
        ]);
    }

    /**
     * @Route("/new", name="informations_new", methods={"GET","POST"})
     */
    public function new(Request $request): Response
    {
        $information = new Informations();
        $form = $this->createForm(InformationsType::class, $information);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($information);
            $entityManager->flush();

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

        return $this->render('informations/new.html.twig', [
            'information' => $information,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="informations_show", methods={"GET"})
     */
    public function show(Informations $information): Response
    {
        return $this->render('informations/show.html.twig', [
            'information' => $information,
        ]);
    }

    /**
     * @Route("/{id}/edit", name="informations_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, Informations $information): Response
    {
        $form = $this->createForm(InformationsType::class, $information);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('informations_index', [
                'id' => $information->getId(),
            ]);
        }

        return $this->render('informations/edit.html.twig', [
            'information' => $information,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="informations_delete", methods={"DELETE"})
     */
    public function delete(Request $request, Informations $information): Response
    {
        if ($this->isCsrfTokenValid('delete'.$information->getId(), $request->request->get('_token'))) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($information);
            $entityManager->flush();
        }

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

<?php

namespace App\Security\Voter;

use App\Entity\Informations;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;

class InformationsVoter extends Voter
{
    
    const EDIT='edit';
    protected function supports($attribute, $subject)
    {
        
        
        return in_array($attribute, ['POST_EDIT', 'POST_VIEW'])
            && $subject instanceof \App\Entity\Informations;
    }

    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
    {
        $user = $token->getUser();
        // if the user is anonymous, do not grant access
        if (!$user instanceof UserInterface) {
            return false;
        }

        // ... (check conditions and return true to grant permission) ...
        switch ($attribute) {
            case 'POST_EDIT':
                 return $this->canEdit($post, $user);
                break;
            case 'POST_VIEW':
                 return $this->canView($post, $user);
                break;
        }

        return false;
    }
    
     private function canView(Post $post, User $user)
    {
        // if they can edit, they can view
        if ($this->canEdit($post, $user)) {
            return true;
        }

        // the Post object could have, for example, a method isPrivate()
        // that checks a boolean $private property
        return !$post->isPrivate();
    }

    private function canEdit(Post $post, User $user)
    {
        // this assumes that the data object has a getOwner() method
        // to get the entity of the user who owns this data object
        return $user === $post->getOwner();
    }
}

0

Nie do końca rozumiem gdzie mam ustawić to userId. Mam
InformationsType.php
Informations.php
InformationsController.php
Czy to stawić w value w builder

->add('author', TextareaType::class,array(                
               'attr' => array('value' => ''),
           ))

Czy inny sposób?

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