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

Visual Studio Code PHP Intelephense get errors wich aren't

$
0
0

I'm working on a Symfony 4 project using Visual Studio Code with Intelephense.

Intelephense gets errors which aren't. There are some examples :

Undefined method 'uasort'.

This error corrsponding to this code :

            // Collection creation of seasons used in the periods 
        $seasons = new ArrayCollection();
        $sortedSeasons = new ArrayCollection();

        //Search seasons used by periods
        foreach ($advert->getPeriods() as $period) 
        {

            $season = $period->getSeason();

            if (! $seasons->contains($season)) 
            {

                $seasons->add($season);

            }

        }

        // Sort seasons by ascending cost 
        $iterator = $seasons->getIterator();

        $iterator->uasort(function ($a, $b) {

            return $a->getCost() <=> $b->getCost();

        });

An other example :

Undefined method 'getAdvertMinPrice'.

$minPrices = $this->getDoctrine()->getRepository(Price::class)->getAdvertMinPrice($advert);

However, the method exists in the PriceRepository :

<?php

namespace App\Repository\advert;

use App\Entity\advert\Price;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;

/**
 * @method Price|null find($id, $lockMode = null, $lockVersion = null)
 * @method Price|null findOneBy(array $criteria, array $orderBy = null)
 * @method Price[]    findAll()
 * @method Price[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class PriceRepository extends ServiceEntityRepository
{

    public function __construct(RegistryInterface $registry)
    {

        parent::__construct($registry, Price::class);

    }

   /**
     * Get the minimum price from an advert
     *
     * @param [type] $advert
     * @return Price[]
     */ 
    public function getAdvertMinPrice($advert): array
    {
        return $this->createQueryBuilder('p')
            ->andWhere('p.price = (
                                    SELECT MIN(p2.price)
                                    FROM ' . $this->_entityName . ' p2
                                    WHERE p2.advert = :val
                                  )'
                      )
            ->setParameter('val', $advert)
            ->getQuery()
            ->getResult()
        ;

    }

}

There is the Price name space :

<?php

namespace App\Entity\advert;

use App\Entity\advert\Advert;
use App\Entity\advert\Period;
use App\Entity\backend\Season;
use App\Entity\backend\Duration;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity(repositoryClass="App\Repository\advert\PriceRepository")
 * 
 * @UniqueEntity(
 *     fields={"duration", "season"},
 *     message="A price already exists for this season and this duration."
 * )
 */
class Price
{

And the use command in the file where I have the problem :

<?php

namespace App\Controller\advert;

use App\Entity\backend\VAT;
use App\Entity\advert\Price;

I don't understand where is the problem. I have searched for days without result.

Somebody would have an idea about this problem origin?

Thank you by advance for your help.


Symfony 4 login form with Guard not displaying error messages

$
0
0

I have tried implementing a simple login form with both Symfony Guard and Symfony Authentication provider but despite everything I tried, both variables $last_email and $error are always empty.

I have followed this step by step: https://symfony.com/doc/4.3/security/form_login_setup.html and all of my LoginFormAuthenticator.php is identical. So is my controller and login.html.twig

I'm putting bellow my controller for the sake of putting some code from the SecurityController.php:

public function login(AuthenticationUtils $authenticationUtils, Request $request, AuthorizationCheckerInterface $authChecker): Response
    {
        if ( ( $this->getUser() || $request->cookies->has('REMEMBERME') ) && $authChecker->isGranted('ROLE_USER'))
            return $this->redirect($this->generateUrl('logged_in'));

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();

        // last username entered by the user
        $last_email = $authenticationUtils->getLastUsername();

        return $this->render('security/login.html.twig', [
            'last_email' => $last_email,
            'error'      => $error,
        ]);
    }

And me security.yaml looks like this:

providers:
    in_memory: { memory: ~ }
    our_db_provider:
        entity:
            class: App\Entity\User
            property: email
firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        pattern:    ^/
        http_basic: ~
        provider: our_db_provider
        anonymous: ~
        remember_me:
            secret:   '%kernel.secret%'
            lifetime: 604800 # 1 week in seconds
            path:     /
            name:     REMEMBERME
            remember_me_parameter: _remember_me
        logout:
            path:  /logout
            target: /
        guard:
            authenticators:
                - App\Security\LoginFormAuthenticator

So the login form WORKS - I can log in and log out. But if my email doesn't exist or if my credentials are invalid, no error message get displayed. Doing a var_dump on $error and $last_email returns NULL and empty string, always. Also, I tried to var dump $this->passwordEncoder->isPasswordValid($user, $credentials['password']); from my LoginFormAuthenticator in the checkCredentials method and if my credentials are invalid, i can see it returns false. So that works. But somehow, something seems broken in the background.

Any help is much appreciated. I'm using Symfony 4.4

EDIT: Adding login.html.twig

<form action="{{ path('login') }}" class="form-validate" method="post" id="login">
    <div class="panel panel-body login-form">

        {% if error %}
            <small class="display-block text-danger">
                {{ error.messageKey|trans(error.messageData, 'security') }}
            </small>
        {% endif %}

        <div class="form-group has-feedback has-feedback-left">
            <input type="text" {#class="form-control"#} placeholder="Email" id="email" name="email" value="{{ last_email }}" required autofocus>
        </div>

        <div class="form-group has-feedback has-feedback-left">
            <input type="password" {#class="form-control"#} placeholder="Password" id="password" name="password" required="required">
        </div>

        <div class="form-group login-options">
            <div class="row">
                <div class="col-sm-6">
                    <label class="checkbox-inline">
                        <input type="checkbox" name="_remember_me" class="styled" checked="checked">
                        Remember me
                    </label>
                </div>
            </div>
        </div>

        <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">

        <div class="form-group">
            <button type="submit" class="btn btn-block new-btn new-blue">Login <i class="icon-arrow-right14 position-right"></i></button>
        </div>
    </div>
</form>

Thanks

Symfony 4 + KnpSnappyBundle. Generate PDF from Twig

$
0
0

I want to generate a pdf (project card) out of a twig template. I used the code from github but I still get the error. Has anyone had a similar problem and managed it?

"Service "knp_snappy.pdf" not found: even though it exists in the app's container, the container inside "App\Controller\ProjectController" is a smaller service locator that only knows about the "doctrine", "form.factory", "http_kernel", "parameter_bag", "request_stack", "router", "security.authorization_checker", "security.csrf.token_manager", "security.token_storage", "session" and "twig" services. Try using dependency injection instead.".

    public function pdfAction()
{
    $html = $this->renderView('MyBundle:Foo:bar.html.twig', array(
        'some'  => $vars
    ));

    return new PdfResponse(
        $this->get('knp_snappy.pdf')->getOutputFromHtml($html),
        'file.pdf'
    );
}

Sylius liip imagine: Unable to open image

$
0
0

I'm working on a Sylius 1.5 project, everything is working fine on my local environment however when deploying to my dev environment I'm getting an error on filtered images (using liip imagine filters).

The environment consists of a docker php-apache container running sylius. The host machine proxies requests to the docker container.

This is the error I get when I try to load the image's url in my browser:

Unable to create image for path "b4/11/650996cb08ee2b5fef5dfc75b8b4.jpeg" and filter "sylius_shop_product_thumbnail". Message was "Unable to open image /var/www/html/public/media/image/b4/11/650996cb08ee2b5fef5dfc75b8b4.jpeg"

The error occurs here: in vendor/imagine/imagine/lib/Imagine/Gd/Imagine.php (line 96)

Observations:

  • Image path is good
  • Image exists on file system
  • PHP manages to read the data from the file with file_get_contents
  • imagecreatefromstring doesn't manage to create resource from data

Here is the code where the error occurs:

    public function open($path)
    {
        $path = $this->checkPath($path);
        $data = @file_get_contents($path);

        if (false === $data) {
            throw new RuntimeException(sprintf('Failed to open file %s', $path));
        }

        $resource = @imagecreatefromstring($data);

        if (!is_resource($resource)) {
            throw new RuntimeException(sprintf('Unable to open image %s', $path));
        }

        return $this->wrap($resource, new RGB(), $this->getMetadataReader()->readFile($path));
    }

I've tried dumping the variables, and it seems imagine succeeds in getting the data from the file with file_get_contents, however imagecreatefromstring fails.

Here is the apache configuration:

NameVirtualHost 127.0.0.1:8000

Listen 127.0.0.1:8000
LimitRequestBody 10485760

<VirtualHost 127.0.0.1:8000>
  ProxyPreserveHost On
  DocumentRoot "/var/www/html"
  DirectoryIndex index.php
  <Directory "/var/www/html">
    AllowOverride All
    Allow from All
  </Directory>
</VirtualHost>

Nginx configuration:

server {
        listen 80;
        client_max_body_size 10M;
        server_name mydomain.com;

        location / {
                proxy_pass http://127.0.0.1:8092;
                include /etc/nginx/proxy_params;
        }

}

I'm having trouble figuring out what in the configuration is making this go wrong.

Raw query with IN and multiple where condition?

$
0
0

I need to write a query with a IN condition and multiple WHERE condition. I have tried following SQL statement but this one is not getting me result. Maybe I did something wrong.

SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters

$columns = "DISTINCT model, manufacturer, logo, year, update_status";

$modelList = array('Version', 'Facelift', 'Optionsänderung');


$orderBy = "manufacturer, model";

// Prepare the sql statement.
$sql = "select $columns from tbl_manufacture where model IN (:modelList)  year > ? AND update_status = ?";
$sql.="order by $orderBy";

$em = $this->getEntityManager();
$query = $em->getConnection()
            ->prepare($sql);
$query->bindValue("modelList", $modelList, Connection::PARAM_STR_ARRAY);

$params = array(
    "year" => $year,
    "update_status" => $status
);

// Execute the statement
$query->execute($params);

AdminLTE seem not to be there in my easyadmin Symfony project

$
0
0

I have a symfony 4.4 project where I installed easyadmin. I saw that AdminLTE is part os easyadmin and can be used to make beautiful dashboard. I followed this tutorial : https://afsy.fr/avent/2017/01-easyadminbundle-l-arriere-guichet-easy-peasy

I tried to create a beautiful dashboard but when I open the page it's not nice at all. When I look at my admin webpage, I can't see any adminlte css in the source code. And inside my project, I don't kow where AdminLTE is located. It seems it's not there.

Is there something I should do to get it ? Maybe a special command ? I think if I remember ok that I installed easyadmin doing a simple :

 composer require admin

What else should I do to have AdminLTE template and be able to use it ?

Thanks for your help.

Including assets in sonata-project/block-bundle 4.0

$
0
0

Symfony sonata block bundle has twig function "sonata_block_include_stylesheets", which must register all blocks assets. But in version 4, i did not find how it can be do.
In 3.* version, in services classes exist methods as "getJavascripts" and "getStylesheets".
I tried simple write <link rel="stylesheet" media="all" href="{{ asset('some.css') }}"> on template, in hope that it will automatically include this script. But they only render this link in block html, but i want to group css links on top of the page.
Any ideas, how this make ?

GraphQl - how to add current user to mutation object

$
0
0

I am attempting to add the current user to a create mutation by decorating graphql stages as per the documentation.

It is a feature to allow users to block other users in a message system, fyi.

It should satisfy the following access control:

"access_control"="is_granted('IS_AUTHENTICATED_FULLY') and object.getBlocker() == user"

Meaning that the user that is blocking is the currently authenticated user.

I can get it done if I modify the above to just:

"access_control"="is_granted('IS_AUTHENTICATED_FULLY')" by decorating the deserialize stage like so:

App/Stage/DeserializeStage

/**
 * @param object|null $objectToPopulate
 *
 * @return object|null
 */
public function __invoke($objectToPopulate, string $resourceClass, string $operationName, array $context)
{
    // Call the decorated serialized stage (this syntax calls the __invoke method).
    $deserializeObject = ($this->deserializeStage)($objectToPopulate, $resourceClass, $operationName, $context);

    if ($resourceClass === 'App\Entity\BlockedUser'&& $operationName === 'create') {
        $user = $this->tokenStorage->getToken()->getUser();
        $deserializeObject->setBlocker($user);
    }

    return $deserializeObject;
}

As I understand it, in order to get it to work fully satisfying the access control, I would need to decorate the read stage, which comes before the security stage and insert the currently authenticated user to the object.

In that way, it would satisfy the second portion of the access control, ie, and object.getBlocker() == user

I attempted to do it as follows, but I get a NULL object :

App/Stage/ReadStage

/**
 * @return object|iterable|null
 */
public function __invoke(?string $resourceClass, ?string $rootClass, string $operationName, array $context)
{
    $readObject = ($this->readStage)($resourceClass, $rootClass, $operationName, $context);

    var_dump($readObject->getBlocked()->getUsername()); // throws error 'method getBlocked on NULL

    if ($resourceClass === 'App\Entity\BlockedUser'&& $operationName === 'create') {
        $userId = $this->tokenStorage->getToken()->getUser();
        $readObject->setBlocker($user);
    }

    return $readObject;
}

Generate entity from an existing table

$
0
0

I have a already created table:

CREATE TABLE `jt_version` (
    `version` int(11) NOT NULL COMMENT '103',
    `model` varchar(4) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '108'

From this table, I have generated an entity.

 php bin/console doctrine:mapping:import "App\Entity" annotation --path=src/Entity

This entity generated creates something like this:

/**
 * @var int
 *
 * @ORM\Column(name="version", type="integer", nullable=false, options={"comment"="103"})
 */
private $version;

/**
 * @var string
 *
 * @ORM\Column(name="model", type="string", length=4, nullable=false, options={"default"="''","comment"="108"})
 */
private $model= '\'\'';

My question is from where the value of model is getting set. In above case the $model value is '\'\''

Is that correct or I need to make some change?

Symfony 4, get .env parameter from a controller, is it possible and how?

$
0
0

From symfony 4, I want create a global parameter and get the value of this parameter from a controller.

This parameter is the path of an another app in the server. So, I thinked add the paramerter in the .env file. But how can I get the value of this parameter from a controller?

Message error from Symfony4 when asking for actor_show with a function generate with a slug

$
0
0

I need some help cause I can't succeed to resolve this error message by myself even after research on the web:

An exception has been thrown during the rendering of a template ("Parameter "slug" for route "actor_show" must match "[^/]++" ("" given) to generate a corresponding URL.").

I suppose that it's because my regex is not well defined but I have no more idea to do it well...

Here is the demand for the function generate(): All special characters are processed: - à, ç, etc. become a, c, etc; !, apostrophes and other punctuation is deleted; - Spaces at the beginning and end of strings are removed; - There are not several - successive; - The generated string is in lowercase

This is my function generate()

class Slugify
{
    public function generate(string $slug) : string
    {
        // lowercase
        $slug = strtolower($slug);
        // transliterate
        $slug = iconv('utf-8', 'us-ascii//TRANSLIT', $slug);
        // remove duplicate -
        $slug = preg_replace('~-+~', '-', $slug);
        // remove spaces
        $slug = preg_replace('^\s+|\s+$', '', $slug);
        // remove punctuation
        $slug = preg_replace('/[^a-z0-9-]/', '', $slug);
        return $slug;
    }
}

This is a part of my twig template:

       {% for actor in actors %}
            <tr>
                <td>{{ actor.name }}</td>
                <td>
                    <a href="{{ path('actor_show', {'slug': actor.slug}) }}">Accéder</a>
                    <a href="{{ path('actor_edit', {'slug': actor.slug}) }}">Modifier</a>
                    <a href="{{ path('actor_delete', {'slug': actor.slug}) }}">Supprimer</a>
                </td>
            </tr>
        {% else %}
            <tr>
                <td colspan="4">Aucun acteur trouvé</td>
            </tr>
        {% endfor %}
        </tbody>
    </table>

    <a href="{{ path('actor_new') }}">Créer un nouveau</a>
{% endblock %}

Thanks for the help and Merry Christmas !!

How can I override a twig extension defined in a symfony4 bundle?

$
0
0

I have to override a method defined in a class extending Twig\Extension\AbstractExtension which is defined within a bundle.

My idea is to create a new class extending the original one but I don't know:

  1. Where should my code be placed (Somewhere inside /src I gues but other than that...)
  2. How can I configure everything for my class to be used instead of the original one (I guess there's some yaml file for this but I don't know which one or what to put inside of it).

    Thanks!

Symfony 4, PHPUnit - authorize user for unit test

$
0
0

I'm writing test to do the unit testing of controller. I want to check if I get the proper content for the url, which requires user to be logged in.

I have following test written

class AdminControllerTest extends WebTestCase
{
    private $client = null;

    public function setUp()
    {
        $this->client = static::createClient();
    }

    public function testAdminHome(): void
    {
        $this->logIn();
        $crawler = $this->client->request('GET', '/admin/');

        $this->assertSame(Response::HTTP_OK, $this->client->getResponse()->getStatusCode());
        $this->assertGreaterThan(0, $crawler->filter('html:contains("Welcome to Admin Panel")')->count());
    }

    private function logIn()
    {
        $user = new User();
        $user->setId(1);
        $user->setEmail('test@admin.com');
        $user->setFullName('Admin User');
        $user->setEnabled(true);

        $session = $this->client->getContainer()->get('session');

        $firewallName = 'main';
        $firewallContext = 'main';

        $token = new UsernamePasswordToken($user, null, $firewallName, ['ROLE_ADMIN']);
        $session->set('_security_'.$firewallContext, serialize($token));
        $session->save();

        $cookie = new Cookie($session->getName(), $session->getId());
        $this->client->getCookieJar()->set($cookie);
    }
}

Configuration in my security.yml

security:
    encoders:
        App\Entity\User: auto

    providers:
        database_users:
            entity:
                class: App\Entity\User
                property: username
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: true
            pattern: ^/
            context: main

            form_login:
                check_path: security_login
                login_path: security_login
                csrf_token_generator: security.csrf.token_manager
                default_target_path: admin_home

            logout:
                path: security_logout
                target: security_login

    access_control:
         - { path: ^/admin, roles: [ROLE_ADMIN, ROLE_EDITOR] }
    role_hierarchy:
        ROLE_ADMIN: ROLE_EDITOR
        ROLE_EDITOR: ROLE_USER

However assertion for the Response code returns me 200, but I land on login page instead of admin home. Also there is not required content, as I'm on login page not an admin home.

Could you please check the code and help me find out the issue?

Kayue\WordpressBundle with SYmfony 4.4.1: The class XXX was not found in the chain configured namespaces App\Entity

$
0
0

I'm trying to work with kayue/KayueWordpressBundle installed with composer as composer require kayue/kayue-wordpress-bundle in my Symfony 4.4.1 project but I'm unable to.

This is what I'm trying to do:

<?php

namespace App\Service\WordPress;

use Doctrine\ORM\EntityManagerInterface;
use Kayue\WordpressBundle\Entity\Post;

class PostCollection
{
    protected $postRepository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->postRepository = $entityManager->getRepository(Post::class);
    }
}

The error I get:

The class 'Kayue\WordpressBundle\Entity\Post' was not found in the chain configured namespaces App\Entity

At first I blamed my dual-database configuration (Symfony is on a different DB from Wordpress) but then I put the DBs together and the issue persists:

doctrine:
    dbal:
        url: '%env(resolve:DATABASE_URL)%'

        # Only needed for MySQL (ignored otherwise)
        charset: utf8mb4
        default_table_options:
            collate: utf8mb4_unicode_ci
    orm:
        auto_generate_proxy_classes: true
        naming_strategy: doctrine.orm.naming_strategy.underscore
        auto_mapping: true
        mappings:
            App:
                is_bundle: false
                type: annotation
                dir: '%kernel.project_dir%/src/Entity'
                prefix: 'App\Entity'
                alias: App

I've been fiddling for the past 2hrs, but now I'm fresh out of ideas. I wonder if ANYONE actually got this to work with Symfony 4.

Thanks!

When wrong url is entered, exception error encountered

$
0
0

I created a new Symfony project trying to work on following.

friendsofsymfony/rest-bundle

Now, at the fos_rest.yml file I added following line of code.

fos_rest:
  format_listener:
    rules:
      - { path: '^/', priorities: ['json'], fallback_format: json }
  view:
    view_response_listener: 'force'
    formats:
      json: true
  exception:
    enabled: true

Now if I try to enter the wrong URL then I am getting following error:

Argument 1 passed to FOS\RestBundle\Controller\ExceptionController::getStatusCode() must be an instance of Exception, instance of Symfony\Component\ErrorHandler\Exception\FlattenException given, called in C:\xampp\htdocs\symfony_rest\vendor\friendsofsymfony\rest-bundle\Controller\ExceptionController.php on line 68

Can anybody help me sort this problem.

Thank You.


Store International Phone Numbers Best Practice [closed]

$
0
0

My Question: How to store international phone numbers in a good way with Symfony/MariaDB ?

Note : I'm not asking about columns types

I've done some research :

Approach 1: store the phone number with the code (same column) :

  • I must also store the country code to be able to identify the phone code (Using Country Table).

    Example UK (+44) :

    Country Code :UK

    International phone :441296999999

Approach 2: store the phone number and phone code separately :

  • FK column which points to the country object (determines the country code, phone code, country name,mask..).

    Same Example :

    International phone :1296999999

    Code points to country : 1

    Table Country :

    |---|id|----|country_code|----|phone_code|----|country_name|----|
    |---|1|-----|UK|--------------|+44|-----------|United Kingdom|--|
    

Symfony routing resource and Bundle name

$
0
0

I an trying to include a file into the Symfony 4 routes, and can't figure out what would be the correct way to put in the Bundle name. My routes.yml:

icatcher_builder:
    # loads routes from the given routing file stored in some bundle
    resource: '@ICatcher/Builder/Resources/config/routes.yaml'

My bundles.php:

App\ICatcher\Builder\Builder::class => ['dev' => true, 'test' => true],

And I get this error:

An exception has been thrown during the rendering of a template ("Bundle "ICatcher" does not exist or it is not enabled. Maybe you forgot to add it in the registerBundles() method of your App\Kernel.php file? in @ICatcher/Builder/Resources/config/routes.yaml (which is being imported from "[PATH]\config/routes.yaml"). Make sure the "ICatcher/Builder/Resources/config/routes.yaml" bundle is correctly registered and loaded in the application kernel class. If the bundle is registered, make sure the bundle path "@ICatcher/Builder/Resources/config/routes.yaml" is not empty.").

If I just copy the routes into the main route.yml file instead of including an external resource - all works fine.

Symfony authentication using LDAP and entity provider

$
0
0

I am working on a small symfony website where I need LDAP authentication. Furthermore, the first time the user logs in, I need to persist a user entity in my databasae in order to link the user entity to other users.

I managed to make it work using a custom guard authentication that checks the LDAP server for verifying credentials. It also uses an LdapUserProvider to generate a User object from LDAP informations.

class LdapCustomAuthenticator extends AbstractFormLoginAuthenticator
{
    use TargetPathTrait;

    private $entityManager;
    private $urlGenerator;
    private $csrfTokenManager;
    private $ldapUserProvider;
    private $ldap;

    public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserProviderInterface $ldapUserProvider, LdapInterface $ldap)
    {
        $this->entityManager = $entityManager;
        $this->urlGenerator = $urlGenerator;
        $this->csrfTokenManager = $csrfTokenManager;
        $this->ldapUserProvider = $ldapUserProvider;
        $this->ldap = $ldap;
    }

    public function supports(Request $request)
    {
        return 'app_login' === $request->attributes->get('_route')
            && $request->isMethod('POST');
    }

    public function getCredentials(Request $request)
    {
        $credentials = [
            'username' => $request->request->get('_username'),
            'password' => $request->request->get('_password'),
            'csrf_token' => $request->request->get('_csrf_token'),
        ];
        $request->getSession()->set(
            Security::LAST_USERNAME,
            $credentials['username']
        );

        return $credentials;
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        $token = new CsrfToken('authenticate', $credentials['csrf_token']);
        if (!$this->csrfTokenManager->isTokenValid($token)) {
            throw new InvalidCsrfTokenException();
        }



        $ldapUser = $this->ldapUserProvider->loadUserByUsername($credentials['username']);

        $localDBUser = $this->entityManager->getRepository(User::class)->findByUserName($credentials['username']);

        if (! $localDBUser){
            $this->entityManager->persist($ldapUser);
            $this->entityManager->flush();
            return $ldapUser;
        }else{
            $localDBUser->setDn($ldapUser->getDn());
            return $localDBUser;
        }
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        $username = $credentials['username'];
        $password = $credentials['password'];

        if ('' === (string) $password) {
            throw new BadCredentialsException('The presented password must not be empty.');
        }

        try {
            $this->ldap->bind($user->getDn(), $password);
            return true;
        } catch (ConnectionException $e) {
            return false;
        }
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
            return new RedirectResponse($targetPath);
        }

        return new RedirectResponse($this->urlGenerator->generate('home'));
    }

    protected function getLoginUrl()
    {
        return $this->urlGenerator->generate('app_login');
    }
}

I am also customizing the LdapUserProvider but I'm skipping the details. But in my security.yaml I still use EntityUserProvider :

security:
    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: username

My problem is in these lines in the getUser method :

        $ldapUser = $this->ldapUserProvider->loadUserByUsername($credentials['username']);

        $localDBUser = $this->entityManager->getRepository(User::class)->findByUserName($credentials['username']);

        if (! $localDBUser){
            $this->entityManager->persist($ldapUser);
            $this->entityManager->flush();
            return $ldapUser;
        }else{
            $localDBUser->setDn($ldapUser->getDn());
            return $localDBUser;
        }

This method is not supposed to save anything in the database. But as I need to persist the user when he logs in the first time, I see nowhere else where this code should go.

What can you suggest to clean it up ?

Unable to find the controller for the path

$
0
0

I am trying to implement jwt to symfony project. I have been following many tutorials. But not had really worked me. I am getting Unable to find the controller for path "/login". The route is wrongly configured. error.

Below are the configuration that I have set up. Do I need to create a login function inside my controller?

security.yaml

security:
    encoders:
        App\Entity\Users:
            algorithm: bcrypt
    providers:
        app_user_provider:
            entity:
                class: App\Entity\Users
                property: email
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        login:
            pattern: ^/login
            stateless: true
            anonymous: true
            json_login:
                check_path: /login
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure
        register:
            pattern:  ^/register
            stateless: true
            anonymous: true
        api:
            pattern: ^/api
            stateless: true
            anonymous: false
            provider: app_user_provider
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator
        main:
            anonymous: true
    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api, roles: IS_AUTHENTICATED_FULLY }

routes.yaml

# Register api
register:
    path: /register
    controller: App\Controller\AuthController::register
    methods: ['POST']

api:
    path: /api
    controller: App\Controller\AuthController::api
    methods: ['POST']

login:
    path: /login
    methods: ['POST']

Return JSON token from postman

$
0
0

I am implementing JWT into Symfony 4 project.

When I try following command using curl:

curl -X POST -H "Content-Type: application/json" http://localhost:8080/login -d "
{\"email\":\"test2@mail.com\",\"password\":\"admin\"}"

It is generating the token. But When I try it using postman, I am getting Token not found error

{
    "code": 401,
    "message": "JWT Token not found"
}

In Postman, I am using following params:

URL: http://localhost:8080/login
METHOD: POST
HEADERS >> KEY: Content-Type VALUE: application/json
BODY >> x-www-form-urlencoded
email & password

Can anybody please help me how can I get token from postman?

Viewing all 3918 articles
Browse latest View live


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