Prestashop - Integrate Bizum method - php

I am trying to integrate the BIZUM payment method in a prestashop store and for this I have installed the payment method addon "redsys" and I am modifying it, for what I have done is take the file redsys.php from the module and modify it by this code
/*
* HOOK V1.7
*/
public function hookPaymentOptions($params) {
if (! $this->active) {
return;
}
if (! $this->checkCurrency ( $params ['cart'] )) {
return;
}
$this->createParameter($params);
$urlBizum = 'https://sis-t.redsys.es:25443/sis/realizarPago';
$newOption2 = new \PrestaShop\PrestaShop\Core\Payment\PaymentOption();
$newOption2->setCallToActionText ($this->l('Pago con Bizum' ))
->setAction ($urlBizum)
->setInputs([
'Ds_SignatureVersion' => [
'name' =>'Ds_SignatureVersion',
'type' =>'hidden',
'value' =>$this->version2,
],
'Ds_MerchantParameters' => [
'name' =>'Ds_MerchantParameters',
'type' =>'hidden',
'value' =>$this->paramsBase64,
],
'Ds_Signature' => [
'name' =>'Ds_Signature',
'type' =>'hidden',
'value' => $this->signatureMac,
],
'Ds_Merchant_PayMethods' => [
'name' =>'Ds_Merchant_PayMethods',
'type' =>'hidden',
'value' => 'z',
],
]);
$payment_options = [$newOption2];
return $payment_options;
}
The problem I have is that I get the redsys TVP screen ... and not the bizum I'm waiting for.
Thank you

Related

How to make username case insensitive in zf2

I used zf2 authentication for authenticate user in my project.I saved Harib in my user table as user name but if i use my user name Harib then its accept or if i use harib then its not accept,i want to remove case sensitivity of user name so both Harib or harib access how i fix this?
Here is my code:
public function loginAction()
{
$this->layout('layout/login-layout.phtml');
$login_error = false;
$loginForm = new LoginForm();
$form_elements = json_encode($loginForm->form_elements);
if ($this->request->isPost()) {
$post = $this->request->getPost();
$loginForm->setData($post);
if ($loginForm->isValid()) {
$hashed_string = '';
if(
array_key_exists('hashed_input' , $post) &&
$post['hashed_input'] != '' &&
strpos(urldecode($this->params('redirect')) , 'programdetailrequest') !== false
) {
$hashed_string = $post['hashed_input'];
}
$data = $loginForm->getData();
$authService = $this->getServiceLocator()->get('doctrine.authenticationservice.odm_default');
$adapter = $authService->getAdapter();
$adapter->setIdentityValue($data['username']);
$adapter->setCredentialValue(md5($data['password']));
$authResult = $authService->authenticate();
if($authResult->isValid()){
$identity = $authResult->getIdentity();
if( is_object($identity) && method_exists($identity, 'getData') ){
$user_data = $identity->getData();
$authService->getStorage()->write($identity);
// for remeber checkbox
if ($post['rememberme']) {
$token = new UserToken();
$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
//if same user already running from other browser then remove previous token.
$check_token = $dm->getRepository('Admin\Document\UserToken')->findOneBy(array( "user_id.id" => $user_data['id'] ));
if (is_object($check_token) && !is_null($check_token)) {
$remove_token = $dm->createQueryBuilder('Admin\Document\UserToken')
->remove()
->field('id')->equals($check_token->id)
->getQuery()->execute();
}
//create token
$user = $dm->getRepository('Admin\Document\User')->findOneBy(array( "id" => $user_data['id'] ));
$token->setProperty('user_id', $user);
$token->setProperty('dataentered', new \MongoDate());
$dm->persist($token);
$dm->flush($token);
//create cookie
if(is_object($token) && property_exists($token, 'id')){
$time = time() + (60 * 60 * 24 * 30); // 1 month
setcookie('token', $token->getProperty('id'), $time, '/');
}
}
if ($user_data['user_type'] == 'onlinemarketer') {
$this->redirect()->toRoute('admin_program_meta');
} elseif ($user_data['user_type'] == 'bucharestofficemanager') {
$this->redirect()->toRoute('admin_program_detail_request');
} else {
if ($this->params('redirect') && urldecode($this->params('redirect')) !== '/logout/') {
$server_url = $this->getRequest()->getUri()->getScheme() . '://' . $this->getRequest()->getUri()->getHost().urldecode($this->params('redirect') . $hashed_string);
return $this->redirect()->toUrl($server_url);
}
return $this->redirect()->toRoute('admin_index');
}
}
} else {
$identity = false;
$login_error = true;
}
}
}
return new ViewModel(array(
'loginForm' => $loginForm,
'form_elements' =>$form_elements,
'login_error' => $login_error,
));
}
and here is my login form code:
<?php
namespace Admin\Form;
use Zend\Form\Form;
use Zend\Form\Element;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
class LoginForm extends Form implements InputFilterAwareInterface
{
protected $inputFilter;
public $form_elements = array(
array(
'name' => 'username',
'attributes' => array(
'id' => 'username',
'type' => 'text',
'error_msg' => 'Enter Valid Username',
'data-parsley-required' => 'true',
'data-parsley-pattern' => '^[a-zA-Z0-9_\.\-]{1,50}$',
'data-parsley-trigger' => 'change'
),
'options' => array(
'label' => 'User Name'
),
'validation' => array(
'required'=>true,
'filters'=> array(
array('name'=>'StripTags'),
array('name'=>'StringTrim')
),
'validators'=>array(
array('name'=>'Regex',
'options'=> array(
'pattern' => '/^[a-z0-9_.-]{1,50}+$/', // contain only a to z 0 to 9 underscore, hypen and space, min 1 max 50
'pattern_js' => '^[a-zA-Z0-9_\.\-]{1,50}$'
)
)
)
)
),
array(
'name' => 'password',
'attributes' => array(
'id' => 'password',
'type' => 'password',
'error_msg' => 'Enter Valid Password',
'data-parsley-required' => 'true',
'data-parsley-pattern' => '^[a-zA-Z0-9_\.\-]{6,25}$',
'data-parsley-trigger' => 'change'
),
'options' => array(
'label' => 'Password'
),
'validation' => array(
'required' => true,
'filters'=> array(
array('name'=>'StripTags'),
array('name'=>'StringTrim')
),
'validators'=>array(
array('name'=>'Regex',
'options'=> array(
'pattern' => '/^[a-z0-9_.-]{6,25}+$/', // contain only a to z 0 to 9 underscore, hypen and space, min 1 max 50
'pattern_js' => '^[a-zA-Z0-9_\.\-]{6,25}$'
)
)
)
)
),
array(
'name' => 'hashed_input',
'attributes' => array(
'type' => 'hidden',
'id' => 'hashed_input',
'value' => ''
)
),
array(
'name' => 'rememberme',
'attributes' => array(
'value' => 1,
'id' => 'rememberme',
'type' => 'Checkbox'
),
'options' => array(
'label' => 'Remember Me',
'use_hidden_element' => false,
)
),
array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Log in',
'id' => 'submitbutton'
)
)
);
public function __construct()
{
parent::__construct('user');
$this->setAttribute('method', 'post');
$this->setAttribute('data-parsley-validate', '');
$this->setAttribute('data-elements', json_encode($this->form_elements));
$this->setAttribute('autocomplete', 'off');
for($i=0;$i<count($this->form_elements);$i++){
$elements=$this->form_elements[$i];
$this->add($elements);
}
}
public function getInputFilter($action=false)
{
if(!$this->inputFilter){
$inputFilter = new InputFilter();
$factory = new InputFactory();
for($i=0;$i<count($this->form_elements);$i++){
if(array_key_exists('validation',$this->form_elements[$i])){
$this->form_elements[$i]['validation']['name']=$this->form_elements[$i]['name'];
$inputFilter->add($factory->createInput( $this->form_elements[$i]['validation'] ));
}
}
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
how we remove case sensitivity of user name so both Harib or harib accepted?
Add a filter StringToLower in your loginform on the element user_id.
For this, the class that defines your loginform must implement InputFilterProviderInterface and you must add in the getInputFilterSpecification method as follows :
public function getInputFilterSpecification()
{
return [
'username' => [
'name' => 'username',
'required' => true,
'filters' => [
'name' => 'StringToLower',
'name'=>'StripTags',
'name'=>'StringTrim'
],
validators => [
[
'name'=>'Regex',
'options'=> [
'pattern' => '/^[a-z0-9_.-]{1,50}+$/',
'pattern_js' => '^[a-zA-Z0-9_\.\-]{1,50}$'
]
]
]
],
'password' => [
'name' => 'password',
'required' => true,
'filters' => [
array('name'=>'StripTags'),
array('name'=>'StringTrim')
],
'validators' => [
[
'name'=>'Regex',
'options'=> [
'pattern' => '/^[a-z0-9_.-]{6,25}+$/',
'pattern_js' => '^[a-zA-Z0-9_\.\-]{6,25}$'
]
]
]
]
];
}
So you are assured that the value returned in the post is in lowercase.
Since you're using MongoDB, you could use a regex to get the user name from the database.
Suggestion 1:
In your example that would be:
db.stuff.find( { foo: /^bar$/i } );
Suggestion 2:
You can Use $options => i for case insensitive search. Giving some possible examples required for string match.
Exact case insensitive string
db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}})
Contains string
db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})
Start with string
db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}})
End with string
db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})
Doesn't Contains string
db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})
More about regex in MongoDb here: https://docs.mongodb.com/manual/reference/operator/query/regex/index.html
You may do this in two ways. Either you may create a custom authentication adapter or override a method of the default authentication adapter. I recommend that override that method which is easier than creating custom adapter.
So here is the method CredentialTreatmentAdapter::authenticateCreateSelect(). If you look up around 94 line (of zf 2.5) of that method from zend-authentication component then you would find the following line.
$dbSelect->from($this->tableName)
->columns(['*', $credentialExpression])
// See the making of where clause
->where(new SqlOp($this->identityColumn, '=', $this->identity));
Here we are going to make our changes. Now lets override that method by extending Zend\Authentication\Adapter\DbTable. We would make a where clause which would search for both Harib or harib therefore. See the following extended CustomDbTable::class.
<?php
namespace Define\Your\Own\Namespace;
use Zend\Authentication\Adapter\DbTable;
class CustomDbTable extends DbTable
{
protected function authenticateCreateSelect()
{
// build credential expression
if (empty($this->credentialTreatment) || (strpos($this->credentialTreatment, '?') === false)) {
$this->credentialTreatment = '?';
}
$credentialExpression = new SqlExpr(
'(CASE WHEN ?' . ' = ' . $this->credentialTreatment . ' THEN 1 ELSE 0 END) AS ?',
array($this->credentialColumn, $this->credential, 'zend_auth_credential_match'),
array(SqlExpr::TYPE_IDENTIFIER, SqlExpr::TYPE_VALUE, SqlExpr::TYPE_IDENTIFIER)
);
// Here is the catch
$where = new \Zend\Db\Sql\Where();
$where->nest()
->equalTo($this->identityColumn, $this->identity)
->or
->equalTo($this->identityColumn, strtolower($this->identity))
->unnest();
// get select
$dbSelect = clone $this->getDbSelect();
$dbSelect->from($this->tableName)
->columns(array('*', $credentialExpression))
->where($where); // Here we are making our own where clause
return $dbSelect;
}
}
Now custom authentication adapter is ready. You need to use this one inside the factory for authentication service instead of Zend\Authentication\Adapter\DbTable as follows
'factories' => array(
// Auth service
'AuthService' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
// Use CustomDbTable instead of DbTable here
$customDbTable = new CustomDbTable($dbAdapter, 'tableName', 'usernameColumn', 'passwordColumn', 'MD5(?)');
$authService = new AuthenticationService();
$authService->setAdapter($customDbTable);
return $authService;
},
),
All are now set. That overridden method should be called whenever you call this one in your controller method:
$authResult = $authService->authenticate();
This is not tested. So you may need to change things where you need. Please fix those if needed.
Hope this would help you!

Error when trying to load Dual Listbox in Yii2

In the project that I want to develop, user can upload an Excel file (xls,xlsx) to system.
The excel sheet has headers in the first row, and value in another row. System has a default excel template that
consist the rule for headers sequence such as (Name, Age, Sex), but sometimes user use their own excel template so sometimes the header sequence become like this (Sex, Name, Age).
To handle this sequence, I've a plan to make a mapping process to handle the headers sequence before save the value to database. I wanna use dual list box.
I've 2 a table in database for this process:
Header -> has to column (header_id, header_name), all the headers from file has been save in here.
Each headers saved with their own header_id and header_name
Info -> the value from the excel file save here.
and I also has a pure (not generated by Gii) CostumizedHeaderController.php, CostumizeHeader.php, Index.php
This is code in CostumizeHeaderController:
class CostumizeHeaderController extends Controller {
//put your code here
public function actionShowHeaders() {
$model = new CostumizeHeader();
$model->loadHeaders();
$items = \backend\models\CostumizeHeader::getAllHeader();
return $this->render('index', [
'model' => $model,
'items' => $items
]);
}}
Code in model (CostumizeHeader.php)
class CostumizeHeader {
//put your code here
/**
* #var array IDs of the favorite foods
*/
public $list_headers = [];
public function rules() {
return [
[['list_headers'], 'string', 'max' => 255],
];
}
/**
* #return array customized attribute labels
*/
public function attributeLabels() {
return [
'list_headers' => 'list Costumized Header',
];
}
public function loadHeaders() {
$this->list_headers = [];
$headers = Header::find()->all();
foreach ($headers as $ff) {
$this->list_headers[] = $ff->header_id;
}
}
public static function getAllHeader() {
$headers = Header::find()->asArray()->all();
$items = ArrayHelper::map($headers, 'header_id', 'nama_header');
return $items;
}
code in index.php
<?php
$form = ActiveForm::begin([
'id' => 'favorite-form',
'enableAjaxValidation' => false,
]);
?>
<?= $form->field($model->list_headers, 'list_headers')->widget(DualListbox::className(), [
'model' => $model,
'items' => $items,
'name'=>'nama_header',
'attribute' => 'list_headers',
'options' => [
'multiple' => true,
'size' => 15,
],
'clientOptions' => [
'nonSelectedListLabel' => 'Available Header',
'selectedListLabel' => 'Final Header',
'moveOnSelect' => false,
],
])
->hint('Select the header according the sequence.');
?>
I've try to var_dump in controller and got this Array ( [1] => age [2] => sex [3] => name .
And I've been check the header table, and all the headers from excel file have been imported to database.
But I still got an error, like this Call to a member function formName() on a non-object.
I wish anybody can help me to solve this problem. Thankyou
Inside your view page I think you are using field incorretly $model->list_headers should be $model only.
your index.php must be as follows:
<?php
$form = ActiveForm::begin([
'id' => 'favorite-form',
'enableAjaxValidation' => false,
]);
?>
<?= $form->field($model, 'list_headers')->widget(DualListbox::className(), [
'model' => $model,
'items' => $items,
'name'=>'nama_header',
'attribute' => 'list_headers',
'options' => [
'multiple' => true,
'size' => 15,
],
'clientOptions' => [
'nonSelectedListLabel' => 'Available Header',
'selectedListLabel' => 'Final Header',
'moveOnSelect' => false,
],
])
->hint('Select the header according the sequence.');
?>

magento saveAction - for beginners

I am a Magento beginner so please bear with me...
I am creating a simple extension for my site to add a custom field to my Tags in adminhtml. The custom field is just a number which I need to identify a specific Z-block (cms block extension) so that I can access it as a widget and show it on the frontend in the Tag "category".
I have created a custom module which is working: I set a field in the form using $fieldset and have extended TagController.php, both of which are being used (I made a simple trial to see whether or not they had been recognized). However, I do not know how to go about saving my custom field to DB (whether amending saveAction is enough, and I haven't done it properly, or if I need to add a custom Model or sql install).
Sorry for the "basic" question but I'm new at this, and have mostly done frontend dev (so my extension knowledge is simply limited).
Thank you to anyone who can help...
Claudia
NEW TAG FORM:
public function __construct()
{
parent::__construct();
$this->setId('tag_form');
$this->setTitle(Mage::helper('tag')->__('Block Information'));
}
/**
* Prepare form
*
* #return Mage_Adminhtml_Block_Widget_Form
*/
protected function _prepareForm()
{
$model = Mage::registry('tag_tag');
$form = new Varien_Data_Form(
array('id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post')
);
$fieldset = $form->addFieldset('base_fieldset',
array('legend'=>Mage::helper('tag')->__('General Information')));
if ($model->getTagId()) {
$fieldset->addField('tag_id', 'hidden', array(
'name' => 'tag_id',
));
}
$fieldset->addField('form_key', 'hidden', array(
'name' => 'form_key',
'value' => Mage::getSingleton('core/session')->getFormKey(),
));
$fieldset->addField('store_id', 'hidden', array(
'name' => 'store_id',
'value' => (int)$this->getRequest()->getParam('store')
));
$fieldset->addField('name', 'text', array(
'name' => 'tag_name',
'label' => Mage::helper('tag')->__('Tag Name'),
'title' => Mage::helper('tag')->__('Tag Name'),
'required' => true,
'after_element_html' => ' ' . Mage::helper('adminhtml')->__('[GLOBAL]'),
));
$fieldset->addField('zblock', 'text', array(
'name' => 'zblock_id',
'label' => Mage::helper('tag')->__('Z-Block Id'),
'title' => Mage::helper('tag')->__('Z-Block Id'),
'required' => true,
'after_element_html' => ' ' . Mage::helper('adminhtml')->__('[GLOBAL]'),
));
$fieldset->addField('status', 'select', array(
'label' => Mage::helper('tag')->__('Status'),
'title' => Mage::helper('tag')->__('Status'),
'name' => 'tag_status',
'required' => true,
'options' => array(
Mage_Tag_Model_Tag::STATUS_DISABLED => Mage::helper('tag')->__('Disabled'),
Mage_Tag_Model_Tag::STATUS_PENDING => Mage::helper('tag')->__('Pending'),
Mage_Tag_Model_Tag::STATUS_APPROVED => Mage::helper('tag')->__('Approved'),
),
'after_element_html' => ' ' . Mage::helper('adminhtml')->__('[GLOBAL]'),
));
$fieldset->addField('base_popularity', 'text', array(
'name' => 'base_popularity',
'label' => Mage::helper('tag')->__('Base Popularity'),
'title' => Mage::helper('tag')->__('Base Popularity'),
'after_element_html' => ' ' . Mage::helper('tag')->__('[STORE VIEW]'),
));
if (!$model->getId() && !Mage::getSingleton('adminhtml/session')->getTagData() ) {
$model->setStatus(Mage_Tag_Model_Tag::STATUS_APPROVED);
}
if ( Mage::getSingleton('adminhtml/session')->getTagData() ) {
$form->addValues(Mage::getSingleton('adminhtml/session')->getTagData());
Mage::getSingleton('adminhtml/session')->setTagData(null);
} else {
$form->addValues($model->getData());
}
$this->setForm($form);
return parent::_prepareForm();
}
NEW CONTROLLER:
public function saveAction()
{
if ($postData = $this->getRequest()->getPost()) {
if (isset($postData['tag_id'])) {
$data['tag_id'] = $postData['tag_id'];
}
$data['name'] = trim($postData['tag_name']);
$data['zblock'] = $postData['zblock_id'];
$data['status'] = $postData['tag_status'];
$data['base_popularity'] = (isset($postData['base_popularity'])) ? $postData['base_popularity'] : 0;
$data['store'] = $postData['store_id'];
if (!$model = $this->_initTag()) {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Wrong tag was specified.'));
return $this->_redirect('*/*/index', array('store' => $data['store']));
}
$model->addData($data);
if (isset($postData['tag_assigned_products'])) {
$productIds = Mage::helper('adminhtml/js')->decodeGridSerializedInput(
$postData['tag_assigned_products']
);
$model->setData('tag_assigned_products', $productIds);
}
try {
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('The tag has been saved.'));
Mage::getSingleton('adminhtml/session')->setTagData(false);
if (($continue = $this->getRequest()->getParam('continue'))) {
return $this->_redirect('*/tag/edit', array('tag_id' => $model->getId(), 'store' => $model->getStoreId(), 'ret' => $continue));
} else {
return $this->_redirect('*/tag/' . $this->getRequest()->getParam('ret', 'index'));
}
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setTagData($data);
return $this->_redirect('*/*/edit', array('tag_id' => $model->getId(), 'store' => $model->getStoreId()));
}
}
return $this->_redirect('*/tag/index', array('_current' => true));
}
The custom field I'm trying to add is "zblock"...thanks and, again, bear with me! :)
First add the field in database table.
For example if you want to add in your custom table.
ALTER TABLE myCustomModuleTable ADD COLUMN 'myCustomField' int(10);
Thenafter, In your controller action take the model object of that table and set the field.
If you are adding data in existing table row:
$value = 6;
$rowInWhichIWantToSave = Mage:getModel('companyname/modulename')->load($rowId);
$rowInWhichIWantToSave->setData('myCustomField',$value)->save();
If you are adding a new row:
$value = 6;
$rowInWhichIWantToSave = Mage:getModel('companyname/modulename');
$rowInWhichIWantToSave->setData('myCustomField',$value)->save();
Hope this helps!!

"Page not found" first plugin for OctoberCMS

I'm working on the backend side of a plugin and I'm having some issues getting it to work. I created all the plugin needed files, models, register things and so on but any time I try to access backend URL as per example http://alomicuba.dev/backend/alomicuba/balancerecharge I get a 404 error and I don't know what I''m doing wrong. This is the code on /plugins/alomicuba/balancerecharge/controllers/balancerecharge/BalanceRecharge.php file:
<?php namespace Alomicuba\BalanceRecharge\Controllers;
use Flash;
use BackendMenu;
use Backend\Classes\Controller;
use System\Classes\SettingsManager;
use Alomicuba\RechargeBalance\Models\Settings as BalanceRechargeSettings;
class BalanceRecharge extends Controller
{
public $implement = [
'Backend.Behaviors.FormController',
'Backend.Behaviors.ListController'
];
public $formConfig = 'config_form.yaml';
public $listConfig = 'config_list.yaml';
public $requiredPermissions = ['balancerecharge.*'];
public $bodyClass = 'compact-container';
public function __construct()
{
parent::__construct();
BackendMenu::setContext('Alomicuba.BalanceRecharge', 'balancerecharge');
SettingsManager::setContext('Alomicuba.BalanceRecharge', 'settings');
}
}
And this is the Plugin.php code:
class Plugin extends PluginBase {
/**
* Returns information about this plugin.
*
* #return array
*/
public function pluginDetails()
{
return [
'name' => 'Balance Recharge',
'description' => 'Plugin that allows users to recharge theirs balance through the PayPal payment gateway',
'author' => 'Dynamo Technology Solutions',
'icon' => 'icon-credit-card'
];
}
public function registerNavigation()
{
return [
'bradmin' => [
'label' => 'Balance Recharge',
'url' => Backend::url('alomicuba/balancerecharge/balancerecharge'),
'icon' => 'icon-credit-card',
'permissions' => ['brecharge.*'],
'order' => 500,
'sideMenu' => [
'brecharge' => [
'label' => 'Balance Recharge',
'icon' => 'icon-credit-card',
'url' => Backend::url('alomicuba/balancerecharge/balancerecharge'),
'permissions' => ['brecharge.*'],
],
]
]
];
}
public function registerSettings()
{
return [
'settings' => [
'label' => 'Balance Recharge PayPal Configuration',
'description' => 'Manage the settings for Balance Recharge.',
'category' => 'AloMiCuba',
'icon' => 'icon-cog',
'class' => 'Alomicuba\BalanceRecharge\Models\Settings',
'order' => 100
]
];
}
public function boot()
{
\App::register('Barryvdh\Omnipay\ServiceProvider');
\Illuminate\Foundation\AliasLoader::getInstance()->alias('Omnipay', 'Barryvdh\Omnipay\Facade');
UserModel::extend(function($model){
$model->hasMany['payment'] = ['Alomicuba\BalanceRecharge\Models\Payment'];
});
}
public function registerComponents()
{
return [
'Alomicuba\BalanceRecharge\Components\Payment' => 'Payment'
];
}
}
I'm missing something here?
In October CMS URL for controller is like
domain-name/backend/author-name/plugin-name/controller-name
so in your case you can use
alomicuba.dev/backend/alomicuba/balancerecharge/balancerecharge

Csrftoken not validating in case of deleting the records in yii

I am learning Yii and i am trying csrf validation
I have made the following class in the application.components.HttpRequest
class HttpRequest extends CHttpRequest {
private $_csrfToken;
public function getCsrfToken() {
if($this->_csrfToken === NULL) {
$this->_csrfToken= sha1(uniqid(mt_rand(),true));
if(!isset(Yii::app()->session['_tokenforcsrf'])) {
Yii::app()->session['_tokenforcsrf']= $this->_csrfToken;
} else {
Yii::app()->session['_tokenforcsrf']= $this->_csrfToken;
}
return $this->_csrfToken;
}
}
public function validateCsrfToken($event) {
if($this->getIsPostRequest()) {
if(isset(Yii::app()->session['_tokenforcsrf']) && isset($_POST['_tokenforcsrf'])) {
$sessiontoken=Yii::app()->session['_tokenforcsrf'];
$posttoken=$_POST['_tokenforcsrf'];
if($sessiontoken === $posttoken) {
$validity=TRUE;
} else {
$validity=FALSE;
}
} else {
$validity=false;
}
if($validity==false) {
throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
}
}
parent::validateCsrfToken($event);
}
}
The csrf validation is working properly in case of everything but whenever i try to delete some thing it shows that
The CSRF token could not be verified
Its not validating in case of deletion of the records.
The link from where i am trying to delete is
$this->menu = [
[
'label' => 'List Rolearea',
'url' => ['index']
],
[
'label' => 'Create Rolearea',
'url' => ['create']
],
[
'label' => 'Update Rolearea',
'url' => [
'update',
'owner'=>$model->roleName
]
],
[
'label' => 'Delete Rolearea',
'url' => '#',
'linkOptions' => [
'submit' => [
'delete',
'id' => $model->roleNo
],
'confirm' => 'Are you sure you want to delete this item?'
]
],
[
'label' => 'Manage Rolearea',
'url' => ['admin']
],
];
So my question is how can i resolve the issue of csrf validation in this case??
Your code requires that every action that has been secured via your CSRF token has to be invoked via POST. A simple link will result into a GET request, which is why your validation fails.

Categories