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

Does Symfony 4 load the environment variables on every request in the "prod" environment?

$
0
0

Does Symfony 4 somehow save or cache the environment variable parameters in the "prod" environment or does it retrieve them on every request?

My problem is that when I host my Symfony application using Apache, I need to list all the environment variables by defining them all in the VirtualHost configuration using SetEnv directives; and I would prefer not having to do that.

I would expect that when using the PHP CLI, I could "compile" the Symfony project by capturing or caching the parameters so that when the application is run through Apache, it uses these "cached" parameters.

Is it doable or the SetEnv approach is the only one?


symfony 4 app on heroku with remote database

$
0
0

I really need some help here hehe Ok i got a symfony 4 application that is working perfectly in local environement.

I installed the app on heroku, but i want to access my Mysql database on my web hosting.

To be able to do that i had to install the Fixie app on heroku to have two ip adress and be able to whitelist those address for the remote access of my database.

The app is running good, but if i go to any links that have a call to do at the database i got a timeout.

I think the problem is in my index.php file, when installing Fixie you have to add code to the trust proxy

Heres what i have right now in my index.php file

<?php

use App\Kernel;
use Symfony\Component\Debug\Debug;
use Symfony\Component\HttpFoundation\Request;

require dirname(__DIR__).'/config/bootstrap.php';

if ($_SERVER['APP_DEBUG']) {
    umask(0000);

    Debug::enable();
}

$trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? $_ENV['TRUSTED_PROXIES'] ?? false;
$trustedProxies = $trustedProxies ? explode(',', $trustedProxies) : [];
if($_SERVER['APP_ENV'] == 'prod') $trustedProxies[] = $_SERVER['REMOTE_ADDR'];
if($trustedProxies) {
    Request::setTrustedProxies($trustedProxies, Request::HEADER_X_FORWARDED_AWS_ELB);
}

if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? $_ENV['TRUSTED_HOSTS'] ?? false) {
    Request::setTrustedHosts([$trustedHosts]);
}

$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Thats the log message i get when i try to access a page that have a call to the database

2019-11-28T22:13:12.218311+00:00 app[web.1]: [2019-11-28 22:12:42] request.INFO: Matched route "publicResultat". {"route":"publicResultat","route_parameters":{"_route":"publicResultat","_controller":"App\\Controller\\PublicController::index"},"request_uri":"https://jugement.herokuapp.com/public","method":"GET"} []
2019-11-28T22:13:12.218435+00:00 app[web.1]: [2019-11-28 22:12:42] security.INFO: Populated the TokenStorage with an anonymous Token. [] []
2019-11-28T22:13:12.220033+00:00 app[web.1]: [2019-11-28 22:13:12] request.CRITICAL: Uncaught PHP Exception Doctrine\DBAL\Exception\ConnectionException: "An exception occurred in driver: SQLSTATE[HY000] [2002] Connection timed out" at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php line 93 {"exception":"[object] (Doctrine\\DBAL\\Exception\\ConnectionException(code: 0): An exception occurred in driver: SQLSTATE[HY000] [2002] Connection timed out at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:93, Doctrine\\DBAL\\Driver\\PDOException(code: 2002): SQLSTATE[HY000] [2002] Connection timed out at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:31, PDOException(code: 2002): SQLSTATE[HY000] [2002] Connection timed out at /app/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:27)"} []

When you install fixie in heroku you have to add something this is the example they give for php but i don't understand how to do that in my symfony app

PHP cURL is the easiest way to get your PHP application working correctly with Fixie. Here’s how:

<?php
  function proxyRequest() {
    $fixieUrl = getenv("FIXIE_URL");
    $parsedFixieUrl = parse_url($fixieUrl);

    $proxy = $parsedFixieUrl['host'].":".$parsedFixieUrl['port'];
    $proxyAuth = $parsedFixieUrl['user'].":".$parsedFixieUrl['pass'];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_PROXY, $proxy);
    curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyAuth);
    curl_close($ch);
  }

  $response = proxyRequest();
  print_r($response);
?>

Hope that i am clear on my problem

any help would be very useful

I also found strange that i have no header present when the call is done

Request URL: https://jugement.herokuapp.com/public
Referrer Policy: no-referrer-when-downgrade

Thats all i have in the header

How to access the POST fields of a form built with the form builder?

$
0
0

I am trying to write a registration form with Symfony 4 I had added a password confirmation field.

class UserFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ...
            ->add('password', PasswordType::class)
            ->add('password2', PasswordType::class, [
                'label' => 'Password Confirmation',
                'mapped' => false,
            ])
            ...

And the controller I use the "password" field and the "password2" field to compare them if they are identical

/**
 * @Route("/register", name="app_user_registration")
 * @return Response
 */
public function userRegistration( Request $request, UserPasswordEncoderInterface $passwordEncoder ) : Response
    {
        $user =  new User();
        $userRegistrationForm = $this->createForm(UserFormType::class, $user);

        $userRegistrationForm->handleRequest($request);

        if ($userRegistrationForm->isSubmitted() && $userRegistrationForm->isValid() ){
            $submittedList = $request->request->get('user_form');
            if($submittedList['password']  === $submittedList['password2'])
            {

As you can see I had to use :

$request->request->get('user_form')['password'];

instead of

$request->request->get('password');

as the documentation suggested : link

Can someone help me to understand where my mistake is to not be able to use the method according to the doc

Symfony guard throws AuthenticationException but user loaded successfully

$
0
0

I want to implement form login with Symfony/Security to my app. I configured everything but it still doesn't work properly.

This is my security.yaml:

security:
    providers:
        sablon_users:
            entity:
                class: App\Entity\User
                property: email
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        admin_login:
            anonymous: true
            pattern: ^/admin/auth
            form_login:
                login_path: security_login
                check_path: security_login
                csrf_token_generator: security.csrf.token_manager
                default_target_path: /admin
        admin:
            pattern: ^/admin
            guard:
                authenticators:
                    - App\Security\LoginAuthenticator
            provider: sablon_users
            logout:
                path: admin_logout
                target: security_login
        main:
            pattern: ^/
            anonymous: true

            # 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 used
    access_control:
        - { path: ^/admin/auth/, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin, roles: IS_AUTHENTICATED_FULLY }

    encoders:
        App\Entity\User:
            algorithm: bcrypt
            cost: 12

my routes.yaml:

admin_logout:
    path: /admin/auth/logout
admin:
    type: annotation
    resource: ../src/Controller/Admin
    prefix: /admin
site:
    type: annotation
    resource: ../src/Controller/Site

LoginAuthenticator.php:

class LoginAuthenticator extends AbstractFormLoginAuthenticator
{


    /**
     * @var EntityManagerInterface
     */
    private $em;

    /**
     * @var RouterInterface
     */
    private $router;

    /**
     * @var UserPasswordEncoderInterface
     */
    private $encoder;

    /**
     * @var CsrfTokenManagerInterface
     */
    private $csrfTokenManager;

    /**
     * @var TokenStorageInterface
     */
    private $tokenStorage;

    /**
     * LoginAuthenticator constructor.
     *
     * @param EntityManagerInterface $em
     * @param CsrfTokenManagerInterface $csrfTokenManager
     * @param RouterInterface $router
     * @param TokenStorageInterface $tokenStorage
     * @param UserPasswordEncoderInterface $encoder
     */
    public function __construct(
        EntityManagerInterface $em,
        CsrfTokenManagerInterface $csrfTokenManager,
        RouterInterface $router,
        TokenStorageInterface $tokenStorage,
        UserPasswordEncoderInterface $encoder

    )
    {
        $this->em = $em;
        $this->csrfTokenManager = $csrfTokenManager;
        $this->router = $router;
        $this->tokenStorage = $tokenStorage;
        $this->encoder = $encoder;
    }

    /**
     * @param Request $request
     * @return bool
     */
    /**
     * @return mixed
     */
    public function getCurrentUser()
    {
        $token = $this->tokenStorage->getToken();

        return $token->getUser();
    }

    /**
     * Does the authenticator support the given Request?
     *
     * If this returns false, the authenticator will be skipped.
     *
     * @param Request $request
     *
     * @return bool
     */
    public function supports(Request $request)
    {
        $isLoginSubmitRequest = $request->getPathInfo() === 'admin/auth/login'&& $request->isMethod('POST');
        if(!$isLoginSubmitRequest){
            return false;
        }
        return true;
    }


    /**
     * @param Request $request
     *
     * @return mixed Any non-null value
     *
     * @throws \UnexpectedValueException If null is returned
     */
    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;
    }


    /**
     * @param mixed $credentials
     * @param UserProviderInterface $userProvider
     * @return User|null|object|UserInterface
     */
    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        $token = new CsrfToken('authenticate', $credentials['csrf_token']);
        if (!$this->csrfTokenManager->isTokenValid($token)) {
            throw new InvalidCsrfTokenException();
        }

        $user = $this->em->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);

        if (!$user) {
            // fail authentication with a custom error
            throw new Exception('Email could not be found.');
        }

        return $user;
    }

    /**
     * @param mixed $credentials
     * @param UserInterface $user
     *
     * @return bool
     *
     * @throws AuthenticationException
     */
    public function checkCredentials($credentials, UserInterface $user)
    {
        $password = $credentials['password'];

        return $this->encoder->isPasswordValid($user,$password);
    }

    /**
     *
     * @param Request $request
     * @param AuthenticationException $exception
     *
     * @return Response|null
     */
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {

        $request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);


        return new RedirectResponse($this->router->generate('security_login'));
    }

    /**
     * @param Request $request
     * @param TokenInterface $token
     * @param string $providerKey The provider (i.e. firewall) key
     *
     * @return Response|null
     */
    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        return new RedirectResponse($this->router->generate('app_homepage'));
    }

    /**
     * @return bool
     */
    public function supportsRememberMe()
    {
        return false;
    }

    /**
     * Return the URL to the login page.
     *
     * @return string
     */
    protected function getLoginUrl()
    {
        return $this->router->generate('security_login');
    }

When i try to login with correct credentials. It loads User and even show the username on the _profiler as authenticated (Token class: UsernamePasswordToken). It shows the corresponding roles for the user.

However when i try to navigate '/admin' area, it redirects me to login page. It doesn't show any error in page or console.

My dev.log shows the flow though:

  • [2019-02-13 13:58:01] request.INFO: Matched route "app_homepage". {"route":"app_homepage","route_parameters":{"_controller":"Symfony\Bundle\FrameworkBundle\Controller\RedirectController::urlRedirectAction","path":"/admin/","permanent":true,"scheme":null,"httpPort":8000,"httpsPort":443,"_route":"app_homepage"},"request_uri":"http://localhost:8000/admin","method":"GET"} [] [2019-02-13 13:58:01] security.DEBUG: Checking for guard authentication credentials. {"firewall_key":"admin","authenticators":1} []
  • [2019-02-13 13:58:01] security.DEBUG: Checking support on guard authenticator. {"firewall_key":"admin","authenticator":"App\Security\LoginAuthenticator"} []
  • [2019-02-13 13:58:01] security.DEBUG: Guard authenticator does not support the request. {"firewall_key":"admin","authenticator":"App\Security\LoginAuthenticator"} []
  • [2019-02-13 13:58:01] security.INFO: An AuthenticationException was thrown; redirecting to authentication entry point. {"exception":"[object] (Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException(code: 0): A Token was not found in the TokenStorage. at /home/vagrant/Code/project_name/vendor/symfony/security-http/Firewall/AccessListener.php:51)"} []
  • [2019-02-13 13:58:01] security.DEBUG: Calling Authentication entry point. [] []

Symfony Form for Hours Of Operation

$
0
0

Currently trying to create a form to submit hours of operation. At the moment I achieved a form where the user is able to select the specific day (monday, tuesday, ...) and the opening time (hh:mm) plus the closing time (hh:mm).

My form type looks currently like this:

        $builder
            ->add('weekday', EntityType::class, ['label' => 'app.weekday', 'class' => Weekday::class, 'choice_label' => 'name', 'choice_translation_domain' => true])
            ->add('open', TimeType::class, ['label' => 'site.hours.open', 'input' => 'datetime_immutable'])
            ->add('close', TimeType::class, ['label' => 'site.hours.close', 'input' => 'datetime_immutable'])
            ->add('submit', SubmitType::class, ['label' => 'app.save']);

I've chosen to use an own Entity to save my weekdays, where 1 = monday, 2 = tuesday, ... (id, name).

However this renders a form where the user has to select each day + each times => submit the form and redo again for other days/times.

This is very inconvientent. My ideal solution would be to use a CollectionType for each day, where you can add more times to the collection and submit 1 form with all times per week.

Now this is where I begin to struggle with. I could make another FormType where I embed my current one as a collection - boom done. However this still needs the user to select each individual day - which I do not want.


So what do I want? A FomType to create a form the following way:

Monday    OpenSelect (HH:MM)     CloseSelect (HH:MM)  [remove Button]
          OpenSelect (HH:MM)     CloseSelect (HH:MM)  [remove Button]
          OpenSelect (HH:MM)     CloseSelect (HH:MM)  [remove Button]
          ---------      ADD Button     ------------

Tuesday   OpenSelect (HH:MM)     CloseSelect (HH:MM)  [remove Button]
          ---------      ADD Button     ------------

...

I dont want the user to select monday/tuesday etc - they should already be set. Just add new times to the collection for each day.

Please feel free to ask, if something is unclear.

Removing a custom form type through terminal Symfony4

$
0
0

I created a custom form type through the terminal in symfony4, but it doesn't work like I expected it to do. I figured out how to solve my problem without using the form type so my DishType isn't necessary anymore. But it is linked to my class 'Dish' (I had to give the class reference when creating it through the terminal) so when I delete the file I get this error:

    Could not load type "App\Entity\Dish": class does not implement "Symfony\Component\Form\FormTypeInterface". 

That's right because I've deleted the file and my Dish should not implement this.

So my thoughts were 'I've created it through the terminal, so I should be able to delete it through the terminal as well', but I can't figure out how.

Is there a different way to do this or can I indeed do it through the terminal?

Anyone who can help me ???

Allow access to specific pages

$
0
0

I am on Symfony 4.3.2, trying to get a way to allow users having role (CommissionOwner) access to only specific pages.

  • Users having role other than 'CommissionOwner' can access all pages.

  • Users having role 'CommissionOwner' can access only following pages.

    • www.xyz.com/Loginlandingpage
    • www.xyz.com/reportSalesCommissions

I am trying in myApp/config/packages/security.yaml

access_control:
     - { path: ^/reportSalesCommissions, roles: IS_CommissionOwner }

How to fix "https://repo.packagist.org/packages.json does not contain valid Json"?

$
0
0

I've an issue with composer running on a vagrantbox (Centos 7), which started to just suddenly happen.

I've already tried manually running the command/solution mentioned on the link below but to no avail.

(To clarify, i'm using vagrant not docker, but it was the closest question i found to my situation. Most of the information i found are related to composer.json not being valid, but here is packagist.org/packages.json which, is currently valid)

Composer not working in docker container: "https://packagist.org/packages.json" does not contain valid JSON

Here are the details of the issue.

While running composer update on terminal i get:

 composer update


  [Seld\JsonLint\ParsingException]
  "https://repo.packagist.org/packages.json" does not contain valid JSON
  Parse error on line 1:

  ^
  Expected one of: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

And when running composer install also on terminal every package returns this:

Failed to download psr/cache from dist: "https://api.github.com/repos/php-fig/cache/zipball/d11b50ad223250cf17b86e38383413f5a6764bf8" 
appears broken, and returned an empty 200 response
    Now trying to download from source

When running composer config --global repo.packagist composer packagist.org the results are now

composer update
Loading composer repositories with package information


  [Composer\Downloader\TransportException]
  Your configuration does not allow connections to http://repo.packagist.org/packages.json. See https://getcomposer.o
  rg/doc/06-config.md#secure-http for details.

Any ideas why this started to happen, how can i fix it?


Autowiring problem with parameter injection in Symfony 5

$
0
0

I'm having troubles trying to retrieve a manager from a controller in Symfony 5.

I've got this MailerManager in src/Manager/MailerManager.php:

<?php
namespace App\Manager;

use App\Client\MailjetClient;

class MailerManager {
    private $mailjetClient;     

    function __construct(MailjetClient $mailjetClient) {
        $this->setMailjetClient($mailjetClient);        
    }

    function send($data) {

    }

    function getMailjetClient() {
        return $this->mailjetClient;
    }

    private function setMailjetClient($mailjetClient) {
        $this->mailjetClient = $mailjetClient;
    }

}

This manager needs to inject src/Client/MailjetClient.php in order to work, that has got this code:

<?php
namespace App\Client;

use \Mailjet\Resources;

class MailjetClient {
    private $client;    

    function __construct(string $apikey, string $apisecret) {                       
        $this->setClient($apikey, $apisecret);      
    }               

    function getClient() {
        return $this->client;
    }

    function setClient($apikey, $apisecret) {
        $this->client = new \Mailjet\Client($apikey, $apisecret);
    }
}

This is just a wrapper for the mailjet sdk installed via composer, that needs to be feeded with different $apikey and $apisecret depending on the environment, for what I'm using parameters through services.yaml file, where I also have got autowiring enabled and service definitions for both MailjetClient and MailerManager:

parameters:
    rabbitmq:
        host: '%env(RABBITMQ_HOST)%'
        port: '%env(RABBITMQ_PORT)%'
        user: '%env(RABBITMQ_USER)%'
        pwd: '%env(RABBITMQ_PWD)%'
    mailjet:
        apikey: '%env(MAILJET_APIKEY)%'
        apisecret: '%env(MAILJET_APISECRET)%'

services:
    _defaults:
        autowire: true
        autoconfigure: true
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

    App\Client\MailjetClient\:
        resource: '../src/Client/MailjetClient.php'
        arguments:
            $apikey: '%mailjet.host%'
            $apisecret: '%mailjet.port%'        

    App\Manager\MailerManager\:
        resource: '../src/Manager/MailerManager.php'        
        arguments:
            $mailjetClient: '@client.mailjet'

The problem I'm having is that I'm getting this error: Cannot autowire service "App\Client\MailjetClient": argument "$apikey" of method "__construct()" is type-hinted "string", you should configure its value explicitly. when I try to inject the MailManager in the src/Controller/MailerController.php controller:

<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use App\Manager\MailerManager;

class MailerController extends AbstractController
{
    /**
     * @Route("/compose", name="compose")
     */
    public function compose(MailerManager $mailerManager) 
    {        
        dump($mailerManager);die();
        }
    }       
}

What could posibbly be wrong? I'm coming from Symfony 2, and this parameter injection was something standard that used to work like a charm, now I'm totally confused about how to mix the autowiring with the service manual definition.

Symfony 4 or 5 : is it a good pratice to use a service from a template?

$
0
0

I prepare a Symfony training class for beginners. I ask myself if using Symfony custom service in template is a bad practice (= Service must only be called in contoller), What do you think ?

Access an private api after login

$
0
0

I have this security.yml :

providers:
    fos_userbundle:
        id: fos_user.user_provider.username_email

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    login:
        pattern:  ^/api/public/login
        stateless: true
        anonymous: true
        json_login:
            check_path:               /api/public/login
            success_handler:          lexik_jwt_authentication.handler.authentication_success
            failure_handler:          lexik_jwt_authentication.handler.authentication_failure
    api:
        pattern:   ^/api/private
        stateless: true
        guard:
            authenticators:
                - lexik_jwt_authentication.jwt_token_authenticator
    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            csrf_token_generator: security.csrf.token_manager
        oauth:
            resource_owners:
                facebook:         "/secured/login_facebook"
                google:           "/secured/login_google"
            login_path:        fos_user_security_login
            failure_path:      fos_user_security_login
            oauth_user_provider:
                service: app.provider.oauth
            default_target_path: /api/public/facebook/back

        logout:       true
        anonymous:    true

access_control:
    - { path: ^/login$,             role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/,             role: ROLE_ADMIN }
    - { path: ^/api/private/,       role: IS_AUTHENTICATED_FULLY }
    - { path: ^/api/public/,        role: IS_AUTHENTICATED_ANONYMOUSLY }

And I have this route :

/**
 * @Route("/api/private/game/{gameName}", name="open_game_page", methods={"GET"})
 * @Method("GET")
 * @param $gameName
 * @return
 */
public function openGameAction($gameName)
{
    $template = '';
    switch ($gameName) {
        case Game::TEST:
            $template = Game::TEST;
            break;
    }
    return $this->render('game/'.$template.'.html.twig');
}

Firts I call the api /api/public/login that retourn me the jwtToken. After that If I wrote in browser : /api/private/game/test I get the JWT Token nout found. If I transorm /api/private/game/test in /api/public/game/test in that case the game is opened. But I need to call in private mode to know the user connected. Please help me. Thx in advance. Any ideas please ?

Access a private API after login

$
0
0

I have this security.yml :

providers:
    fos_userbundle:
        id: fos_user.user_provider.username_email

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    login:
        pattern:  ^/api/public/login
        stateless: true
        anonymous: true
        json_login:
            check_path:               /api/public/login
            success_handler:          lexik_jwt_authentication.handler.authentication_success
            failure_handler:          lexik_jwt_authentication.handler.authentication_failure
    api:
        pattern:   ^/api/private
        stateless: true
        guard:
            authenticators:
                - lexik_jwt_authentication.jwt_token_authenticator
    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            csrf_token_generator: security.csrf.token_manager
        oauth:
            resource_owners:
                facebook:         "/secured/login_facebook"
                google:           "/secured/login_google"
            login_path:        fos_user_security_login
            failure_path:      fos_user_security_login
            oauth_user_provider:
                service: app.provider.oauth
            default_target_path: /api/public/facebook/back

        logout:       true
        anonymous:    true

access_control:
    - { path: ^/login$,             role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/,             role: ROLE_ADMIN }
    - { path: ^/api/private/,       role: IS_AUTHENTICATED_FULLY }
    - { path: ^/api/public/,        role: IS_AUTHENTICATED_ANONYMOUSLY }

And I have this route :

/**
 * @Route("/api/private/game/{gameName}", name="open_game_page", methods={"GET"})
 * @Method("GET")
 * @param $gameName
 * @return
 */
public function openGameAction($gameName)
{
    $template = '';
    switch ($gameName) {
        case Game::TEST:
            $template = Game::TEST;
            break;
    }
    return $this->render('game/'.$template.'.html.twig');
}

Firts I call the api /api/public/login that returns me the jwtToken. After that If I wrote in browser : /api/private/game/test I get the JWT Token not found. If I transorm /api/private/game/test in /api/public/game/test in that case the game is opened. But I need to call in private mode to know the user connected. Please help me. Thanks in advance. Any ideas please?

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?

Symfony 4.x public dir rename to public_html

$
0
0

I got a little struggle with renaming dir to public_html for web host. According to latest tutorial I'm trying to successfully rename it, but every time when i'm trying to run local server using console command I'm getting an error: [ERROR] The document root directory ".../.../App/public" does not exist.

I'm sure that I'm doing something wrong with code. But I don't know where. I'm very beginner with Symfony.

Here's my code from composer.json:

"extra": {
    "symfony": {
        "allow-contrib": false,
        "require": "4.2.*",   
    }
    "public-dir": "public_html"
},

Did I understood something wrong with it? Thanks for help.

Symfony 4+ form validation done in a controller action?

$
0
0

I understand how constraints are applied in Form types, etc.

But in the case of implementing a password reset, I need to check for the existence of an email and error if it does not exist.

How might one achieve that in Symfony 4+?

This doesn't seem to solve my issue:

https://symfony.com/doc/current/validation/raw_values.html


The implementation of deleting from the database does not work, I can not understand why

$
0
0

I have an entity to work with the base

class Task
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

    /**
     * @ORM\Column(type="boolean", nullable=true)
     */
    private $status;

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

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

    public function getStatus(): ?bool
    {
        return $this->status;
    }

    public function setStatus(?bool $status): self
    {
        $this->status = $status;

        return $this;
    }
}

I also have a controller that works with crud of this object. In which create, update, read are implemented, but deletion does not work

    /**
     * @Route("/delete/{id}", name="delete_task")
     * @param Task $id
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function delete(Task $id)
    {
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->remove($id);
        $entityManager->flush();

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

When deleting an object from the list, it produces this error

enter image description here

How to solve this problem.

addenter image description here

How display the value of the object from the controller? [closed]

$
0
0

I want to display the details of an object (from Controller class). there is no value.

EtablissementRepository:

    public function findOneEtab($uairne): ?Etablissement
    {
      return $this->createQueryBuilder('e')
        ->where('e.uairne = :uairne')
        ->setParameter('uairne', $uairne)
        ->getQuery()
        ->getOneOrNullResult()
    ;
   }      

EtablissementController

   $etabs = $this->getDoctrine()
        ->getRepository(Etablissement::class)
        ->findOneEtab('0770002J');

index.html.twig

{% for etab in etabs %}
  {{ etab.uairne }}
{% endfor %}

{{ dump(etabs) }}

dump value

    Etablissement^ {#1657 ▼
      -id: 8
      -uairne: "0770002J"
      -nom: "COLLEGE DENECOURT                     "
    }

UPDATED I founded and thank you

index.html.twig

{{ etabs.nom }}

APP_SERVER env var not found when deploying with EasyDeploy

$
0
0

I have this error when the deploy script tries to install the assets:

(Setup PHP 7.2, Symfony 4.4)

[Symfony\Component\Process\Exception\ProcessFailedException]
The command "ssh -A root@vps.net -p 21 '(export APP_ENV=prod; cd /var/www-deploy/site.com/releases/20191129224025
&& php /var/www-deploy/site.com/releases/20191129224025/bin/console assets:install /var/www-deploy/site.com/releases/20191129224025/public --symlink --no-debug --env=prod)'" failed.
Exit Code: 1(General error)
Working directory: /Users/coil/Sites/site.com
Output:
================
Error Output:
================
In EnvVarProcessor.php line 162:
Environment variable not found: "APP_SERVER".

I have put the .env file in the shared files, so it's copied when the release directory is created, this file is in the directory.

public function configure(): DefaultConfiguration
{
    return $this->getConfigBuilder()
        // ...
        ->sharedFilesAndDirs(['.env'])
        // ...
}

I also tried to put the env vars in the .bashrc file of the user who deploys:

printenv | grep -i app
APP_DEBUG=0
APP_SECRET=whatever
APP_ENV=prod
APP_SERVER=prod

So, I don't understand, why the environment variables are still not found. And why they are not taken from the .env file. If I interrupt the deployment and if I manually run the same command on the server it works well. Thanks.

[Edit 2019-11-30] I think I understand know, when running the command, there is an export of the APP_ENV that is done. And, if the application detects this env variable it will just skip the .env file. So, I need to avoid setting this env var, or I must set all instead of this one only.

How to update OneToMany ressource

$
0
0

I am a beginner in API platform. I am working with two entities Author and Book with a OneToMany relationship:

  • a user can have several books
  • a book can belong to only one Author.

I've tried POST, GET and DELETE methods, they work. However, the PUT method does not work and returns this error:

"hydra:title": "An error occurred",

"hydra:description": **"An exception occurred while executing 'UPDATE Book SET author_id = ? WHERE id = ?' with params [null, 1]:\n\nSQLSTATE[23000]:

Integrity constraint violation: 1048 Column 'author_id' cannot be null"

Here's my code:

/**
 * @ORM\Entity(repositoryClass="App\Repository\AuthorRepository")
 * @ApiResource(
 *          normalizationContext={"groups"={"book:output"}},
 *          denormalizationContext={"groups"={"book:input"}}
 * )
 */
class Author
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @Groups({"book:input"})
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups({"book:output", "book:input"})
     */
    private $firstname;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups({"book:output", "book:input"})
     */
    private $lastname;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Book", mappedBy="author", cascade={"all"})
     * @Groups({"book:output", "book:input"})
     */
    private $books;
/**
 * @ORM\Entity(repositoryClass="App\Repository\BookRepository")
 * @ApiResource()
 */
class Book
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @Groups({"book:output", "book:input"})
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups({"book:output", "book:input"})
     */
    private $name;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Author", inversedBy="books")
     * @ORM\JoinColumn(nullable=false)
     */
    private $author;

Cannot see validation errors when form is invalid (submitted as json from react)

$
0
0

How do I see validation errors when posting json data and self submitting to a symfony form? isValid() is false but I can't access error messages to return. But the Symfony Profiler DOES show the error messages in the Ajax request history.

When all the fields are valid the new User is created in the database successfully as expected.

Here is my controller:

namespace App\Controller;

use App\Entity\User;
use App\Form\RegistrationFormType;
use App\Security\LoginFormAuthenticator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;

class RegistrationController extends AbstractController
{
    /**
     * @Route("/api/register", name="app_register")
     */
    public function register(
        Request $request,
        UserPasswordEncoderInterface $passwordEncoder,
        GuardAuthenticatorHandler $guardHandler,
        LoginFormAuthenticator $authenticator
    ): Response {
        if ($request->isMethod('POST')) {
            $user = new User();
            $form = $this->createForm(RegistrationFormType::class, $user);

            $data = json_decode($request->getContent(), true);

            $form->submit($data);

            if ($form->isSubmitted()) {
                if ($form->isValid()) {
                    $user->setPassword(
                        $passwordEncoder->encodePassword(
                            $user,
                            $form->get('plainPassword')->getData()
                        )
                    );

                    $em = $this->getDoctrine()->getManager();
                    $em->persist($user);
                    $em->flush();

                    // login the newly registered user
                    $login = $guardHandler->authenticateUserAndHandleSuccess(
                        $user,
                        $request,
                        $authenticator,
                        'main' // firewall name in security.yaml
                    );

                    if ($login !== null) {
                        return $login;
                    }

                    return $this->json([
                        'username' => $user->getUsername(),
                        'roles' => $user->getRoles(),
                    ]);
                } else {
                    $formErrors = $form->getErrors(true); // returns {}
                    return $this->json($formErrors, Response::HTTP_BAD_REQUEST);
                }
            }
        }
    }

Here is my RegistrationFormType:

namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\IsTrue;

class RegistrationFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName', TextType::class, [
                'label' => 'First Name',
                'required' => false
            ])
            ->add('lastName', TextType::class, [
                'label' => 'Last Name',
                'required' => false
            ])
            ->add('username')
            ->add('emailAddress', EmailType::class, [
                'label' => 'Email Address'
            ])
            ->add('plainPassword', PasswordType::class, [
                'mapped' => false
            ])
            ->add('agreeTerms', CheckboxType::class, [
                'mapped' => false,
                'constraints' => [
                    new IsTrue([
                        'message' => 'You must comply.',
                    ]),
                ],
            ])
            ->add('Register', SubmitType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
            'csrf_protection' => false
        ]);
    }

    public function getName()
    {
        return 'registration_form';
    }
}

Here is my entity:

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @UniqueEntity(fields={"username"}, message="There is already an account with this username")
 * @UniqueEntity(fields={"emailAddress"}, message="There is already an account with this email address")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

    /**
     * @ORM\Column(type="json")
     */
    private $roles = [];

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     */
    private $password;

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

    /**
     * @ORM\Column(type="string", length=80, nullable=true)
     */
    private $firstName;

    /**
     * @ORM\Column(type="string", length=80, nullable=true)
     */
    private $lastName;

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

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUsername(): string
    {
        return (string) $this->username;
    }

    public function setUsername(string $username): self
    {
        $this->username = $username;

        return $this;
    }

    /**
     * @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 getEmailAddress(): ?string
    {
        return $this->emailAddress;
    }

    public function setEmailAddress(string $emailAddress): self
    {
        $this->emailAddress = $emailAddress;

        return $this;
    }

    public function getFirstName(): ?string
    {
        return $this->firstName;
    }

    public function setFirstName(?string $firstName): self
    {
        $this->firstName = $firstName;

        return $this;
    }

    public function getLastName(): ?string
    {
        return $this->lastName;
    }

    public function setLastName(?string $lastName): self
    {
        $this->lastName = $lastName;

        return $this;
    }
}
Viewing all 3916 articles
Browse latest View live


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