Intro To Magento 2, Part 6: Personalizing Data & Securing User Pages

You have all the tools you need to build a custom module that will show database stored data to your users. They can even manage that data. Now let’s talk about personalizing data and securing user pages. The last step to this is securing the data so only your authenticated users can see their own data.

1. What do we need to change?

Here is our file structure:

app/code/Danjoseph/Helloworld/Blocks/Helloworld.php
app/code/Danjoseph/Helloworld/Controller/Index/Index.php
app/code/Danjoseph/Helloworld/Controller/Crud/Create.php
app/code/Danjoseph/Helloworld/Controller/Crud/Update.php
app/code/Danjoseph/Helloworld/Controller/Crud/Delete.php
app/code/Danjoseph/Helloworld/etc/module.xml
app/code/Danjoseph/Helloworld/etc/frontend/routes.xml
app/code/Danjoseph/Helloworld/Model/Hello.php
app/code/Danjoseph/Helloworld/Model/ResourceModel/Hello.php
app/code/Danjoseph/Helloworld/Model/ResourceModel/Hello/Collection.php
app/code/Danjoseph/Helloworld/view/frontend/layout/customer_account.xml
app/code/Danjoseph/Helloworld/view/frontend/layout/helloworld_index_index.xml
app/code/Danjoseph/Helloworld/view/frontend/templates/helloworld.phtml
app/code/Danjoseph/Helloworld/Setup/InstallSchema.php
app/code/Danjoseph/Helloworld/Setup/UpgradeSchema.php
app/code/Danjoseph/Helloworld/registration.php

We’re going to update two and then introduce one new file:

app/code/Danjoseph/Helloworld/Blocks/Helloworld.php
app/code/Danjoseph/Helloworld/Setup/InstallSchema.php
app/code/Danjoseph/Helloworld/Setup/UpgradeSchema.php

2. How do we get the session and work with it?

Magento makes it very easy to see if there is a user session established.

app/code/Danjoseph/Helloworld/Blocks/Helloworld.php

<?php

namespace Danjoseph\Helloworld\Block;

use Magento\Framework\View\Element\Template;

class Helloworld extends \Magento\Framework\View\Element\Template
{
    public function __construct( \Magento\Framework\View\Element\Template\Context $context )
    {
        parent::__construct($context);
    }

    protected function _prepareLayout()
    {
        $this->pageConfig->getTitle()->set(__('My Greetings'));
    }

    public function getGreetings()
    {
        $this->_isScopePrivate = true;

        $objectManagerr   = \Magento\Framework\App\ObjectManager::getInstance();

        $customerSession  = $objectManagerr->get('Magento\Customer\Model\Session');
        $greetingsFactory = $objectManagerr->create( 'Danjoseph\Helloworld\Model\Helloworld' );

	$id               = $customerSession->getCustomerId();
        $data             = $greetingsFactory ->getCollection()->addFieldToFilter('customerid', $id);;

        return $data;
    }
}

There are three lines that we added.

First, the $customerSession object was instantiated. This will give us access to the session, and let us get the id.

Second, $id was populated with the current user session.

Finally, we added a filter to our collection. This is how we add a WHERE to our SQL.

Next, let’s modify our install schema:

app/code/Danjoseph/Helloworld/Setup/InstallSchema.php

<?php

namespace Danjoseph\Helloworld\Setup;

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

class InstallSchema implements InstallSchemaInterface
{
    public function install( SchemaSetupInterface $setup, ModuleContextInterface $context )
    {
        $setup->startSetup();

        $table = $setup->getConnection()->newTable(
            $setup->getTable('danjoseph_greetings')
        )->addColumn(
            'greetings_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            null,
            ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
            'Greetings ID'
        )->addColumn(
            'greeting_text',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            [],
            'Greeting Text'
        )->addColumn(
            'customerid',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            null,
            [],
            'Customer ID'
         )->setComment(
            'Greetings Table'
        );
        $setup->getConnection()->createTable($table);

        $setup->endSetup();
    }
}

Here we add another column to our install schema. This is the approach you would take if you were installing this module from the beginning. We are not, so there are two approaches you can take. You can manually add a column called “customerid” to your database table. The proper way to update your table would be through an upgrade schema script.

Like the install schema script, the setup scheme script will run when you update your module database. Let’s take a look at what it would look like.

app/code/Danjoseph/Helloworld/Setup/UpgradeSchema.php

<?php
 
namespace Danjoseph\Helloworld\Setup;

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

class UpgradeSchema implements  UpgradeSchemaInterface
{
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
    
        if ( version_compare( $context->getVersion(), '1.0.1' ) < 0 ) 
        {
            $tableName = $setup->getTable('danjoseph_greetings');

            if ( $setup->getConnection()->isTableExists( $tableName ) == true ) 
            {
                $columns = [
                    'customerid' => [
                        'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                        'nullable' => false,
                        'comment' => 'Customer ID',
                    ],
                ];

                $connection = $setup->getConnection();

                foreach ($columns as $name => $definition) 
                {
                    $connection->addColumn( $tableName, $name, $definition );
                }

            }
        }

        $setup->endSetup();
    }
}

Let’s examine this. First, I’m checking if the table “danjoseph_greetings” is there. Then, I’m building my columns. In this situation we’re only adding the one. Finally, I’m looping through and adding them to the database table. You can add as many as you want. For this tutorial, we’re just adding customerid.

If you have any entries in your table, you’ll need to go in and add your customer ID to each greeting.

3. How do I make this work?

Finally, you’re going to tell Magento to run your upgrade schema script.

% php bin/magento setup:update

This will update the version of your module with Magento and add your customerid column to the database table.

Securing user pages is as simple as adding some code and giving your database table a reference for the id. There are many more security aspects to this that you should investigate. Your delete and update controllers need some checks and validation. Plus when you create you are going to need to tell the code to save the customerid to the database.

As a challenge, I am going to leave that for you to explore and install. If you have any questions, you can comment below.

Written by Dan
Welcome to my blog! Here you'll find my collection of bible study lessons, book reviews, and other posts I feel inspired to write. I am a Christian currently serving at First Baptist Church of Northville in Northville, MI.