.Net Core application console how to hide password

I was working on a Command-line Interface (CLI) made with .Net Core.
And I ask myself how I can hide a password when the user is typing it? Like it’s the case with Linux’s Terminal.

But, in fact, It’s pretty easy

private string AskForPassword()
{
    Console.Write("Please give us your password : ");

    string password = "";
    ConsoleKeyInfo info = Console.ReadKey(true);
    while (info.Key != ConsoleKey.Enter)
    {
        if (info.Key != ConsoleKey.Backspace)
        {
            password += info.KeyChar;
            info = Console.ReadKey(true);
        }
        else if (info.Key == ConsoleKey.Backspace)
        {
            if (!string.IsNullOrEmpty(password))
            {
                password = password.Substring
                (0, password.Length - 1);
            }
            info = Console.ReadKey(true);
        }
    }

    return password;
}

The source

Posted in .Net Core

Symfony 2 – How-to check user’s role in Voter

How-to make sure in a Voter that a user has the right role in the Symfony role hierarchy.

first, two links. One to the Symfony 2 Voter’s documentation, and the second to the Access Decision Manager’s documentation.

We will see here, how to check if the current user has the right role in the roles’s hierarchy.

In a first time we have to add a service to the Voter declaration DI. We need to use the “security.access.role_hierarchy_voter” service.

Your declaration, must look like that.

<service id="security.voter.categorie" class="MyBundle\Security\Authorization\Voter\CategorieVoter" public="false">
   <argument type="service" id="security.access.role_hierarchy_voter" />
   <tag name="security.voter" />
</service>

In your Voter class you have to retrieve the service. We just need to add a new attribute, like the code below.

namespace MyBundle\Security\Authorization\Voter;

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

class CategorieVoter implements VoterInterface
{
    /**
     * @var \Symfony\Component\Security\Core\Authorization\Voter\RoleHierarchyVoter
     */
    private $roleVoter;

    public function __construct($roleVoter)
    {
            $this->roleVoter = $roleVoter;
    }
//...
}

The use of this service is pretty easy.

if($this->roleVoter->vote($token, $token->getUser(), array('ROLE_USER')) === VoterInterface::ACCESS_GRANTED) {
      // The user has the right role
}

So, now, if the current user has the role ROLE_ADMIN, according to the hierarchy of roles, he has ROLE_USER to, so the voter method return a VoterInterface::ACCESS_GRANTED

Posted in PHP, Symfony2

KnpMenuBundle the easy way breadcrumb !

In a previous post, I explain how to make a breadcrumb who work with the KnpMenuBundle.
Unfortunately this post was obsolete (and for a while). The staff of the KnpMenuBundle have deprecated the useful function getBreadcrumbsArray

I don’t find any solution, so I’ve made my own. The CnertaBreadcrumpBundle.
Now it’s a piece of cake to create a breadcrumb with KnpMenuBundle.

You can find the documentation on github.
Here, I just want to show you how to use it a bit more deeply than in the documentation.

Below the Builder class. This is just a classical builder from the KnpMenuBudle.

namespace WaldoColorfullBundleMenu;
use KnpMenuFactoryInterface;
use SymfonyComponentDependencyInjectionContainerAware;
class Builder extends ContainerAware
{
  public function mainMenu(FactoryInterface $factory, array $options)
  {
      $menu = $factory->createItem('main');
      $menu->addChild('Entrée 1', array('route' => '_route_entre_1'))
              ->addChild('Entrée 1.1', array('route' => '_route_entre_1_1'))
              ->addChild('Entrée 1.1.1', array('route' => '_route_entre_1_1_1'));
      $menu->addChild('Entrée 2', array('route' => '_route_entre_1'))
              ->addChild('Entrée 2.1', array('route' => '_route_entre_2_1'))
              ->addChild('Entrée 2.1.1', array('route' => '_route_entre_2_1_1'));
      return $menu;
  }
}

In this class we just put a classical menu definition.
Now if we want to render a breadcrumb in our Twig template, let me show you how too easy it is.

{{ cnerta_breadcrumb_render('WaldoColorfullBundle:Builder:mainMenu') }}

Thats all. You just have to call the Helper cnerta_breadcrumb_render and give the path of your menu. Like the KnpMenuBundle.
Too easy ?
Now, if you want to customize your beardcrump in your template :

{% set currentItem = cnerta_breadcrumb_get('WaldoColorfullBundle:Builder:mainMenu') %}
{% for item in currentItem %}
   {% if loop.index != 1 %}
       {% if loop.index > 2 %} > {% endif %}
       {% if not loop.last %}<a href="{{ item.uri }}">{{ item.label }}</a>
       {% else %}<span>{{ item.label }}</span>{% endif %}
   {% endif %}
{% endfor %}

You just need to call The Helper cnerta_breadcrumb_get and give the path of your menu.
But if you want a clean code, you have to put your breadcrumb template in a separate file. To specifies the template, it’s like the KnpMenuBundle, you have to give an option array with the template path.

{{ cnerta_breadcrumb_render('WaldoColorfullBundle:Builder:mainMenu', {'template': 'MyWonderfullBundle:Breadcrumb:myBreadcrumb.html.twig'}) }}

The code and the architecture come from a big part from the KnpMenu and the KnpMenuBundle. This bundle is not perfect but it make the job.

Posted in Symfony2

PHP Behind a proxy server

Note : In this post, a proxy is a software running on a server. This software filter incoming and outgoing flow of the netwok to internet. And if a desktop want to go on the internet it must be configured for use this proxy server.

PHP behind a proxy server is just a pain in the ass to configure. It’s not possible to configure in one place the informations of proxy connection.

Some examples:
SoapClient, SoapServer, CURL take configuration information in its parameters.
Functions from the file_get_contents family can take configuration information in its parameters or have a global configuration through the application.
And the other, who take any configuration like exif_imagetype.

The question is, how to configure PHP for use a proxy server in a easy manner ?

Take a deep breath, and Allons-Y !

If you use Symfony2, you can use a really wonderful BehindAProxyBundle (yes I made it), and read the documentation.
In the other case you can use the code from the ProxyService.php.

What does the ProxyService Class?
This class centralizes the connection configuration options for some functions.
It is what it takes for SOAP connections, CURL, or stream context.

What for the function who can’t take configuration options ?

The palliative solution for this problem is to download the distant file in a temporary file on the server. Let me show you an example.

In the case below, we don’t use any external library.

function loadFileTemporarily($url) {

// Our stream Context
$context = array(
               'http' => array(
                   'proxy' => 'tcp://172.0.0.1:8080',
                   'request_fulluri' => true,
               )
           );
$cxContext = stream_context_create($context);

$tmpfile = file_get_contents($file, false , $cxContext);

              // Writing the retrieved content to a temporary file
           $tempStreamFile = tmpfile();
           fwrite($tempStreamFile, $tmpfile);
           fseek($tempStreamFile, 0);

    // Retrieving information in relation to this temporary file
    $streamMetadData = stream_get_meta_data($tempStreamFile);

    // We return the uri
           return $streamMetadData['uri'];
}

echo “<pre>”;
print_r(
exif_imagetype(
loadFileTemporarily( “http://lost.com//a-picture.jpg” )
)
);
echo “</pre>”;

I’ve used this type of code in a fork of ImageBundle made by Grewar.

How to configure the stream context in a global manner?

For the PHP’s functions who use stream context, it’s possible to define the proxy server connection options in a global manner.
For that we use the function stream_context_set_default. This function must be place in a configuration file. The same file where you write the database connection.

Below, an implementation example :

$context = array(
               'http' => array(
                   'proxy' => 'tcp://127.0.0.1:8080',
                   'request_fulluri' => true,
               )
           );
stream_context_set_default($context);
Posted in PHP, Symfony2

Une Langue en particulier ?

Un peu de Pub?