How to use magento 1 customer password in magento 2

 Magento 1 use MD5 hash to encrypt the password and Magento 2 use SHA-256.

In Magento 1, they use Mage_Core_Model_Encryption class with following functions.

Magento 1 generate hash by md5(salt + password) and save in database with 1 colon like $password-hash : $salt.

Magento 2 has changed logic and written in vendor/magento/framework/Encryption/Encryptor.php

Magento 2 generate hash like hash(‘sha256’, $salt . $password); and save with 2 colons in database like

$password-hash : $salt: $version

You have to override Encryptor class via di.xml with some private functions in your module.


/**

 * Class Encryptor provides basic logic for hashing strings and encrypting/decrypting misc data

 */

class Encryptor extends \Magento\Framework\Encryption\Encryptor

{

/**

* @var array map of hash versions

*/

private $hashVersionMap = [

self::HASH_VERSION_MD5 => 'md5',

self::HASH_VERSION_SHA256 => 'sha256'

];

/**

* @var array map of password hash

*/

private $passwordHashMap = [

self::PASSWORD_HASH => '',

self::PASSWORD_SALT => '',

self::PASSWORD_VERSION => self::HASH_VERSION_LATEST

];

/**

* @param string $hash

* @return array

*/

private function explodePasswordHash($hash)

{

$explodedPassword = explode(self::DELIMITER, $hash, 3);

foreach ($this->passwordHashMap as $key => $defaultValue) {

$this->passwordHashMap[$key] = (isset($explodedPassword[$key])) ? $explodedPassword[$key] : $defaultValue;

}

return $this->passwordHashMap;

}

/**

* @return string

*/

private function getPasswordHash()

{

return (string)$this->passwordHashMap[self::PASSWORD_HASH];

}

/**

* @return string

*/

private function getPasswordSalt()

{

return (string)$this->passwordHashMap[self::PASSWORD_SALT];

}

/**

* @return array

*/

private function getPasswordVersion()

{

return array_map('intval', explode(self::DELIMITER, $this->passwordHashMap[self::PASSWORD_VERSION]));

}

    /**

     * @inheritdoc

     */

    public function isValidHash($password, $hash)

    {

        $this->explodePasswordHash($hash);

        

        $hashs = explode(":", $hash);

        if(count($hashs) == 2){

        $password = md5($this->getPasswordSalt() . $password);

        }

        else{

        foreach ($this->getPasswordVersion() as $hashVersion) {

        $password = $this->hash($this->getPasswordSalt() . $password, $hashVersion);

        }

        }

        

        //print $password . " ". $this->getPasswordHash(); die;


        return Security::compareStrings(

            $password,

            $this->getPasswordHash()

        );

    }

}

 

Now Magento 1 user will able to login their old password. New customers password logic will remain same.

Magento 2 : How do create Setup/InstallSchema.php?

Install Script: InstallSchema & InstallData

The InstallSchema and InstallData classes will be run during the module install.
The InstallSchema setup script in magento 2 will be use to change the database schema (create or change database table). This’s the setup script to create the m2commerce_adminlog_post table:
File: app/code/M2commerce/Adminlog/Setup/InstallSchema.php
<?php

namespace M2commerce\Adminlog\Setup;

class InstallSchema implements \Magento\Framework\Setup\InstallSchemaInterface
{

 public function install(\Magento\Framework\Setup\SchemaSetupInterface $setup, \Magento\Framework\Setup\ModuleContextInterface $context)
 {
  $installer = $setup;
  $installer->startSetup();
  if (!$installer->tableExists('m2commerce_adminlog_post')) {
   $table = $installer->getConnection()->newTable(
    $installer->getTable('mageplaza_helloworld_post')
   )
    ->addColumn(
     'post_id',
     \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
     null,
     [
      'identity' => true,
      'nullable' => false,
      'primary'  => true,
      'unsigned' => true,
     ],
     'Post ID'
    )
    ->addColumn(
     'name',
     \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
     255,
     ['nullable => false'],
     'Post Name'
    )
    ->addColumn(
     'url_key',
     \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
     255,
     [],
     'Post URL Key'
    )
    ->addColumn(
     'post_content',
     \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
     '64k',
     [],
     'Post Post Content'
    )
    ->addColumn(
     'tags',
     \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
     255,
     [],
     'Post Tags'
    )
    ->addColumn(
     'status',
     \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
     1,
     [],
     'Post Status'
    )
    ->addColumn(
     'featured_image',
     \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
     255,
     [],
     'Post Featured Image'
    )
    ->addColumn(
     'created_at',
     \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
     null,
     ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
     'Created At'
    )->addColumn(
     'updated_at',
     \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
     null,
     ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE],
     'Updated At')
    ->setComment('Post Table');
   $installer->getConnection()->createTable($table);

   $installer->getConnection()->addIndex(
    $installer->getTable('mageplaza_helloworld_post'),
    $setup->getIdxName(
     $installer->getTable('mageplaza_helloworld_post'),
     ['name', 'url_key', 'post_content', 'tags', 'featured_image'],
     \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
    ),
    ['name', 'url_key', 'post_content', 'tags', 'featured_image'],
    \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
   );
  }
  $installer->endSetup();
 }
}
Looking into this file we will see:
The class must extend \Magento\Framework\Setup\InstallSchemaInterface
The class must have install() method with 2 arguments SchemaSetupInterface and ModuleContextInterface. The SchemaSetupInterface is the setup object which provide many function to interact with database server. The ModuleContextInterface has only 1 method getVersion() which will return the current version of your module.
In the example above, we create a table named m2commerce_adminlog_post with columns: post_id, name, post_content, created_at ....
InstallData will be run after the InstallSchema class to add data to the database table.
File: app/code/M2commerce/Adminlog/Setup/InstallData.php
<?php

namespace m2commerce\Adminlog\Setup;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{
 protected $_postFactory;

 public function __construct(\M2commerce\Adminlog\Model\PostFactory $postFactory)
 {
  $this->_postFactory = $postFactory;
 }

 public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
 {
  $data = [
   'name'         => "How to Create SQL Setup Script in Magento 2",
   'post_content' => "In this article, we will find out how to install and upgrade sql script for module in Magento 2. When you install or upgrade a module, you may need to change the database structure or add some new data for current table. To do this, Magento 2 provide you some classes which you can do all of them.",
   'url_key'      => '/magento-2-module-development/magento-2-how-to-create-sql-setup-script.html',
   'tags'         => 'magento 2,m2commerce helloworld',
   'status'       => 1
  ];
  $post = $this->_postFactory->create();
  $post->addData($data)->save();
 }
}
This class will have the same concept as InstallSchema.

Upgrade Script: UpgradeSchema & UpgradeData

The both of this files will run when the module is installed or upgraded. This classes is difference with the Install classes because they will run every time the module upgrade. So we will need to check the attribute setup_version in module.xml at app/code/M2commerce/Adminlog/etc/ and separate the script by each version.
In this example, we will change the attrubute setup_version to 1.2.0
File: app/code/M2commerce/Adminlog/etc/module.xml
Contents would be:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="M2commerce_Adminlog" setup_version="1.2.0">
    </module>
</config>

Upgrade Schema:

File: app/code/M2commerce/Adminlog/Setup/UpgradeSchema.php
<?php
namespace M2commerce\Adminlog\Setup;

use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;

class UpgradeSchema implements UpgradeSchemaInterface
{
 public function upgrade( SchemaSetupInterface $setup, ModuleContextInterface $context ) {
  $installer = $setup;

  $installer->startSetup();

  if(version_compare($context->getVersion(), '1.2.0', '<')) {
   $installer->getConnection()->addColumn(
    $installer->getTable( 'mageplaza_helloworld_post' ),
    'test',
    [
     'type' => \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
     'nullable' => true,
     'length' => '12,4',
     'comment' => 'test',
     'after' => 'status'
    ]
   );
  }



  $installer->endSetup();
 }
}

In this class, we use the upgrade() method which will be run every time the module is upgraded. We also have to compare the version to add the script for each version.

Upgrade Data:

This will same with the UpgradeSchema class
File: app/code/M2commerce/Adminlog/Setup/UpgradeData.php
<?php

namespace M2commerce\Adminlog\Setup;

use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;

class UpgradeData implements UpgradeDataInterface
{
 protected $_postFactory;

 public function __construct(\M2commerce\Adminlog\Model\PostFactory $postFactory)
 {
  $this->_postFactory = $postFactory;
 }

 public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
 {
  if (version_compare($context->getVersion(), '1.2.0', '<')) {
   $data = [
    'name'         => "Magento 2 Events",
    'post_content' => "This article will talk about Events List in Magento 2. As you know, Magento 2 is using the events driven architecture which will help too much to extend the Magento functionality. We can understand this event as a kind of flag that rises when a specific situation happens. We will use an example module Mageplaza_HelloWorld to exercise this lesson.",
    'url_key'      => '/magento-2-module-development/magento-2-events.html',
    'tags'         => 'magento 2,mageplaza helloworld',
    'status'       => 1
   ];
   $post = $this->_postFactory->create();
   $post->addData($data)->save();
  }
 }
}

Recurring Script

The recurring script is a script which will be run after the module setup script every time the command line php bin/magento setup:upgrade run.
This script will be defined same as InstallSchema class but difference in name of the class. The example for this class you can see in vendor/magento/module-indexer/Setup/Recurring.php

Uninstall Script

Magento 2 provide us the uninstall module feature which will remove all of the table, data like it hadn’t installed yet. This’s the example for this class:
File: app/code/M2commerce/Adminlog/Setup/Uninstall.php
<?php
namespace Mageplaza\HelloWorld\Setup;

use Magento\Framework\Setup\UninstallInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;

class Uninstall implements UninstallInterface
{
 public function uninstall(SchemaSetupInterface $setup, ModuleContextInterface $context)
 {
  $installer = $setup;
  $installer->startSetup();

  $installer->getConnection()->dropTable($installer->getTable('m2commerce_adminlog_post'));

  $installer->endSetup();
 }
}

Magento 2.x | Steps for create a new module

Module is a structural element of Magento 2 – the whole system is built upon modules. Typically, the first step in creating a customization is building a module.
To create a module, you have to complete the following high-level steps:
  1. Create the module folder e.g VendorName/ModuleName.
  2. Create the VendorName/ModuleName/etc/module.xml file.
  3. Create the VendorName/ModuleName/registration.php file.
  4. Run the bin/magento setup:upgrade script to install the new module.
  5. Check that the module is working.
Let’s go through each of these steps in detail.

Create the module folder

There are two possible locations for modules in Magento 2: the app/code folder and the vendor folder

Depending on how Magento 2 has been installed, core modules can either be located in the vendor/magento/magento-*folders (for composer installation) or in the app/code/Magento/ folder (for cloning GitHub).

Which of these locations should you choose for your new module?

If you build a module for a specific project, it is best to choose the app/code folder and commit to the project’s repository.
If you build an extension to be reused, it is better to use composer to create it, and put your module in the vendor/<YOUR_VENDOR>/module-something folder.
Each module name in Magento 2 consists of two parts – the vendor and the module itself. In other words, modules are grouped into vendors, so you need to define the vendor and module names. For this example, let’s name the vendor “Learning” and the module “FirstUnit”.
Let’s create the folder app/code/Learning and inside this folder place another folder: FirstUnit. If you’re using the command line, the code would be:
  1. cd to the root folder
  2. mkdir app/code/Learning
  3. mkdir app/code/Learning/FirstUnit

Make sure you have permission to create files and folders in your installation

Next, you need to create an etc/module.xml file. This file is required for the module to exist.
This file contains the following information:
  • Module name
  • Module version
  • Dependencies
Module name is defined by the folders we just created, because in Magento 2, class names must follow the folder structure. Because we created the folders Learning/FirstUnit, our module name will be Learning_FirstUnit and all classes that belong to this module will begin with Learning\FirstUnit – for example: Learning\FirstUnit\Observer\Test.
Module version indicates the current version of the database schema and data, and is used in upgrading. For example, assume you decide to modify a table’s schema in your module. How can you be sure that this change will happen on all instances where the code is deployed? Altering the database by direct SQL queries won’t work. Instead, Magento 2 has install and upgrade scripts in every module (optionally). These scripts contain commands to modify the database schema or data. To track whether to execute a script or not, Magento 2 uses module versions. Every time you implement a new database change, you implement a new version of a module and change the corresponding module.xml. Magento saves the current module’s version in a database, and if the database value and the one in the module.xml do not match, it will execute the upgrade code.
Dependencies. If one module depends on another, the module.xml file will have a special declaration that defines a list of modules that the current module depends on. For this example, we will make our module dependent on Magento_Catalog.
Using the following command-line code, create the folder app/code/Learning/FirstUnit/etc:
mkdir app/code/Learning/FirstUnit/etc
Then put the following code into it:
1
2
3
4
5
6
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Learning_FirstUnit" setup_version="0.0.1"> <sequence>
<module name="Magento_Catalog"/> </sequence>
    </module>
</config>
Note that in the XML file we specified:
  • Module name: Learning_FirstUnit (based on the folders we created)
  • Version: 0.0.1 (initial version of our module)
  • Dependency: Magento_Catalog. We could have multiple dependencies. In this case, we would put <module name=”..” /> nodes under the sequence node.

Create the registration.php file

Each module must have this file, which tells Magento how to locate the module. Continuing our example, create the file app/code/Learning/FirstUnit/registration.php. Then put the following content into it:
1
2
3
4
<?php \Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE, 'Learning_FirstUnit',
__DIR__
);
The registration.php is a standardized file that follows the same pattern for all modules.
The only thing that varies is the module name, which in our case is Learning_FirstUnit.

Run the “setup:upgrade” command

Running this command makes your new module active, notifying Magento of its presence.
php bin/magento setup:upgrade
It should echo a large amount of output, one line of which should be Learning_FirstUnit. Verify that this line of code is there.

Check that the new module is active

So far, we haven’t added any useful code to our module – it is still empty (and therefore invisible). In order to verify that it has been recognized, check the file app/etc/config.php. It has a list of auto-generated modules that are active.
Never change this list manually!
grep Learning_FirstUnit app/etc/config.php
Employing these steps, you can successfully create a new module in Magento 2.

Mysql create Database and give permission to user to access and write privilege.

Login in mysql command

mysql -u root -p


Create database command

CREATE DATABASE m2;


Grant privilege

GRANT ALL PRIVILEGES ON m2.* TO 'root'@'localhost';

Create a Linux Swap File

Swap is a space on a disk that is used when the amount of physical RAM memory is full. When a Linux system runs out of RAM, inactive pages are moved from the RAM to the swap space.
Swap space can take the form of either a dedicated swap partition or a swap file. In most cases, when running Linux on a virtual machine, a swap partition is not present, so the only option is to create a swap file.
This tutorial was tested on Linux systems with Ubuntu 18.04 and CentOS 7, but it should work with any other Linux distribution.

How to add Swap File


Follow these steps to add 1GB of swap to your server. If you want to add 2GB instead of 1 GB, replace 1G with 2G.

1. Create a file that will be used for swap:
sudo fallocate -l 1G /swapfile
If faillocate is not installed or if you get an error message saying fallocate failed: Operation not supported then you can use the following command to create the swap

file:
sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576


2. Only the root user should be able to write and read the swap file. To set the correct permissions type:
sudo chmod 600 /swapfile

3. Use the mkswap utility to set up the file as Linux swap area:
sudo mkswap /swapfile

4. Enable the swap with the following command:
sudo swapon /swapfile
To make the change permanent open the /etc/fstab file and append the following line:
/etc/fstab
/swapfile swap swap defaults 0 0

5. To verify that the swap is active, use either the swapon or the free command as shown below:
sudo swapon --show

Output
NAME      TYPE  SIZE   USED PRIO
/swapfile file 1024M 507.4M   -1

sudo free -h


How to check if Magento is running in production mode or developer mode

If you want to know. your Magento 2 website is running on which environment you can run below command on terminal and very easily you can kn...

Popular Posts

Posts