Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions app/code/Kai/GeoIP/Block/Display.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php
namespace Kai\GeoIP\Block;

/**
* class Display
*
* Block class to display relevant templates
*
* @author Cheng Shea kai <gabazoo@gmail.com>
* @see https://github.com/bugcskai/
*/
class Display extends \Magento\Framework\View\Element\Template
{
const USA = 'US';

private $geoHandler;

private $countryCode;

public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Kai\GeoIP\Model\GeoHandler $geoHandler
)
{
$this->geoHandler = $geoHandler;

parent::__construct($context);
}

public function getCountryCode(){
return $this->countryCode;
}

protected function _toHtml()
{

$this->setCurrentBlockTemplate();
if (!$this->getTemplate()) {
return __('Nothing to Render');
}

return $this->fetchView($this->getTemplateFile());
}

/**
* Check the Country code and assign template
*
* @return void
*/
private function setCurrentBlockTemplate(){

$this->countryCode = $this->geoHandler->getUserCountryCode();

switch ($this->countryCode) {
case self::USA:
$this->setTemplate('Kai_GeoIP::us.phtml');
break;

default:
$this->setTemplate('Kai_GeoIP::global.phtml');
break;
}
}
}
91 changes: 91 additions & 0 deletions app/code/Kai/GeoIP/Model/GeoHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<?php
namespace Kai\GeoIP\Model;

/**
* class GeoHandler
*
* Does the IP checks, geolocation checks, and heavy lifting, requires http://ipstack.com API
*
* @author Cheng Shea kai <gabazoo@gmail.com>
* @see https://github.com/bugcskai/
*/
class GeoHandler
{
const IPSTACK_URL = 'http://api.ipstack.com/';

private $httpClient;

private $scopeConfig;

private $logger;

public function __construct(
\Magento\Framework\HTTP\Client\Curl $curl,
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
){
$this->httpClient = $curl;
$this->logger = $logger;
$this->scopeConfig = $scopeConfig;
}


/**
* Get The location of the current user
*
* @return string country code in ISO 3166-A2 format
*/
public function getUserCountryCode(){

$ipAddress = $this->getIPAddress();

$params = $this->buildParameters();

$url = self::IPSTACK_URL . $ipAddress . '?' . http_build_query($params);

$this->httpClient->get($url);

try {
$response = json_decode( $this->httpClient->getBody() );
return $response->country_code;
} catch (\Exception $e) {
$this->logger->error(__('Problem with ipstack'));
$this->logger->error( $e->getMessage() );
}

}

/**
* Return IP Address of user
*
* @return string IP address
*/
public function getIPAddress() {
$ipaddress = '';

if (array_key_exists('HTTP_CLIENT_IP', $_SERVER))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if (array_key_exists('HTTP_X_FORWARDED', $_SERVER))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if (array_key_exists('HTTP_FORWARDED_FOR', $_SERVER))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if (array_key_exists('HTTP_FORWARDED', $_SERVER))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if (array_key_exists('REMOTE_ADDR', $_SERVER))
$ipaddress = $_SERVER['REMOTE_ADDR'];

return $ipaddress;
}

private function buildParameters() {
$api_key = $this->scopeConfig->getValue( 'geoip/general/geoapikey', \Magento\Store\Model\ScopeInterface::SCOPE_STORE );

return [
'access_key' => $api_key,
'format' => '1',
];
}

}
53 changes: 53 additions & 0 deletions app/code/Kai/GeoIP/Plugin/BlockCountry.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace Kai\GeoIP\Plugin;

/**
* Plugin BlockCountry
*
* Blocks user if from designated countries, wrap around controller dispatch,
* try to block it as higher level as possible to prevent extra load to the server
* https://devdocs.magento.com/guides/v2.2/extension-dev-guide/routing.html
*
* @author Cheng Shea kai <gabazoo@gmail.com>
* @see https://github.com/bugcskai/
*/
class BlockCountry
{
private $geoHandler;

private $logger;

private $restrictedCountries;

public function __construct(
\Kai\GeoIP\Model\GeoHandler $geoHandler,
\Psr\Log\LoggerInterface $logger
){
$this->geoHandler = $geoHandler;
$this->logger = $logger;

$this->restrictedCountries = ['RU','CN'];
}


public function aroundDispatch(
\Magento\Framework\App\FrontControllerInterface $subject,
callable $proceed,
\Magento\Framework\App\RequestInterface $request
) {

$countryCode = $this->geoHandler->getUserCountryCode();

if ( in_array($countryCode, $this->restrictedCountries) )
{
$this->logger->info(__('User barred from site'.$this->geoHandler->getIPAddress()));

throw new \Exception(__('You are blocked from accessing the site'));
}

return $proceed($request);

}

}
21 changes: 21 additions & 0 deletions app/code/Kai/GeoIP/etc/adminhtml/system.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<tab id="kaie" translate="label" sortOrder="1">
<label>Kai Demo</label>
</tab>
<section id="geoip" translate="label" sortOrder="130" showInDefault="1" showInWebsite="1" showInStore="1">
<class>separator-top</class>
<label>GeoIP</label>
<tab>kaie</tab>
<resource>Kai_GeoIP::geoip</resource>
<group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
<label>General Configuration</label>
<field id="geoapikey" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<label>API Key</label>
<comment>This API to be used with ipstack.com.</comment>
</field>
</group>
</section>
</system>
</config>
10 changes: 10 additions & 0 deletions app/code/Kai/GeoIP/etc/config.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<geoapi>
<general>
<geoapikey>bf3b3ee9a0affbce479f174fd1a42041</geoapikey>
</general>
</geoapi>
</default>
</config>
5 changes: 5 additions & 0 deletions app/code/Kai/GeoIP/etc/di.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<type name="Magento\Framework\App\FrontControllerInterface">
<plugin name="Kai_GeoIP_Plugin_BlockCountry" type="Kai\GeoIP\Plugin\BlockCountry" sortOrder="1" disabled="false" />
</type>
</config>
4 changes: 4 additions & 0 deletions app/code/Kai/GeoIP/etc/module.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?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="Kai_GeoIP" setup_version="1.0.0"/>
</config>
11 changes: 11 additions & 0 deletions app/code/Kai/GeoIP/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
## User GeoIP and Restriction demo extension for magento 2

by Cheng Shea Kai

https://github.com/bugcskai/

- Usage: adds text block in "content" xml section to indicate country code and display a different template according to country code

- Restrict access for IP addresses from restricted countries

- Uses ipstack.com for IP location checks
6 changes: 6 additions & 0 deletions app/code/Kai/GeoIP/registration.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Kai_GeoIP',
__DIR__
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="Kai\GeoIP\Block\Display" name="geoip_display" cacheable="false"/>
</referenceContainer>
</body>
</page>
1 change: 1 addition & 0 deletions app/code/Kai/GeoIP/view/frontend/templates/global.phtml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h3><?= __('Your country code is:') ?> <?= $block->getCountryCode(); ?>, <?= __('This is the Global template.') ?></h3>
1 change: 1 addition & 0 deletions app/code/Kai/GeoIP/view/frontend/templates/us.phtml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h3><?= __('Your country code is:') ?> <?= $block->getCountryCode(); ?> <?= __('This is the US template.') ?></h3>