Quantcast
Channel: Active questions tagged symfony4 - Stack Overflow
Viewing all 3924 articles
Browse latest View live

LexikJWTAuthenticationBundle with multiple providers

$
0
0

I 2 part of applications - first for admins (admin panel) and second API. For API I want to use another model to check credentials and that retrieve a token. I thought that it could be achieved by specified check_path route where I can verify the provided data and then return manually token.

But It seems that the application doesn't event go to this endpoint because I haven`t seen any debug message from the response - only 401 error code. Here is my security.yml config:

security:
    encoders:
        App\Entity\Security\AdminUser:
            algorithm: bcrypt
        Lexik\Bundle\JWTAuthenticationBundle\Security\User\JWTUser:
            algorithm: bcrypt

role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: ROLE_ADMIN
providers:
    fos_userbundle:
        id: fos_user.user_provider.username_email
    jwt:
        lexik_jwt: ~

firewalls:
    api:
        provider: jwt
        pattern:  ^/api/
        stateless: true
        anonymous: true
        guard:
            authenticators:
                - 'jwt.token.authenticator'
        json_login:
            check_path: api.v1.0.token.get
            username_path: passwordName
            success_handler: lexik_jwt_authentication.handler.authentication_success
            failure_handler: lexik_jwt_authentication.handler.authentication_failure
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        context: 'main'
        pattern: ^/
        form_login:
            provider: fos_userbundle
            default_target_path: easyadmin
            csrf_token_generator: security.csrf.token_manager

        logout:       true
        anonymous:    true


access_control:
    - { path: ^/api/doc, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api/v1.0/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }

And here is my action where I tried to debug:

class TokenController extends AbstractController
{
/**
 * @Route("/login", name="api.v1.0.token.get", methods={"POST"})
 * @param Request $request
 */
public function obtainToken(Request $request, JWTEncoderInterface $encoder, SiteRepository $siteRepository)
  {
      dd(123); // I don`t see this message - only 401 error

  }
}

Adding the repository to construct gives user deprecated error

$
0
0

I have following lines of code in my controller.

<?php

namespace App\Controller;

use App\Repository\TaskListRepository;
use FOS\RestBundle\Controller\AbstractFOSRestController;

class ListController extends AbstractFOSRestController
{
    /**
     * @var TaskListRepository
     */
    private $taskListRepository;

    public function __construct(TaskListRepository $taskListRepository)
    {
        $this->taskListRepository = $taskListRepository;
    }

    /**
     * @Route("/lists", name="lists")
     */
    public function getListsAction()
    {
        return $this->taskListRepository->findAll();
    }

}

When I try to debug route, I am getting following error:

[info] User Deprecated: Using the WebserverBundle is deprecated since Symfony 4.4. The new Symfony local server has more features, you can use it instead. 2019-12-16T04:37:53+01:00 [info] User Deprecated: Loading the file "../../src/Controller/" from the global resource directory "D:\xampp\htdocs\symfony_rest\src" is depre cated since Symfony 4.4 and will be removed in 5.0.

How can I fix this issue?

How to use custome constraint in symfony routing

$
0
0

I have a custom validation constraint.

final class Cellphone extends Constraint
{

    public $message = 'Invalid cellphone given "{{ string }}"';

    public function validatedBy()
    {
        return CellphoneValidator::class;
    }

}

And It's validator :

class CellphoneValidator extends ConstraintValidator
{

    /**
     * @param mixed      $value
     * @param Constraint $constraint
     */
    public function validate($value, Constraint $constraint)
    {
        if (!$constraint instanceof Cellphone) {
            throw new UnexpectedTypeException($constraint, Cellphone::class);
        }
        if (null === $value || '' === $value) {
            return;
        }
        if (!is_string($value)) {
            throw new UnexpectedValueException($value, 'string');
        }
        if (!preg_match('/^09[0-9]{9}$/', $value, $matches)) {
            $this->context->buildViolation($constraint->message)
                          ->setParameter('{{ string }}', $value)
                          ->addViolation();
        }
    }
}

I want to use it in the method of my controller by annotation, is there any way to do that ?

/**
 * @param string             $uuid
 * @param TransactionService $transactionService
 * @Rest\Get("{uuid<@Cellphone>}/history", name="history")
 * or
 * @Rest\Get("{uuid}/history", requirements={"uuid":@Cellphone} name="history")
 *
 * @return View
 */
public function getHistory(........)
{
 ........

And It throws following exception exception :

Routing requirement for "uuid" must be a string in /usr/share/nginx/config/routes/../../src/Http/Api/Controller/ (which is being imported from "/usr/share/nginx/config/routes/annotations.yaml"). Make sure annotations are installed and enabled.

Symfony 4 : Webpack Encore ReferenceError: $ is not defined

$
0
0

I try to add jQuery to webpack Encore

.addEntry('js/app', [
    './assets/js/jquery.min.js',
    './assets/js/app.js',
])

but always when I try to use a jQuery code I get this error

Uncaught ReferenceError: $ is not defined

I try to add this function .disableSingleRuntimeChunk() and

.autoProvidejQuery({
   'window.jQuery': 'jquery'
})

to the webpack.config.js

but always I get to same error, is there any solution ?

On Symfony 4-4, I can't create a controller using the CLI

$
0
0

I am a false newbie on Symfony. I learnt about 3.2 in school but for my current job, we are using 4.4. I wanted to redo all the training at home and I am stuck (that's really a good start if I must say :) )

I have downloaded Composer uptodate and all seems fine. I can start my server.

But when I use the "php bin/console make:controller" each time either, via my CLI or a shell like cmder, I get a red alert: "Aborted."

I don't see my mistakes on my configuration. I am on W10pro and work with PhpStorm.

Did that occur to you? Thanks.

Could not determine access type

$
0
0

I need to create a master entity named Users and another one named Specialties. A user can have many specialties.

There is my users entity:

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UsersRepository")
 * @UniqueEntity(
 *     fields={"email"},
 *     errorPath="email",
 *     message="It appears you have already registered with this email."
 * )
 */
class Users implements UserInterface
{

    /**
     * Users constructor.
     */
    public function __construct()
    {
        $this->created_at = new \DateTime();
        $this->specialtyId = new ArrayCollection();
    }

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @Groups({"public"})
     */
    private $id;

    //Other properties there...

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Specialties", inversedBy="users")
     */
    private $specialtyId;

    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * @return Collection|Specialties[]
     */
    public function getSpecialtyId(): Collection
    {
        return $this->specialtyId;
    }

    public function addSpecialtyId(Specialties $specialtyId): self
    {
        if (!$this->specialtyId->contains($specialtyId)) {
            $this->specialtyId[] = $specialtyId;
        }
        return $this;
    }

    public function removeSpecialtyId(Specialties $specialtyId): self
    {
        if ($this->specialtyId->contains($specialtyId)) {
            $this->specialtyId->removeElement($specialtyId);
        }
        return $this;
    }

}

There is my specialties entity:

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\SpecialtiesRepository")
 */
class Specialties
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    //Other properties there...

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Users", mappedBy="specialtyId")
     */
    private $users;

    public function __construct()
    {
        $this->users = new ArrayCollection();
    }

    /**
     * @return Collection|Users[]
     */
    public function getUsers(): Collection
    {
        return $this->users;
    }

    public function addUser(Users $user): self
    {
        if (!$this->users->contains($user)) {
            $this->users[] = $user;
            $user->addSpecialtyId($this);
        }

        return $this;
    }

    public function removeUser(Users $user): self
    {
        if ($this->users->contains($user)) {
            $this->users->removeElement($user);
            $user->removeSpecialtyId($this);
        }

        return $this;
    }
}

When I try to save the registration form, I got this exception:

**> Could not determine access type for property "specialtyId" in class

"App\Entity\Users": The property "specialtyId" in class "App\Entity\Users" can be defined with the methods "addSpecialtyId()", "removeSpecialtyId()" but the new value must be an array or an instance of \Traversable, "App\Entity\Specialties" given.**

A new table is created named: users_specialties that contains: users_id/specialties_id

Symfony 4, conditional route redirect/override in PROD mode

$
0
0

The route of FosUserBundle '/login' must not be accessible in Production mode. It must redirect to the route '/choiceConnexion'.

I thought I had this working because in dev mode there is a redirect successfully taking place, using 'config/routes/dev/routes.yaml' in this mode. However when setting the env in prod, the redirect doesn't work.

I have tried putting similar confingurations in a config/routes/prod folder, thinking it would switch, however it doesn't work.

I assumed in Prod the first code snippet below woulc be called:

config/routes.yaml

home_choiceConnexion:
  path: /login
  controller: App\Controller\HomeController::choiceConnexion

The above doesn't work, however in dev, the rerouting taking place in config/dev/routes.yaml does work when the app is in dev mode.

fos_user_security_login:
  path: /softia/login
  controller: FOS\UserBundle\Controller\SecurityController::loginAction

The main difference is that '/login' already exists, so I think the rerouting doesn't get prioretized and doesn't override the route fos_user_security_login.

I need to achieve this redirection for a client's project and would be grateful of any help.

Symfony 5 : translate Arabic numbers to Modern numbers

$
0
0

I use Symfony 5, and I checked Arabic like the default language of the website.

but when I write a number on the database and get it, the Symfony translate it automatically to Arabic numbers ( from [1,2,3,4,5,6,7,8,9] to [١,٢,٣,٤,٥,٦,٧,٨,٩] ).

is there any solution to use modern numbers in place of Arabic numbers ?


symfony 4.4 + FOSCKEditor + helios-agElfinder not working

$
0
0

Using Symfony 4.4 + "friendsofsymfony/ckeditor-bundle": "^2.2" + "helios-ag/fm-elfinder-bundle": "dev-master" after composer install (but also tried composer require helios-ag/fm-elfinder-bundle from the docs page) gives me

Executing script cache:clear [KO]
 [KO]
Script cache:clear returned with error code 1
!!  
!!  In RegisterControllerArgumentLocatorsPass.php line 173:
!!                                                                                 
!!    Cannot determine controller argument for "FM\ElfinderBundle\Controller\ElFi  
!!    nderController::load()": the $eventDispatcher argument is type-hinted with   
!!    the non-existent class or interface: "Psr\EventDispatcher\EventDispatcherIn  
!!    terface".                                                                    
!!                                                                                 
!!  
!!  
Script @auto-scripts was called via post-install-cmd

route is imported, config files set...

BTW: include_assets is not recognized in fm_elfinder.yml (commented it out)

i have absolutly no idea. Can anyone of you guys give me a clue? Thanks.

ps. worked fine with symf. 4.1

Cannot return null for non-nullable field on API platform and graphql

$
0
0

I have an "user" entity with an unmapped property like this :

namespace App\Entity\User;

// ...

/**
 * @var string
 * @Groups({"readAnnounce", "readUser"})
 */
private $lastUrlImageProfilValid;


/**
 * @return string
 */
public function getLastUrlImageProfilValid()
{
    foreach ($this->imageProfil as $image){
        if ($image->getIsValid()){
            return $image->getUrl();
        }
    }

    return null;
}

when i call this entity with REST, it work but not with graphql, it return this error:

Cannot return null for non-nullable field User.lastUrlImageProfilValid

Graphql code :

{
  users(
    first: 30,
  ) {
    edges {
      node {
        lastUrlImageProfilValid
      }
    }
  }
}

How can i set an unmapped property nullable ?

TypeTestCase with EntityType and ServiceEntityRepository

$
0
0

I'm using EntityRepositories as a service in my application. All works fine, but when testing my forms with a TypeTestCase, an EntityManager can't be created for EntityType form fields because an EntityManager is being injected instead of a Manager.

Here is my code, partly based on this answer:

<?php

use App\Entity\Bar;
use App\Entity\Foo;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\EntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Test\TypeTestCase;

class FooType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)  // phpcs:ignore
    {
        $builder->add(
            'bar',
            EntityType::class,
            [
                'class' => Bar::class,
                'query_builder' => static function (EntityRepository $er) {
                    return $er->createQueryBuilder('bar');
                },
            ]
        );
    }
}
final class BarRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Bar::class);
    }
}

class FooTypeTest extends TypeTestCase
{
    protected function setUp() : void
    {
        $this->entityManager   = DoctrineTestHelper::createTestEntityManager();

        // ...

        parent::setUp();
    }
    public function testSubmitValidData()
    {
        $foo = new Foo();
        $form = $this->factory->create(FooType::class, $foo);
    }
}

When running this test, I get this error message:

TypeError : Argument 1 passed to BarRepository::__construct() must implement interface Doctrine\Persistence\ManagerRegistry, instance of Doctrine\ORM\EntityManager given, called in vendor/doctrine/orm/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php on line 69

I'm using Symfony 4.4.2, doctrine/doctrine-bundle 1.12.6, doctrine/orm v2.7.0, symfony/phpunit-bridge v5.0.2 and phpunit/phpunit 8.5.2.

Any idea how I can use a TypeTestCase while using a ServiceEntityRepository?

How to expose a property which depends on a serialization group from API-Platform to react-admin?

$
0
0

I use Changing the Serialization Context Dynamically in my application to apply the admin:write group when the user is an admin. So that an user on the admin will be able to update this property.

The context builder has this configuration:

<?php

namespace App\Serializer;

use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

final class AdminContextBuilder implements SerializerContextBuilderInterface
{
    private $decorated;
    private $authorizationChecker;

    public function __construct(SerializerContextBuilderInterface $decorated, AuthorizationCheckerInterface $authorizationChecker)
    {
        $this->decorated = $decorated;
        $this->authorizationChecker = $authorizationChecker;
    }

    public function createFromRequest(Request $request, bool $normalization, ?array $extractedAttributes = null): array
    {
        $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);

        if (isset($context['groups']) && $this->authorizationChecker->isGranted('ROLE_ADMIN') && false === $normalization) {
            $context['groups'][] = 'admin:write';
        }
        if (isset($context['groups']) && $this->authorizationChecker->isGranted('ROLE_ADMIN') && true === $normalization) {
            $context['groups'][] = 'admin:read';
        }

        return $context;
    }
}

I want to show this property to the admin:

abstract class User implements UserInterface
{
   /**
     * @ORM\Column(name="account_status", type="string", length=8)
     * @Groups({"read", "admin:write"})
     */
    protected $accountStatus;
}

The data is returned successfully and I can see the string on table view or item view in the admin.

But the documentation generated by API-Platform on …/api/docs.jsonld does not expose this property: the property is not writable:

{
    "@type": "hydra:SupportedProperty",
    "hydra:property": {
        "@id": "#User/accountStatus",
        "@type": "rdf:Property",
        "rdfs:label": "accountStatus",
        "domain": "#User",
        "range": "xmls:string"
    },
    "hydra:title": "accountStatus",
    "hydra:required": false,
    "hydra:readable": true,
    "hydra:writable": false
},

I think that it prevents showing the field in the administration.

How can I add this property to the documentation and ultimately to react-admin?

I tried any configuration I could think of:

abstract class User implements UserInterface
{
    /**
     * @ORM\Column(name="account_status", type="string", length=8)
     * @Groups({"read", "admin:write"})
     * @ApiProperty(writable=true)
     */
    protected $accountStatus;
}

Symfony 4 Slack Client Injection

$
0
0

I'm trying to setup a php slack client into my symfony 4 project but I can't understand how autowiring works.

This is the library I'm trying to setup : https://github.com/nexylan/slack-bundle.

Used the following documentation:

Argument 1 passed to Nexy\Slack\Client::__construct() must be an instance of Psr\Http\Client\ClientInterface, instance of Http\Client\Common\HttpMethodsClient given, called in .../symfony-project/var/cache/dev/ContainerGSurbkS/getNexySlack_ClientService.php on line 12

I have installed theses composer packages :

"nexylan/slack-bundle": "^2.0",
"nyholm/psr7": "^1.2",
"php-http/guzzle6-adapter": "1.1.1",

This is because I'm trying to upgrade from php 7.3.14 to php 7.4.0 but there is a lot of error with dependency that I have already fixed.

Config File :

nexy_slack:

    # If you want to use an another httplug client service.
    http:
        client: httplug.client

    # The Slack API Incoming WebHooks URL.
    endpoint:             'https://hooks.slack.com/services/thesesAreFakeIds/FGVP0LTYH/jSDvjo59uyqqVxL7Lv2gl0cf'
    channel:              null
    username:             null
    icon:                 null
    link_names:           false
    unfurl_links:         false
    unfurl_media:         true
    allow_markdown:       true
    markdown_in_attachments: []

Bundles

return [
    Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
    Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
    Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle::class => ['all' => true],
    Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true],
    Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true],
    Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle::class => ['all' => true],
    Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
    Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle::class => ['all' => true],
    Symfony\Bundle\WebServerBundle\WebServerBundle::class => ['dev' => true],
    Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true, 'test' => true],
    Symfony\Bundle\DebugBundle\DebugBundle::class => ['dev' => true, 'test' => true],
    Symfony\Bundle\MakerBundle\MakerBundle::class => ['dev' => true],
    Fresh\DoctrineEnumBundle\FreshDoctrineEnumBundle::class => ['all' => true],
    Ornicar\GravatarBundle\OrnicarGravatarBundle::class => ['all' => true],
    KnpU\OAuth2ClientBundle\KnpUOAuth2ClientBundle::class => ['all' => true],
    Http\HttplugBundle\HttplugBundle::class => ['all' => true],
    Nexy\SlackBundle\NexySlackBundle::class => ['all' => true],
    Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['dev' => true, 'test' => true, 'prod' => true],
];

Symfony 4: Is actual SSO between multiple TLDs possible? [duplicate]

$
0
0

This question already has an answer here:

So I am trying to figure out whether I can create true SSO between the applications of my client. The applications are reachable through actual TLDs so not subdomains like app1.companyurl.com, app2.companyurl.com. There is a central identity server working with OAuth2. All works if I log in every application on it's own, requiring the visitor to log in at every site separately. But now I want the visitors to be able to log in at companyapp1.com and be immediately recognized as logged in when they visit companyapp2.com. Is that possible?

With the subdomains I easily made it work by setting the cookie domain in the config. With TLDs in my tests the browser always changes the session id for every TLD. I want to know is there a way around this or just not, period in which case I don't need to spend anymore time on this. If it is possible, do you maybe have a tip for me using Symfony 4 for all applications (including the central identity server using OAuth2)? Thank you in advance!

EDIT: I see in this thread Single Sign On across multiple domains in the answer from jason saldo that it just doesn't work with cookies. The top rated answer doesn't satisfy my condition of cross-tld. Is there any way to do this other than with cookies?

EDIT2: Ok, it has been pointed out to me that the highest rated answer in that thread can indeed solve the problem, it is just not written in a tld-scenario. I will try this with my applications.

Symfony - set expiration time automatically

$
0
0

I am setting new entity in my form and I have field 'created' which I want to use to set expiration time automatically. I want for expired field to be set on true 30 minutes after entity is set.

I have some logic created but I think it won't work.

My part of the code:

 $dateNow = new \DateTime();
    $entity->setCreated($dateNow)->modify("+33 Minutes");
    if($dateNow >= $entity){
        $entity->setExpired(true);
        $this->em->persist($entity);
        $this->em->flush();
    }

if($entity->isExpired()) {
        throw new /Exception('Sorry,it is expired.');
    }

Do you have any idea how to do this when using setter in Doctrine? Thanks


Symfony 4 undefined property error when using serializer

$
0
0

While making an ajax call back to a controller to get comments from a database I'm getting the following error:

Notice: Undefined property: App\Entity\ExceptionReport::$typeID

Comments are related to users which has a relation to exception report so I'm guessing that relationship is what is throwing the error. I wasn't sure if setting max depth was what I needed to implement, so I tried setting max depth on the users field in the comments class but got the same error.

public function getComments(CommentRepository $commentRepository, SerializerInterface $serializer) {

        $comments = $commentRepository->findAll();
        $encoder = new JsonEncoder();

        $defaultContext = [
            AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER =>function($object) {
                return $object->getUsername();
            }
        ];
        $normalizer = new ObjectNormalizer(null, null, null, null, null,
            null, $defaultContext);
        $serializer = new Serializer([$normalizer], [$encoder]);

        return $serializer->serialize($comments, 'json');
    }

Serializing and Deserializing UUIDs objects in Symfony

$
0
0

I'm trying to serialize objects to JSON then deserialize them. I'm using ramsey/uuid for all the id.

/**
 * NotificationService constructor.
 */
public function __construct(ObjectManager $manager, EntityManagerInterface $entityManager, SerializerInterface $serializer)
{
    $this->manager = $manager;
    $this->entityManager = $entityManager;
    $this->pollRepository = $this->entityManager->getRepository(Poll::class);
    $this->threadRepository = $this->entityManager->getRepository(ForumThread::class);
    $this->notificationRepository = $this->entityManager->getRepository(Notification::class);
    $this->serializer = $serializer;
}

/**
 * @param $objectToSerialize
 *
 * @return string
 */
public function jsonEncode($objectToSerialize)
{
    // Serialize my object in Json
    return $this->serializer->serialize($objectToSerialize, 'json', [
        'circular_reference_handler' => function ($object) {
            return $object->getId();
        },
    ]);
}

/**
 * @param $json
 * @param $class
 *
 * @return mixed
 */
public function jsonDecode($json, $class)
{
    return $this->serializer->deserialize($json, $class, 'json');
}

My function jsonEncode works fine. But the second one jsonDecode shows me this error:

Symfony\Component\Serializer\Exception\NotNormalizableValueException

The type of the "id" attribute for class "App\Entity\Poll" must be one of "Ramsey\Uuid\UuidInterface" ("string" given).

Thanks for the help

API Platform GraphQL security

$
0
0

So I'm using API platform in my Symfony 4 project, and I've read that it supports graphQl, so I set up an access control in security.yml to allow users to access graphQl API:

- { path: ^/api/graphql, roles: IS_AUTHENTICATED_ANONYMOUSLY }

And in each entity I have access controls for itemOperations and collectinOperations. Example:

 * @ApiResource(
 *     itemOperations={
 *         "get"={
 *             "access_control"="is_granted('ROLE_ADMIN')"
 *         }
 *     },
 *     collectionOperations={
 *         "get"={
 *             "access_control"="is_granted('ROLE_ADMIN')"
 *         }
 *     }
 * )

But issue is, any user can access this entity through graphQL, because graphQL ignores the access controls for these operations. Is there a way to force graphQL to follow these rules?

Decorate all services that implement the same interface by default?

$
0
0

I have a growing number of service classes that share a common interface (let's say BarService and BazService, that implement FooInterface).

All of these need to be decorated with the same decorator. Reading the docs, I know that I can do:

services:
  App\BarDecorator:
    # overrides the App\BarService service
    decorates: App\BarService

Since I have to use the same decorator for different services I guess I would need to do:

services:
 bar_service_decorator:
    class: App\BarDecorator
    # overrides the App\BarService service
    decorates: App\BarService

 baz_service_decorator:
    class: App\BarDecorator
    # overrides the App\BazService service
    decorates: App\BazService

Problem is: this gets repetitive, quickly. And every time a new implementation of FooInterface is created, another set needs to be added to the configuration.

How can I declare that I want to decorate all services that implement FooInterface automatically, without having to declare each one individually?

Symfony 4, Login, how debug the error 'Invalid credentials'?

$
0
0

From symfony 4, I would like create a simple authentication form. I created a User class (the identifier is the email field, not the 'Username', I created a class controller and configured the security.yml file.

I created some users with this static method : (for tests, password by default is 'test')

class User implements \Serializable, UserInterface
{
// ...
  public static function new_alea($email, $isActive = false, $password="test"){
    $instance = new self();
    $instance->isActive = $isActive;
    $instance->email = $email;

    $brypt = new BCryptPasswordEncoder(4);
    $instance->password = $brypt->encodePassword($password, null);

    return $instance;
  }
// ...
}

Its work, there are some user in my database with encrypted passwords.

But when I go to the form page and try to login (fill email/password fields and click on the submit button), I get the error "Invalid credentials."

enter image description here

What this error means ? How/where do I debug my code for find why this error occurs ?

Below, mains part of my code, maybe you'll see an error I didn't see :

the security.yaml file :

security:
    encoders:
        App\Entity\User:
            algorithm: bcrypt
    providers:
        my_db_provider:
            entity:
                class: App\Entity\User
                property: email
    firewalls:
        main:
            provider: my_db_provider
            anonymous: ~
            form_login:
                login_path: login
                check_path: login
    role_hierarchy:
        # ...

the User Entity Class :

class User implements \Serializable, UserInterface
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

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

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

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

    private $plainPassword;

    public static function new_alea($email, $isActive = false, $password="coucou"){
        $instance = new self();
        $instance->isActive = $isActive;
        $instance->email = $email;

        $brypt = new BCryptPasswordEncoder(4);
        $instance->password = $brypt->encodePassword($password, null);

        return $instance;
    }

    public function eraseCredentials() {
        $this->plainPassword = null;
    }

    public function serialize() {
        return serialize(array(
            $this->id,
            $this->email,
            $this->password,
        ));
    }

    public function unserialize($serialized) {
        list (
            $this->id,
            $this->email,
            $this->password,
            ) = unserialize($serialized);
    }

    public function getRoles() {
        return array('ROLE_ADMIN');
    }

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

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

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

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

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

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

    // and others getters/setters

the login Controller :

class LoginController extends Controller
{
    /**
     * @Route("/login", name="login")
     */
    public function login(Request $request, AuthenticationUtils $authUtils)
    {
        // get the login error if there is one
        $error = $authUtils->getLastAuthenticationError();

        // last username entered by the user
        $email = $authUtils->getLastUsername();

        return $this->render('frontend/log/login.html.twig', array(
            'email' => $email,
            'error' => $error,
        ));
    }
}

And the template login.html.twig file :

{% extends 'base.html.twig' %}

{% block body %}

    {% if error %}
        <div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
    {% endif %}

    <form action="{{ path('login') }}" method="post">
        <label for="email">Email:</label>
        <input type="text" id="email" name="_email" value="{{ email }}" />

        <label for="password">Password:</label>
        <input type="password" id="password" name="_password" />

        {#
            If you want to control the URL the user
            is redirected to on success (more details below)
            <input type="hidden" name="_target_path" value="/account" />
        #}

        <button type="submit">login</button>
    </form>

{% endblock body %}
Viewing all 3924 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>