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

How can I customize form fields IDs in Symfony 4?

$
0
0

I'm building a web page in Symfony that is built with multiple instances of the same form, but with different POST urls. I want to intercept the submit with javascript, and do a simple AJAX POST.

The structure of this page is this:

<h1>Title</h1>{% for document in documents %}<div id="form_{{ document.id }}">        {{ form(document.form) }}<input type="submit">Submit button</input></div>{% endfor %}<hr />

If I have 4 documents in the documents array, 4 forms will be rendered. The problem is that all the documents fields will have the same ID: there will be 4 document_csrf, 4 document_title title, and so, because all documents are views of the DocumentType form.

What I want is to add something to the generation of the form, so each form field is rendered with unique fieldnames: document_csrf1, document_title_1, document_csrf2, document_title_2, etc.

I've been looking around StackOverflow and the Symfony Documentation, but I can't find anything. I can pass an ['attr'] => ['id' => $id]] then calling the createForm function, but this ID is only used for the <form> tag, not the other fields...

Is there any way to automatically add an ID to the form, or should I render the form adding the id to each element ({{ form_widget(form.name, {'attr': {'id': 'document_name' ~ document.id}}) }})?

Thank you for your help!


Symfony: How can i use Remote procedure call (RPC) with Messenger?

$
0
0

I'm trying to do RPC with Symfony Messenger but I get stuck.Looking at the Messenger component it looks like the implementation has not been added:

https://github.com/webnet-fr/symfony/branches/allhttps://github.com/symfony/symfony/pull/34337/commits/06a5a434ce6e5349a33e81c97d83c8b4392603cd

But, I tell myself, if it hasn't been added it's because there should be a way for it to work but ... I can't find it.Could someone please confirm if it is possible to do RPC with Messenger? if you have any documentation, I am a taker and I will thank you.

TypeError DoctrineParamConverter.php (line 46)

$
0
0

i'm new to symfony framework.I've installed it by following the tutorial in the official documentation Setup.And i've created a new project with the following commande symfony new portfolio2 --full, i ran the commande symfony server:start and every think was as suspected a default page showed up with the header * Welcome to Symfony 4.4.13 .....*.I faced the problem when i was triying to create my first page by following the official documentation Create your First Page in Symfony.

I've configured the routes.yml file:

#index:#    path: /#    controller: App\Controller\DefaultController::index# config/routes.yaml# the "app_lucky_number" route name is not important yetapp_lucky_number:    path: /lucky/number    controller: App\Controller\LuckyController::number

i've added the LuckyController.php

<?php// src/Controller/LuckyController.phpnamespace App\Controller;use Symfony\Component\HttpFoundation\Response;class LuckyController{    public function number()    {        $number = random_int(0, 100);        return new Response('<html><body>Lucky number: '.$number.'</body></html>'        );    }}

but when i run the server and try to access http://localhost:8000/lucky/number, the following TypeError is shown

        Argument 1 passed toSensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DoctrineParamConverter::__construct() must be an instance of Doctrine\Common\Persistence\ManagerRegistry or null, instance of Doctrine\Bundle\DoctrineBundle\Registry given, called in F:\projects\portfolio2\var\cache\dev\ContainerEnYgzlJ\srcApp_KernelDevDebugContainer.php on line 4306

TypeError

in F:\projects\portfolio2\vendor\sensio\framework-extra-bundle\src\Request\ParamConverter\DoctrineParamConverter.php (line 46)

41 /**     42 * @var array     43 */44 private $defaultOptions;  45  46 public function __construct(ManagerRegistry $registry = null, ExpressionLanguage $expressionLanguage = null, array $options = [])    47 {        48 $this->registry = $registry;        49 $this->language = $expressionLanguage;        5051 $defaultValues = [

i did exactly what the documentation says, also i tried to clear the var\cache but it didn't work.

i'm using PHP 7.2.4, symfony 4.4 and here is my composer.json:

{"type": "project","license": "proprietary","require": {"php": ">=7.1.3","ext-ctype": "*","ext-iconv": "*","composer/package-versions-deprecated": "^1.11","doctrine/annotations": "^1.0","doctrine/doctrine-bundle": "^2.1","doctrine/doctrine-migrations-bundle": "^3.0","doctrine/orm": "^2.7","phpdocumentor/reflection-docblock": "^5.2","sensio/framework-extra-bundle": "^5.1","symfony/asset": "4.4.*","symfony/console": "4.4.*","symfony/dotenv": "4.4.*","symfony/expression-language": "4.4.*","symfony/flex": "^1.3.1","symfony/form": "4.4.*","symfony/framework-bundle": "4.4.*","symfony/http-client": "4.4.*","symfony/intl": "4.4.*","symfony/mailer": "4.4.*","symfony/monolog-bundle": "^3.1","symfony/process": "4.4.*","symfony/property-access": "4.4.*","symfony/property-info": "4.4.*","symfony/security-bundle": "4.4.*","symfony/serializer": "4.4.*","symfony/translation": "4.4.*","symfony/twig-bundle": "4.4.*","symfony/validator": "4.4.*","symfony/web-link": "4.4.*","symfony/yaml": "4.4.*","twig/extra-bundle": "^2.12|^3.0","twig/twig": "^2.12|^3.0"    },"require-dev": {"symfony/browser-kit": "^4.4","symfony/css-selector": "^4.4","symfony/debug-bundle": "^4.4","symfony/maker-bundle": "^1.0","symfony/phpunit-bridge": "^5.1","symfony/var-dumper": "^4.4"    },"config": {"preferred-install": {"*": "dist"        },"sort-packages": true    },"autoload": {"psr-4": {"App\\": "src/"        }    },"autoload-dev": {"psr-4": {"App\\Tests\\": "tests/"        }    },"replace": {"paragonie/random_compat": "2.*","symfony/polyfill-ctype": "*","symfony/polyfill-iconv": "*","symfony/polyfill-php71": "*","symfony/polyfill-php70": "*","symfony/polyfill-php56": "*"    },"scripts": {"auto-scripts": {"cache:clear": "symfony-cmd","assets:install %PUBLIC_DIR%": "symfony-cmd"        },"post-install-cmd": ["@auto-scripts"        ],"post-update-cmd": ["@auto-scripts"        ]    },"conflict": {"symfony/symfony": "*"    },"extra": {"symfony": {"allow-contrib": false,"require": "4.4.*"        }    }}

Can you help me fix this issue? (if it possible with details about what causes the problem)

And thank you in advance.

Solving Security Vulnerability https://symfony.com/cve-2020-15094

$
0
0

In order to solve the vulnerability described above, I have updated this old PHP project.

I update to Symfony 4.4.13 using the steps describe in this excellent blog

Unfortunately, I starting getting NGINX 502 errors on most of my endpoints.

Do you know how to solve this issue?

Why my captcha bot works in local but doesn't work on heroku?

$
0
0

I added a captcha bot to my registration form.

My captcha bot works perfectly fine on local (on dev and prod mode)but when I deployed the code to Heroku the /register page doesn't work anymore.I get this error :

ERROR: BotDetect requires the GD library and its support library:libpng, libjpeg and FreeType 2. You can read more aboutinstalling/enabling them at http://php.net/manual/en/book.image.php.

You can see the error here : website link

I dont think the problem is from my code, but here is it:Controlleur code :

/** * @Route("/register", name="user_register", methods={"GET","POST"}) */public function register(Request $request,UserPasswordEncoderInterface $encoder): Response{    $user = new User();    $form = $this->createForm(RegisterType::class, $user, ['validation_groups' => ['register'], ]);    $form->handleRequest($request);    if ($form->isSubmitted() && $form->isValid()) {        $hash = $encoder->encodePassword($user,$user->getPassword());        $user->setPassword($hash);        $this->addFlash('success', 'You succesfully registered, Now Login!');        $entityManager = $this->getDoctrine()->getManager();        $entityManager->persist($user);        $entityManager->flush();        return $this->redirectToRoute('user_login');}    return $this->render('authentication/register.html.twig', ['user' => $user,'form' => $form->createView(),    ]);}

My form :

class RegisterType extends AbstractType{    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('username')            ->add('password',PasswordType::class)            ->add('password2',PasswordType::class)            ->add('email')            ->add('name')            ->add('captchaCode', CaptchaType::class, ['captchaConfig' => 'ExampleCaptchaUserRegistration','constraints' => [                    new ValidCaptcha(['message' => 'Invalid captcha, please try again',                    ]),                ],]);    }    public function configureOptions(OptionsResolver $resolver)    {        $resolver->setDefaults(['data_class' => User::class,        ]);    }}

The captchaCode on User.php

/** * @CaptchaAssert\ValidCaptcha( *     message = "Invalid captcha, please try again", *     groups={"register"} * ) */protected $captchaCode;public function getCaptchaCode(){  return $this->captchaCode;}public function setCaptchaCode($captchaCode){  $this->captchaCode = $captchaCode;}

Variables that can be used in the whole symfony app? - Symfony 4

$
0
0

So right now I'm developing an app in Symfony4 where the users can create files with one parameter that can be chosen between a variety of options (these options being already defined), for example:

Year = [2020,2019,2018,2017];Type = ['A','B','C'];User = ['User' => 'ROLE_USER','Admin' => 'ROLE_ADMIN','Guest' => 'ROLE_GUEST',];

And I would like that the admin could change this variables by adding a new year or adding a new type of file.So I thought that this could be achievable by creating a global variable for the whole app (a variable that can be accessed from everywhere) in order to use it in the forms, views, etc. But I dont know how to do it.I think I could do it in two ways:

  • Creating a specific table in the db for these parameters, this way using doctrine to fetch the data and being able to updating it easily. (One more call to the database every time I want to use it)
  • Or creating a global variable as I said before that I can access everytime I want

What should I do?Is there any other easier way to achieve this?

Thank you very much in advance

Add select COUNT events in common between the current user and the others in DQL query

$
0
0

I have this DQL query in Symfony 4 project, it does select all users who are registered in all the same events as current user

$query = $this->_em->createQuery("select u as user, er.dateRegistration from App:EventRegistration er      left join App:User u with er.user = u.id     where er.user != :user_id and      er.event in (select identity(er2.event) from App:EventRegistration er2      where er2.user = :user_id)")->setParameter('user_id', $user->getId());return $query->getResult();

Now, in the same query, I'd like to select COUNT how many times each one of the other users has registered in the same event of the current user.

I mean the number of events in common between the current user and the others.

if I add count(er.id) to the select

select u as user, er.dateRegistration, count(er.id)

I get this error :

SQLSTATE[42803]: Grouping error: 7 ERREUR: la colonne « u0_.username » doit apparaître dans la clause GROUP BY ou doit être utilisé dans une fonction d'agrégatLINE 1: SELECT u0_.username AS username_0, u0_.username_canonical AS..

Symfony 4 produces SQLSTATE[HY000] [2002] Connection refused using Docker containers

$
0
0

I have 2 Docker containers using the following configuration:

version: '2'volumes:  db_data: {}services:  db:    container_name: database-mysql-5.7    build:      context: ./docker/db/    ports:      - "3321:3306"    volumes:      - db_data:/var/lib/mysql  web:    container_name: apache-symfony-4    build:      context: ./docker/web/    image: php    links:      - db    depends_on:      - db    ports:      - "8021:80"    volumes:      - ./app/:/var/www/symfony

I can connect to the db container from my local host (Mac OS) and I can connect to the db container (and execute sql statements successfully) from the web container. Additionally, when I exec to the web container I can execute doctrine:migrations:diff commands successfully.

However, when I try and run code like the following:

$User = $this->getDoctrine()                ->getRepository(User::class)                ->findAll();

I receive the following error:

An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refusedoctrine\DBAL\Exception\ConnectionException:An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused  at vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:108  at Doctrine\DBAL\Driver\AbstractMySQLDriver->convertException('An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused', object(PDOException))     (vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:176)  at Doctrine\DBAL\DBALException::wrapException(object(Driver), object(PDOException), 'An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused')     (vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:161)  at Doctrine\DBAL\DBALException::driverException(object(Driver), object(PDOException))     (vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOMySql/Driver.php:47)

Here is the contents of my .env file

# This file is a "template" of which env vars need to be defined for your application# Copy this file to .env file for development, create environment variables when deploying to production# https://symfony.com/doc/current/best_practices/configuration.html#infrastructure-related-configuration###> symfony/framework-bundle ###APP_ENV=devAPP_SECRET=7c2deaf7464ad40b484d457e02a56918#TRUSTED_PROXIES=127.0.0.1,127.0.0.2#TRUSTED_HOSTS=localhost,example.com###< symfony/framework-bundle ######> symfony/swiftmailer-bundle #### For Gmail as a transport, use: "gmail://username:password@localhost"# For a generic SMTP server, use: "smtp://localhost:25?encryption=&auth_mode="# Delivery is disabled by default via "null://localhost"MAILER_URL=null://localhost###< symfony/swiftmailer-bundle ######> doctrine/doctrine-bundle #### Format described at http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url# For an SQLite database, use: "sqlite:///%kernel.project_dir%/var/data.db"# Configure your db driver and server_version in config/packages/doctrine.yamlDATABASE_URL=mysql://hereswhatsontap:####@db:####/hereswhatsontap###< doctrine/doctrine-bundle ###

Additionally, if I try and use the DBAL it returns the same error:

/**     * @Route("/test")     */    public function testAction(Connection $connection){        $users = $connection->fetchAll('SELECT * FROM users');        return $this->render("startup/startup.html/twig", ["NewUser" => $users        ]);    }

Attempts to use the root username/password are also failing.

Ok, last additional data (I promise :)

Executing the following code works fine from within the /public folder of Symfony

<?php$dsn = 'mysql:host=db;dbname=hereswhatsontap;';$username = 'hereswhatsontap';$password = '####';$options = array(    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',);$dbh = new PDO($dsn, $username, $password, $options);$sql = "SELECT * from user";$statement = $dbh->prepare($sql);$statement->execute();$users = $statement->fetchAll(2);print_r($users);?>

Symfony4 / Docker: SQLSTATE[HY000] [2002] Connection refused

$
0
0

i have a problem with Symfony 4 and database connexion.I try to make migration with php bin/console make:migration but then i face the connection refused error.

In AbstractMySQLDriver.php line 113:  An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused  In PDOConnection.php line 50:  SQLSTATE[HY000] [2002] Connection refused  In PDOConnection.php line 46:  SQLSTATE[HY000] [2002] Connection refused  

My .env file is like this.

###> doctrine/doctrine-bundle #### Format described at http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url# For an SQLite database, use: "sqlite:///%kernel.project_dir%/var/data.db"# Configure your db driver and server_version in config/packages/doctrine.yamlDATABASE_URL=mysql://db_user:db_password@127.0.0.1:3306/db_nameDATABASE_USER=sf4userDATABASE_PWD=sf4pwdDATABASE_NAME=sf4DATABASE_HOST=127.0.0.1DATABASE_PORT=3306###< doctrine/doctrine-bundle ###

And here is my packages/doctrine.yaml:

parameters:    # Adds a fallback DATABASE_URL if the env var is not set.    # This allows you to run cache:warmup even if your    # environment variables are not available yet.    # You should not need to change this value.    env(DATABASE_URL): ''    doctrine:        dbal:            # configure these for your database server            driver: 'pdo_mysql'            server_version: '5.7'            charset: utf8mb4            default_table_options:                charset: utf8mb4                collate: utf8mb4_unicode_ci            host: '%env(DATABASE_HOST)%'            user: '%env(DATABASE_USER)%'            password: '%env(DATABASE_PWD)%'            dbname: '%env(DATABASE_NAME)%'            port: '%env(DATABASE_PORT)%'            url: '%env(resolve:DATABASE_URL)%'        orm:            auto_generate_proxy_classes: '%kernel.debug%'            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 understant that database URL is resolved on the basis of what i setted in .env file, but i cannot manage to make it work and whenever i try to call a console method dealing with db i get the connection refused error.

I build the project with a docker-compose.yml file:

version: '3'services:    apache:        build: .docker/apache        container_name: sf4_apache        ports:          - 80:80        volumes:          - .docker/config/vhosts:/etc/apache2/sites-enabled          - .:/home/wwwroot/sf4        depends_on:          - php    mysql:        image: mysql        container_name: sf4_mysql        volumes:            - .docker/data/db:/var/lib/mysql        command: ["--default-authentication-plugin=mysql_native_password"]        ports:            - "3306:3306"        environment:            MYSQL_ROOT_PASSWORD: root_pwd_test            MYSQL_DATABASE: sf4            MYSQL_USER: sf4user            MYSQL_PASSWORD: sf4pwd    php:        build: .docker/php        container_name: sf4_php        volumes:          - .:/home/wwwroot/sf4        environment:          - maildev_host=sf4_maildev        depends_on:          - maildev          - mysql    phpmyadmin:        image: phpmyadmin/phpmyadmin        container_name: sf4_phpmyadmin        ports:            - 8080:80        links:            - mysql        environment:            MYSQL_USERNAME: root            MYSQL_ROOT_PASSWORD: root_pwd_test            PMA_HOST: mysql

What could i be missing ?

NelmioApiDocBundle package is giving Unexpected token error? [closed]

$
0
0

I have installed a NelmioApiDocBundle ~ 3.7. It works perfectly in my local. But in the server I am getting Uncaught SyntaxError: Unexpected token '<'.

This errors are pointed at

swagger-ui-bundle.js:1 swagger-ui-standalone-preset.js:1 init-swagger-ui.js:1

How to load doctrine fixtures if we have multiple databases and connections

$
0
0

I used this documentation : https://symfony.com/doc/4.4/doctrine/multiple_entity_managers.html

So now I can create new databases named legacy and Project like this

doctrince.yaml:

doctrine:  dbal:    default_connection: legacy    connections:      legacy:        driver: pdo_mysql        host: "%env(database_host)%"        port: "%env(database_port)%"        dbname: "%env(database_name)%"        user: "%env(database_user)%"        password: "%env(database_password)%"        charset: UTF8      project:        driver: pdo_mysql        host: "%env(database_host_project)%"        port: "%env(database_port_project)%"        dbname: "%env(database_name_project)%"        user: "%env(database_user_project)%"        password: "%env(database_password_project)%"        charset: UTF8  orm:    default_entity_manager: legacy    entity_managers:      legacy:        connection: legacy        mappings:          Legacy:            is_bundle: false            type: annotation            dir: "%kernel.project_dir%/..."            prefix: '...'            alias: Legacy      project:        connection: project        auto_mapping: true        mappings:          Project:            is_bundle: false            type: annotation            dir: "%kernel.project_dir%/src/Entity"            prefix: 'App\Entity'            alias: Project

Now I have several Fixture classes all of them depend on each other and also some will create fixture for legacy and some will create for project.

Now my question is when I do:

php bin/console doctrine:fixtures:load --em=legacy

It runs the appfixtures of the project but not the of the bundle.and then i get this error:

The class .. was not found in the chain configured namespaces ....

My question is now how can I load fixtures on multiple databases with multiple connections.Thanks in advance.

Symfony 4.4 Multiple firewalls security for multiple providers

$
0
0

I have two firewalls, for users and soumissionaire. I created two different providers linking two different entities. I can log in as a user, but never as soumissionaire, i got 302 http error.

I do not understand what I need to add more

security:encoders:App\Entity\User:algorithm: bcrypt

    App\Entity\Compte:        algorithm: bcrypt# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providersproviders:    chain_provider:        chain:            providers: [user_provider, soumissionnaire_provider]    in_memory: { memory: ~ }    user_provider:        entity:            class: App\Entity\User            property: username    soumissionnaire_provider:        entity:            class: App\Entity\Compte            property: usernamerole_hierarchy:    # Un admin hérite des droits d'utilisateur et de souscommission    ROLE_ADMIN:       ROLE_SOUSCOMMISSION    # On garde ce rôle superadmin, il nous resservira par la suite    #ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]firewalls:    dev:        pattern: ^/(_(profiler|wdt)|css|images|js)/        security: false    soumission:        pattern: ^/compte        anonymous: true        provider:            soumissionnaire_provider        form_login:            login_path: authentificatin_security            check_path: authentificatin_security            default_target_path: home        logout:            path: deconnexion_security            target: authentificatin_security    main:        pattern: ^/        anonymous: true        provider:            user_provider        form_login:            login_path: security_login            check_path: security_login            default_target_path: accueil        logout:            path: security_logout            target: security_login        # activate different ways to authenticate        # http_basic: true        # https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate        # form_login: true        # https://symfony.com/doc/current/security/form_login_setup.html# Easy way to control access for large sections of your site# Note: Only the *first* access control that matches will be usedaccess_control:    - { path: ^/admin, roles: ROLE_ADMIN }    - { path: ^/analyse, roles: ROLE_SOUSCOMMISSION }    - { path: ^/compte, roles: ROLE_SOUSMISSIONAIRE }access_denied_url: /login

Symfony Manually Log User In

$
0
0

A page exists where a user entity is created (this is outside of the normal registration flow).

When the user is created they should be logged in, a guardHandler is used with an authenticator as shown below.

use App\Security\FakeAuthenticator;use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;        $response = $guardHandler->authenticateUserAndHandleSuccess(                $user, // the User object you just created                $request,                $authenticator, // authenticator whose onAuthenticationSuccess you want to use'main'          // the name of your firewall in security.yaml        );

However the authenticator is a mess, it has only been created for the one method onAuthenticationSuccess.

use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;class FakeAuthenticator extends AbstractGuardAuthenticator{    public function supports(Request $request)    {    return false;    }    public function getCredentials(Request $request)    {    throw new \RuntimeException('Unreachable code');    }    public function getUser($credentials, UserProviderInterface $userProvider)    {    throw new \RuntimeException('Unreachable code');    }    public function checkCredentials($credentials, UserInterface $user)    {    throw new \RuntimeException('Unreachable code');    }    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)    {    return null;    }    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)    {    throw new \RuntimeException('Unreachable code');    }    public function start(Request $request, AuthenticationException $authException = null)    {    throw new \RuntimeException('Unreachable code');    }    public function supportsRememberMe()    {    return true;    }}

Lots of methods have to be implemented because the method handleAuthenticationSuccess expects a class which implements AuthenticatorInterface.

The code works and the user is logged in but it doesn't feel like the cleanest solution, is there another way to log in a user?

FosUserBundle is being used in the project and the following does work, but I am unsure if calling methods on loginManager is supported, I can't find anything in the documentation and I don't want my code to be depend on a feature that could change.

\FOS\UserBundle\Security\LoginManagerInterface::logInUser('main', $user, $response);

Load list of active users from database with symfony without using a controller

$
0
0

I'm making a presonification menu on my navbar and so that i can access from any page i don't want to use the getRepository inside a controller and pass to the frontend.

Is there a way on symfony 4 that I can get all the users from my database and call it to front? like the app.session.user (to get info on the logged user) for example?

Thanks!

Is there a known bug for bernard.receiver when used with symfony 4?

$
0
0

I tried using bernard-bundle in my Symfony 4.3 project to run a basic helloWorld background task, but when I try to run bernard: consume I get an error

In SimpleRouter.php line 38:Given "my_receiver" is not supported. 

This is the services.yaml part

 my_receiver:        class: App\BackgroundTasks\Receiver\        tags:            - { name: bernard.receiver, message: 'HelloWorld' }

It says the error is in SimpleRouter, so I tried debugging there using

    var_dump($name);    var_dump($receiver);    var_dump(class_exists($receiver)); 

and I got

    string(10) "HelloWorld"    string(11) "my_receiver"    bool(false)

Is this a bug because of Symfony? Or am I missing something?


Sylius Security: Login-form Google reCaptcha

$
0
0

I'm trying to add ReCaptcha to Sylius Login Form, I have installed stefandoorn/sylius-recaptcha-plugin and followed all installation instructions, but it's not validating, the form is logged even when the captcha field is empty, no error is throwed.I'm currently using Sylius v1.7

The view is working well and look like that:Login with captchaI have extended SecurityLoginType and created an Extension:

<?phpdeclare(strict_types=1);namespace App\Form\Extension;use EWZ\Bundle\RecaptchaBundle\Form\Type\EWZRecaptchaType;use EWZ\Bundle\RecaptchaBundle\Validator\Constraints\IsTrue as RecaptchaTrue;use Sylius\Bundle\UiBundle\Form\Type\SecurityLoginType;use Symfony\Component\Form\AbstractTypeExtension;use Symfony\Component\Form\FormBuilderInterface;class SecurityLoginTypeExtension extends AbstractTypeExtension{    public function buildForm(FormBuilderInterface $builder, array $options): void    {        $builder->add('_recaptcha', EWZRecaptchaType::class, ['mapped' => false,'constraints' => [                new RecaptchaTrue(),            ],'attr' => ['defer' => true,'async' => true,            ],        ]);    }    public static function getExtendedTypes(): iterable    {        return [SecurityLoginType::class];    }}

And register the extension on config/services.yml

app.form.extension.type.security_login:        class: App\Form\Extension\SecurityLoginTypeExtension        tags:            - { name: form.type_extension, extended_type: Sylius\Bundle\UiBundle\Form\Type\SecurityLoginType }

And override the login tempate in SyliusUiBundle/Security/_login.html.twig

...{% form_theme form '@EWZRecaptcha/Form/ewz_recaptcha_widget.html.twig' %}{{ form_errors(form._recaptcha) }}{{ form_widget(form._recaptcha, { 'attr': {'options' : {'theme': 'light','type': 'image','size': 'normal'    },} }) }}...

Any suggestions about it.Thanks in advance.

JSONLD—Absolute URLs for @context

$
0
0

I am using Symfony 4 and the Api Platform, works fine so far. To implement stuff on the frontend, I am using jsonld.js, which seams to be the »official« library to handle ld+json related actions, since it is directly linked at json-ld.org.

However: GET /api/v1 returns that:

{"@context": "/api/v1/contexts/Entrypoint","@id":"/api/v1","@type":"Entrypoint","story":"/api/v1/stories","author":"/api/v1/authors",}

And trying to:

fetch('/api/v1')  .then(r => r.json())  .then(json => jsonld.expand(json))  .then(expanded => console.log(expanded))

results in:

Error: Dereferencing a URL did not result in a valid JSON-LD object. Possible causes are an inaccessible URL perhaps due to a same-origin policy (ensure the server uses CORS if you are using client-side JavaScript), too many redirects, a non-JSON response, or more than one HTTP Link Header was provided for a remote context.

Changing @context value to: http://localhost:8000/api/v1 and everything works, so the cause of the error are the relative urls.

Question:Is it possible to set the »base url« either at the server or with jsonld.js? If so, what should be the preferred solution: Server- or clientside.

symfony redirect from one domain to another

$
0
0

I got a Symfony 4.2 site that serves content on two sub domains:

a.example.com

b.example.com

How can I redirect requests made for /resetting/reset/ on a to b, while keeping the query string?

I tried the below but it's not doing anything - ie when I hit a.example.com/resetting/reset it just stays there. No errors.

resetting:    host: ^%a_domain%$    path: ^/resetting/reset/    controller: Symfony\Bundle\FrameworkBundle\Controller\RedirectController::urlRedirectAction    defaults:        path: '%b_domain%/resetting/reset/'        permanent: true        keepQueryParams: true

Any ideas would be appreciated!

Symfony 4 login form : authenticating successfully, but authentication immediately lost after redirect

$
0
0

I built a login form following this form login setup doc.

This is working fine on localhost but not on the production server.

On both localhost and prod, authentication begins successfully

  1. Guard authentication successful
  2. Guard authenticator set success response
  3. Stored the security token in the session
  4. Matched route "easyadmin

    ### var/log/prod.log output with info level[2019-07-05 10:28:46] request.INFO: Matched route "app_login". {"route":"app_login","route_parameters":{"_route":"app_login","_controller":"App\\Controller\\SecurityController::login"},"request_uri":"https://example.com/login","method":"POST"} [][2019-07-05 10:28:46] security.DEBUG: Checking for guard authentication credentials. {"firewall_key":"main","authenticators":1} [][2019-07-05 10:28:46] security.DEBUG: Checking support on guard authenticator. {"firewall_key":"main","authenticator":"App\\Security\\LoginFormAuthenticator"} [][2019-07-05 10:28:46] security.DEBUG: Calling getCredentials() on guard authenticator. {"firewall_key":"main","authenticator":"App\\Security\\LoginFormAuthenticator"} [][2019-07-05 10:28:46] security.DEBUG: Passing guard token information to the GuardAuthenticationProvider {"firewall_key":"main","authenticator":"App\\Security\\LoginFormAuthenticator"} [][2019-07-05 10:28:46] php.INFO: User Deprecated: The "Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder" class is deprecated since Symfony 4.3, use "Symfony\Component\Security\Core\Encoder\NativePasswordEncoder" instead. {"exception":"[object] (ErrorException(code: 0): User Deprecated: The \"Symfony\\Component\\Security\\Core\\Encoder\\BCryptPasswordEncoder\" class is deprecated since Symfony 4.3, use \"Symfony\\Component\\Security\\Core\\Encoder\\NativePasswordEncoder\" instead. at /var/www/clients/client0/web4/web/vendor/symfony/security-core/Encoder/BCryptPasswordEncoder.php:14)"} [][2019-07-05 10:28:46] security.INFO: Guard authentication successful! {"token":"[object] (Symfony\\Component\\Security\\Guard\\Token\\PostAuthenticationGuardToken: PostAuthenticationGuardToken(user=\"myemail@gmail.com\", authenticated=true, roles=\"ROLE_EDITOR, ROLE_USER\"))","authenticator":"App\\Security\\LoginFormAuthenticator"} [][2019-07-05 10:28:46] security.DEBUG: Guard authenticator set success response. {"response":"[object] (Symfony\\Component\\HttpFoundation\\RedirectResponse: HTTP/1.0 302 Found\r\nCache-Control: no-cache, private\r\nDate:          Fri, 05 Jul 2019 10:28:46 GMT\r\nLocation:      /backoffice\r\n\r\n<!DOCTYPE html>\n<html>\n    <head>\n        <meta charset=\"UTF-8\" />\n        <meta http-equiv=\"refresh\" content=\"0;url=/backoffice\" />\n\n        <title>Redirecting to /backoffice</title>\n    </head>\n    <body>\n        Redirecting to <a href=\"/backoffice\">/backoffice</a>.\n    </body>\n</html>)","authenticator":"App\\Security\\LoginFormAuthenticator"} [][2019-07-05 10:28:46] security.DEBUG: Remember me skipped: it is not configured for the firewall. {"authenticator":"App\\Security\\LoginFormAuthenticator"} [][2019-07-05 10:28:46] security.DEBUG: The "App\Security\LoginFormAuthenticator" authenticator set the response. Any later authenticator will not be called {"authenticator":"App\\Security\\LoginFormAuthenticator"} [][2019-07-05 10:28:46] security.DEBUG: Stored the security token in the session. {"key":"_security_main"} [][2019-07-05 10:28:46] request.INFO: Matched route "easyadmin". {"route":"easyadmin","route_parameters":{"_controller":"Symfony\\Bundle\\FrameworkBundle\\Controller\\RedirectController::urlRedirectAction","path":"/backoffice/","permanent":true,"scheme":null,"httpPort":80,"httpsPort":443,"_route":"easyadmin"},"request_uri":"https://example.com/backoffice","method":"GET"} []

But while in localhost, I am correctly redirected to the backoffice :

  • Read existing security token from the session
  • User was reloaded from a user provider

    ### var/log/prod.log (following lines, localhost) [2019-07-05 10:19:29] security.DEBUG: Read existing security token from the session. {"key":"_security_main","token_class":"Symfony\\Component\\Security\\Guard\\Token\\PostAuthenticationGuardToken"} [][2019-07-05 10:19:29] security.DEBUG: User was reloaded from a user provider. {"provider":"Symfony\\Bridge\\Doctrine\\Security\\User\\EntityUserProvider","username":"raoux.thierry@free.fr"} [][2019-07-05 10:19:29] security.DEBUG: Checking for guard authentication credentials. {"firewall_key":"main","authenticators":1} [][2019-07-05 10:19:29] security.DEBUG: Checking support on guard authenticator. {"firewall_key":"main","authenticator":"App\\Security\\LoginFormAuthenticator"} [][2019-07-05 10:19:29] security.DEBUG: Guard authenticator does not support the request. {"firewall_key":"main","authenticator":"App\\Security\\LoginFormAuthenticator"} [][2019-07-05 10:19:29] cache.INFO: Lock acquired, now computing item "easyadmin.processed_config" {"key":"easyadmin.processed_config"} []

In prod environment, instead :

  • it skips step : reading existing security token
  • does not refresh user as expected
  • instead it populates the TokenStorage with an anonymous Token
  • Acces denied and back to login url

    ### var/log/prod.log (same following lines, but from production server) [2019-07-05 10:28:46] security.DEBUG: Checking for guard authentication credentials. {"firewall_key":"main","authenticators":1} [][2019-07-05 10:28:46] security.DEBUG: Checking support on guard authenticator. {"firewall_key":"main","authenticator":"App\\Security\\LoginFormAuthenticator"} [][2019-07-05 10:28:46] security.DEBUG: Guard authenticator does not support the request. {"firewall_key":"main","authenticator":"App\\Security\\LoginFormAuthenticator"} [][2019-07-05 10:28:46] security.INFO: Populated the TokenStorage with an anonymous Token. [] [][2019-07-05 10:28:46] security.DEBUG: Access denied, the user is not fully authenticated; redirecting to authentication entry point. {"exception":"[object] (Symfony\\Component\\Security\\Core\\Exception\\AccessDeniedException(code: 403): Access Denied. at /var/www/clients/client0/web4/web/vendor/symfony/security-http/Firewall/AccessListener.php:72)"} [][2019-07-05 10:28:46] security.DEBUG: Calling Authentication entry point. [] [][2019-07-05 10:28:46] request.INFO: Matched route "app_login". {"route":"app_login","route_parameters":{"_route":"app_login","_controller":"App\\Controller\\SecurityController::login"},"request_uri":"https://example.com/login","method":"GET"} []

security.yaml

security:    encoders:        App\Entity\User:            algorithm: bcrypt    providers:        app_user_provider:            entity:                class: App\Entity\User                property: email    firewalls:        dev:            pattern: ^/(_(profiler|wdt)|css|images|js)/            security: false        main:            anonymous: true            guard:                authenticators:                    - App\Security\LoginFormAuthenticator            logout:                path: app_logout    access_control:        - { path: ^/backoffice, roles: ROLE_EDITOR} # requires_channel: https

routes.yaml

admin:  path: /backoffice  controller: EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController

LoginFormAuthenticator

// use...class LoginFormAuthenticator extends AbstractFormLoginAuthenticator{    use TargetPathTrait;    private $entityManager;    private $urlGenerator;    private $csrfTokenManager;    private $passwordEncoder;    public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)    {        $this->entityManager = $entityManager;        $this->urlGenerator = $urlGenerator;        $this->csrfTokenManager = $csrfTokenManager;        $this->passwordEncoder = $passwordEncoder;    }    public function supports(Request $request)    {        return 'app_login' === $request->attributes->get('_route')&& $request->isMethod('POST');    }    public function getCredentials(Request $request)    {        $credentials = ['email' => $request->request->get('email'),'password' => $request->request->get('password'),'csrf_token' => $request->request->get('_csrf_token'),        ];        $request->getSession()->set(            Security::LAST_USERNAME,            $credentials['email']        );        return $credentials;    }    public function getUser($credentials, UserProviderInterface $userProvider)    {        $token = new CsrfToken('authenticate', $credentials['csrf_token']);        if (!$this->csrfTokenManager->isTokenValid($token)) {            throw new InvalidCsrfTokenException();        }        $user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);        if (!$user) {            // fail authentication with a custom error            throw new CustomUserMessageAuthenticationException('Email could not be found.');        }        return $user;    }    public function checkCredentials($credentials, UserInterface $user)    {        return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);    }    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('admin'));    }    protected function getLoginUrl()    {        return $this->urlGenerator->generate('app_login');    }}

Security controller

// use...class SecurityController extends AbstractController{    /**     * @Route("/login", name="app_login")     */    public function login(AuthenticationUtils $authenticationUtils): Response    {        // get the login error if there is one        $error = $authenticationUtils->getLastAuthenticationError();        // last username entered by the user        $lastUsername = $authenticationUtils->getLastUsername();        return $this->render('security/login.html.twig',          ['last_username' => $lastUsername,'error' => $error,          ]        );    }    /**     * @Route("/logout", name="app_logout")     * @return \Symfony\Component\HttpFoundation\RedirectResponse     */    public function logout()    {        return $this->redirectToRoute('home');    }}//... skipped forgottenPassword and resetPassword methods

EDIT:

php bin/console debug:config security output

Current configuration for extension with alias "security"=========================================================security:encoders:    App\Entity\User:        algorithm: bcrypt        hash_algorithm: sha512        key_length: 40        ignore_case: false        encode_as_base64: true        iterations: 5000        cost: null        memory_cost: null        time_cost: null        threads: nullproviders:    app_user_provider:        entity:            class: App\Entity\User            property: email            manager_name: nullfirewalls:    dev:        pattern: ^/(_(profiler|wdt)|css|images|js)/        security: false        methods: {  }        user_checker: security.user_checker        stateless: false        logout_on_user_change: true    main:        anonymous:            secret: null        guard:            authenticators:                - App\Security\LoginFormAuthenticator            entry_point: null        logout:            path: app_logout            csrf_parameter: _csrf_token            csrf_token_id: logout            target: /            invalidate_session: true            delete_cookies: {  }            handlers: {  }        methods: {  }        security: true        user_checker: security.user_checker        stateless: false        logout_on_user_change: trueaccess_control:    -        path: ^/backoffice        roles:            - ROLE_EDITOR        requires_channel: null        host: null        port: null        ips: {  }        methods: {  }        allow_if: nullaccess_decision_manager:    strategy: affirmative    allow_if_all_abstain: false    allow_if_equal_granted_denied: trueaccess_denied_url: nullsession_fixation_strategy: migratehide_user_not_found: truealways_authenticate_before_granting: falseerase_credentials: truerole_hierarchy: {  }

EDIT 2

AS @Arno commented, I edited framework.yaml to save sessions in var/ directory and I can check that this step works without permissions issues, each time I hit the login form, a sess_ file is written.

Worth saying that if I comment :

access_control:    - { path: ^/odelices_admin, roles: ROLE_USER}

I can access backoffice.

EDIT 3 : session behavior

So now sessions are saved into var/sessions/prod.

  1. I clean the dir : sudo rm -r var/sessions/prod/sess_*
  2. I open Chrome and the url, it sets a PHPSSID cookie with the same value as a first sess_xyz file :

    _sf2_attributes|a:2:{s:19:"_csrf/https-contact";s:43:"Oq-QpN21bI_BUDcVbv0ocyrYsTzQo3aJr80QAk2AR7w";s:19:"_csrf/https-booking";s:43:"z_L4TG7Wg0jydwl5VabfJMx0NBhQgeasuAiqxksLvD8";}_sf2_meta|a:3:{s:1:"u";i:1562668584;s:1:"c";i:1562668584;s:1:"l";s:1:"0";}
  3. I go to login page. New PHPSSID value associated with a new sess_xyz file :

    _sf2_attributes|a:1:{s:24:"_csrf/https-authenticate";s:43:"erWMU-irtptcZodr8UOjFtxiuyE23LbAeFHRnXgcNdc";}_sf2_meta|a:3:{s:1:"u";i:1562668662;s:1:"c";i:1562668662;s:1:"l";s:1:"0";}
  4. I log in with correct values. This creates 3 new ssid_xyz files.

    # 1st one shows user logged in with correct roles and so on_sf2_attributes|a:3:{s:24:"_csrf/https-authenticate";s:43:"erWMU-irtptcZodr8UOjFtxiuyE23LbAeFHRnXgcNdc";s:23:"_security.last_username";s:21:"user_email@gmail.com";s:14:"_security_main";s:799:"C:67:"Symfony\Component\Security\Guard\Token\PostAuthenticationGuardToken":718:{a:2:{i:0;s:4:"main";i:1;a:5:{i:0;O:15:"App\Entity\User":6:{s:19:"^@App\Entity\User^@id";i:1;s:22:"^@App\Entity\User^@email";s:21:"user_email@gmail.com";s:22:"^@App\Entity\User^@roles";a:1:{i:0;s:11:"ROLE_EDITOR";}s:25:"^@App\Entity\User^@password";s:60:"$2y$13$cXaR7Ss.kTH1U.T/Rzi6m.ALsKwWCLDcO5/OIeRDAq02iylmf4us6";s:21:"^@App\Entity\User^@name";s:7:"Thierry";s:13:"^@*^@resetToken";N;}i:1;b:1;i:2;a:2:{i:0;O:41:"Symfony\Component\Security\Core\Role\Role":1:{s:47:"^@Symfony\Component\Security\Core\Role\Role^@role";s:11:"ROLE_EDITOR";}i:1;O:41:"Symfony\Component\Security\Core\Role\Role":1:{s:47:"^@Symfony\Component\Security\Core\Role\Role^@role";s:9:"ROLE_USER";}}i:3;a:0:{}i:4;a:2:{i:0;s:11:"ROLE_EDITOR";i:1;s:9:"ROLE_USER";}}}}";}_sf2_meta|a:3:{s:1:"u";i:1562668713;s:1:"c";i:1562668713;s:1:"l";s:1:"0";}# 2nd one ...is empty# 3rd one refers to backoffice url_sf2_attributes|a:1:{s:26:"_security.main.target_path";s:42:"https://mywebsite.com/backoffice";}_sf2_meta|a:3:{s:1:"u";i:1562668713;s:1:"c";i:1562668713;s:1:"l";s:1:"0";}# last one is similar to point 3, before logging, only ssid value differs, and a corresponding cookie is set on Chrome_sf2_attributes|a:1:{s:24:"_csrf/https-authenticate";s:43:"3UC5dCRrahc2qhdZ167Jg4HKTJCexf8PFlefibTVpYk";}_sf2_meta|a:3:{s:1:"u";i:1562668713;s:1:"c";i:1562668713;s:1:"l";s:1:"0";}

EDIT 4 : User Entity

namespace App\Entity;use Doctrine\ORM\Mapping as ORM;// use Symfony\Component\Security\Core\User\EquatableInterface;use Symfony\Component\Security\Core\User\UserInterface;/** * @ORM\Entity(repositoryClass="App\Repository\UserRepository") */class User implements UserInterface # , EquatableInterface{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string", length=180, unique=true)     */    private $email;    /**     * @ORM\Column(type="json")     */    private $roles = [];    /**     * @var string The hashed password     * @ORM\Column(type="string")     */    private $password;    /**     * @ORM\Column(type="string", length=255)     */    private $name;    /**     * @var string le token qui servira lors de l'oubli de mot de passe     * @ORM\Column(type="string", length=255, nullable=true)     */    protected $resetToken;  /*public function __construct($username, $password, array $roles)  {    $this->username = $username;    $this->password = $password;    $this->roles = $roles;  }*/    public function getId(): ?int    {        return $this->id;    }    public function getEmail(): ?string    {        return $this->email;    }    public function setEmail(string $email): self    {        $this->email = $email;        return $this;    }    /**     * A visual identifier that represents this user.     *     * @see UserInterface     */    public function getUsername(): string    {        return (string) $this->email;    }    /**     * @see UserInterface     */    public function getRoles(): array    {        $roles = $this->roles;        // guarantee every user at least has ROLE_USER        $roles[] = 'ROLE_USER';        return array_unique($roles);    }    public function setRoles(array $roles): self    {        $this->roles = $roles;        return $this;    }    /**     * @see UserInterface     */    public function getPassword(): string    {        return (string) $this->password;    }    public function setPassword(string $password): self    {        $this->password = $password;        return $this;    }    /**     * @see UserInterface     */    public function getSalt()    {        // not needed when using the "bcrypt" algorithm in security.yaml    }    /**     * @see UserInterface     */    public function eraseCredentials()    {        // If you store any temporary, sensitive data on the user, clear it here        // $this->plainPassword = null;    }    public function getName(): ?string    {        return $this->name;    }    public function setName(string $name): self    {        $this->name = $name;        return $this;    }    /**     * @return string     */    public function getResetToken(): string    {      return $this->resetToken;    }    /**     * @param string $resetToken     */    public function setResetToken(?string $resetToken): void    {      $this->resetToken = $resetToken;    }    public function __toString() {      return $this->getName() ;    }/*    public function isEqualTo(UserInterface $user)    {      if ($this->password !== $user->getPassword()) {        return false;      }      if ($this->email !== $user->getUsername()) {        return false;      }      return true;    }*/}

Stack

Debian Stretch, Nginx + Varnish : Nginx handles 443 requests, pass them to Varnish as a cache proxy, which delivers cached objects or pass requests to nginx backend on 8083 port. This is working like a charm for another app with similar login logic (the lone difference is the buggy one redirects to easyadmin instead of a custom admin), so I don't think it is related to the stack.

vhost

server { # this block only redirects www to non www        listen aaa.bbb.ccc.ddd:443 ssl;        server_name www.somewebsite.com;        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;        ssl_certificate /var/www/clients/client0/web4/ssl/somewebsite.com-le.crt;        ssl_certificate_key /var/www/clients/client0/web4/ssl/somewebsite.com-le.key;        return 301 https://somewebsite.com$request_uri;}server { # this block redirects ssl requests to Varnish        listen aaa.bbb.ccc.ddd:443 ssl;        server_name somewebsite.com;        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;        ssl_certificate /var/www/clients/client0/web4/ssl/somewebsite.com-le.crt;        ssl_certificate_key /var/www/clients/client0/web4/ssl/somewebsite.com-le.key;        location / {            # Pass the request on to Varnish.            proxy_pass  http://127.0.0.1;            # Pass some headers to the downstream server, so it can identify the host.            proxy_set_header Host $host;            proxy_set_header X-Real-IP $remote_addr;            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;            # Tell any web apps that the session is HTTPS.            proxy_set_header X-Forwarded-Proto https;            proxy_redirect     off;        }}server { # now sent to backend         listen aaa.bbb.ccc.ddd:8083;        server_name somewebsite.com;        root   /var/www/somewebsite.com/web/public;        location / {            try_files $uri /index.php$is_args$args;       }       location ~ ^/index\.php(/|$) {            fastcgi_pass 127.0.0.1:8998;            fastcgi_split_path_info ^(.+\.php)(/.*)$;            include fastcgi_params;            fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;            fastcgi_param DOCUMENT_ROOT $realpath_root;            internal;        }        location ~ \.php$ {            return 404;        }        error_log /var/log/ispconfig/httpd/somewebsite.com/error.log;        access_log /var/log/ispconfig/httpd/somewebsite.com/access.log combined;        location ~ /\. {                        deny all;        }        location ^~ /.well-known/acme-challenge/ {                        access_log off;                        log_not_found off;                        root /usr/local/ispconfig/interface/acme/;                        autoindex off;                        try_files $uri $uri/ =404;        }        location = /favicon.ico {            log_not_found off;            access_log off;            expires max;        }        location = /robots.txt {            allow all;            log_not_found off;            access_log off;        }}

Could this be related to permissions on some dir ? HTTPS ? EasyAdmin ? How can I make sure the security token was stored in the session, even it is logged as stored ? I also tried to change access_control to role ROLE_USER so that any authenticated user should access. No way.

Any help is really appreciated.

Symfony 4 S3Client::factory issue: 'class Aws\S3\S3Client not found'

$
0
0

I am trying getObject() from aws bucket, but when try s3Client, error: 'class Aws\S3\S3Client not found'

$s3Client = S3Client::factory(['credentials' => ['key'    => $key,'secret' => $secret  ],'region' => $region,'version' => 'latest','scheme' => 'http'             ]);
Viewing all 3921 articles
Browse latest View live


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