Magento 2.1 – How to Generate Random Password for Customer

customermagento-2.1password

We had a method to generate the random passwords for the customers in Magento1 in following class.

app\code\core\Mage\Customer\Model\Customer.php

method >>

 /**
     * Retrieve random password
     *
     * @param   int $length
     * @return  string
     */
    public function generatePassword($length = 8)
    {
        $chars = Mage_Core_Helper_Data::CHARS_PASSWORD_LOWERS
            . Mage_Core_Helper_Data::CHARS_PASSWORD_UPPERS
            . Mage_Core_Helper_Data::CHARS_PASSWORD_DIGITS
            . Mage_Core_Helper_Data::CHARS_PASSWORD_SPECIALS;
        return Mage::helper('core')->getRandomString($length, $chars);
    }

What is the similar method in Magento2?

Best Answer

I used the following code to generate the passwords for the customers.

<?php
namespace Muk\Common\Helper;

class CustomerPasswordGeneration extends \Magento\Framework\App\Helper\AbstractHelper
{

    /**
     * @var \Magento\Framework\Math\Random
     */
    protected $mathRandom;

    public function __construct(
        Context $context,
        \Magento\Framework\Math\Random $mathRandom
    ) {        
        $this->mathRandom = $mathRandom;
        parent::__construct($context);
    }

    /**
     * Retrieve random password
     *
     * @param   int $length
     * @return  string
     */
    public function generatePassword($length = 10)
    {
        $chars = \Magento\Framework\Math\Random::CHARS_LOWERS
            . \Magento\Framework\Math\Random::CHARS_UPPERS
            . \Magento\Framework\Math\Random::CHARS_DIGITS;

        return $password = $this->mathRandom->getRandomString($length, $chars);
    }
Related Topic