Sunday, 19 April 2020

Jwt authentication in laravel

Jwt authentication in Laravel 5.5 or above

Step 1#: Run the following three command one by one to install the Jwt in your installed Laravel framework.

composer require tymon/jwt-auth
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
php artisan jwt:secret


Step 2#: Update your user model

<?php

namespace App;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

 
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

   
    public function getJWTCustomClaims()
    {
        return [];
    }

}

Step 3#: Create Auth controller by running this command

php artisan make:controller AuthController
php artisan make:middleware authJwt

add this code to kernel.php

protected $routeMiddleware = [
  ........
'jwt-auth' => \App\Http\Middleware\authJwt::Class,

]

and add the following code to your authcontroller

<?php


namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Controller; class AuthController extends Controller { public function __construct() { $this->middleware('auth:api', ['except' => ['login']]); } public function login() { $credentials = request(['email', 'password']); if (! $token = auth()->attempt($credentials)) { return response()->json(['error' => 'Unauthorized'], 401); } return $this->respondWithToken($token); } public function me() {

try { $user = auth()->userOrFail(); } catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {
return response()->json(['error' => $e->getMessage()], 401);
} return response()->json(auth()->user()); } public function logout() { auth()->logout(); return response()->json(['message' => 'Successfully logged out']); } public function refresh() {
try { $user = auth()->userOrFail(); } catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {
return response()->json(['error' => $e->getMessage()], 401);
}
return $this->respondWithToken(auth()->refresh()); } protected function respondWithToken($token) { return response()->json([ 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => auth()->factory()->getTTL() * 60 ]); } }
?>

Step 4#: Create api routes in api.php file.

<?php

Route::group([
'middleware' => 'api', 'prefix' => 'auth' ], function ($router) {
Route::post('login', 'AuthController@login');
Route::get('logout', 'AuthController@logout');
Route::get('refresh', 'AuthController@refresh'); Route::get('me', 'AuthController@me'); });


?>

Step 5#: Test on postman




Wednesday, 8 April 2020

Mailingboss api integration (Builderall)

Mailingboss api integration

Get Api token after login to builderall acount then mailingboss integration section.

We can integrate these given api in PHP or jquery ajax


1) Get list api from Mailingboss autoresponder Email

Request example


GET: https://member.mailingboss.com/integration/index.php/lists/{api-token} 

Response example JSON:

 {
status: "success",
data: [{
list_uid: "m07ug174cie26",
name: "E-mail Marketing",
display_name: "E-mail Marketing",
description: "E-mail Marketing"
}, {
list_uid: "mj546z2pwp2de",
name: "Lista Teste",
display_name: "Lista Teste",
description: "Lista" 
                  }
                    ]
}

2) Add lead to list api example of Mailingboss autoresponder Email


Request example 


POST: https://member.mailingboss.com/integration/index.php/lists/subscribers/create/{api-token}

PARAMS:
email: teste@teste.com 
                list_uid: vh485p76so057 
                status:confirmed 

Response example JSON: 

{
       status: "success",
      data: {
             subscriber_uid: "ow305e5oat103",
             email: "teste@teste.com",
             taginternals: "testetag, tag2",
             status: "confirmed"
            }

}

Mailingboss is the one of the best module of builderall
If you need any help please feel free to comment. 

Sunday, 2 February 2020

Host '*.wpxhosting.com' is not allowed to connect to this MariaDB server error 1130

Host '*.wpxhosting.com' is not allowed to connect to this MariaDB server

wpxhosting MariaDB server error 1130

When you add database users to the database in WPXhosting and you also assign the password to the user
But while making connection to database  use the password as shown in above image under FTP/MYSQL Login details section. In short username will be different but password same for all database.
Thanks.
 

Wednesday, 25 December 2019

json encode chinese character php

json encode chinese character php

-------json_encode() in PHP returns Chinese characters in escaped-------

Many time you were not able to create php json_encode from special characters which generate the  null. I have a code by which you can create a valid json in php 


//****************start encodeing***********/
$data  = array(
array('Sr No'=> 1,'name' => "删除一个连续数组值的方式产生的非连续数组"),
array('Sr No'=> 2,'name' => "删除一个连续数组值的方式产生的非连续数组"),
array('Sr No'=> 3,'name' => "删除一个连续数组值的方式产生的非连续数组")
);


foreach ($data as $key => $value) {
$data[$key]['name'] = mb_convert_encoding($value['name'], "UTF-8", "UTF-8");
}
echo json_encode($data);

///*************end ********************//

using  mb_convert_encoding($string, "UTF-8", "UTF-8");
function you can easily create a valid jSon 

// ************output is given below ***********//
php json_encode special characters null solved

Method 2:  Change collation to utf8mb4_unicode_ci In mysql DB of your column.

Thanks for sharing your time. I believe that you issue has been resolved Please Give a comment to support my efforts. Thanks 





Saturday, 31 August 2019

send message from popup to content script in chrome extension

send message from popup to content script in chrome extension

You really need this to create chrome extensions for websites like amazon, facebook, flipkart etc..
Step 1: Set permissions to all tabs in manifest file of chrome extension.

"permissions": [
        "activeTab",
          "tabs"
    ],

Step 2: Add this code to popup.js file to send message to content.

  chrome.tabs.query({
                    active: true,
                    currentWindow: true
                }, function (tabs) {
                    chrome.tabs.sendMessage(tabs[0].id,{'action':'frompopup'});
                });


Step 3: Add this code to content.js file

chrome.extension.onMessage.addListener(function(message, sender, send_response) {
    if (message.action== 'frompopup') {
      ////////// do your work here
    }
});

In this way we can send messages.
Thanks for  reading.

send message from content script to background script in chrome extension

send message from Content script to background script in chrome extension

You really need this to create chrome extensions for websites like amazon, facebook, flipkart etc..
Step 1: Set permissions to all tabs in manifest file of chrome extension.

"permissions": [
        "activeTab",
          "tabs"
    ],

Step 2: Add this code to contentscript.js file to send message to background.

chrome.runtime.sendMessage({'type': 'fromcontent'});

Step 3: Add this code to background.js file

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {  
    if (request.type == 'fromcontent') {
               ///////// do your work here
           }
});

In this way we can send messages.
Thanks for reading.

Friday, 9 August 2019

send message from background script to content script on particular tab

send message from background script to content script on particular tab in chrome extension

You really need this to create chrome extensions for websites like amazon, flipkart, facebook etc..
Step 1: Set permissions to all tabs in manifest file of chrome extension.

"permissions": [
        "activeTab",
          "tabs"
    ],

Step 2: Add this code to contentscript.js file to send message to background.

/// content script is work individually for every tab so we can send message to background

chrome.runtime.sendMessage({'action':'content'});


Step 3: Add this code to background.js file

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {  
   var senderId = sender.tab.id; ///// sender id of particular tab
    if (request.from == 'content') {
               chrome.tabs.sendMessage(senderId,{action:'takeaction',});
           }
});

In this way we can send back message to particular tab by sending sender id.
Thanks reading.

Thursday, 27 June 2019

Interview questions of codeigniter framework

Interview questions of codeigniter framework


Q 1: What is helper function in codeigniter?
Ans: Helper file is a collection of functions in a particular category.A helper can be loaded by
$this->load->helper('name');
Q 2: Define hook.
Ans: It is use to modify the inner workings of the framework without hacking the core files. When CodeIgniter runs it follows a specific execution process e.g. pre_system , pre_controller etc..
Q 3: How to load a custom library in codeigniter?
Ans: $CI =& get_instance(); On $CI object you can load library.
e.g. $CI->load->library('classname');
Q 4: How load automatically a library in codeigniter ?
Ans: write the name of class in autoload file in autoload array. e.g. database
Q 5:What is the name of database object/
Ans: $ob->
Q 6: How we can require a custom library in controller using APPATH?
Ans: require APPPATH . '/libraries/filename.php';
Q 7: Generate a random sting which contains alphabet and numbers having length 15. Ans: For this we can use string helper function.
e.g. random_string('alnum', 16);
Q 8: In which file you can define the modify routes?
Ans: application/config/routes.php
$route['product'] = 'controller_name/function_name'; browser url will be www.example.com/product
Q 9: Which library is used for form validation in codigniter? Ans: Please type in comment box.

Sunday, 19 May 2019

jwt in wordpress

Jwt authentication in wordpress for rest api,

In this tutorial we will learn how we can implement jwt authentication in wordpress for every Rest api request (Not only for private posts.).

Using jwt authentication we can protect your wordpress data post data.

Step: 1. Install and activate the wp rest api plugin. And download the jwt library form github link is given below.


Place this file inside your active theme directory along with functions.php file

comment these few lines as show below:

//namespace Firebase\JWT;
//use \DomainException;
//use \InvalidArgumentException;
//use \UnexpectedValueException;
//use \DateTime;

and save this file with "jwt.php".
Than include this file in function.php using this line of code

require get_template_directory() . '/jwt.php'; 

Step 3: create a page template token.php

as show below:
get jwt token

Hello is the secret key at line no 13.
at line number 6 you can change username or password as you desire.

Step: 4 Put this code inside function.php

decode jwt token data

Get token form headers and decoded the token data using jwt libraray.

Postman testing sample images are given below:


get jwt token passing username and password

Send jwt token with every request to get data:
send jwt token in header data


Thank you for giving yours time.

Saturday, 13 April 2019

create pdf file from caldera form data

Caldera form pdf file

Install Run Action addon  then add a action on process

as shown in fig:
caldera form pdf  

Install dompdf (open source) which using composer inside you theme folder 
Using this command

Composer require dompdf

Than add the following code to yours functions.php file

require_once '/vendor/autoload.php';
 use Dompdf\Dompdf;
add_action('create_pdf','create_pdf_fun');

function create_pdf_fun($data)
{

$html = 'First Name:'.$data['first_name'].'<br>
        Last Name:'.$data['last_name'].'<br>
        Email:'.$data['email_address'].'<br>
        message:'.$data['message'].'<br>
        Question:'.$data['comments_questions'];
// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml($html);

$dompdf->setPaper('A4', 'landscape');
$dompdf->render();

$output = $dompdf->output();

$subdir = wp_get_upload_dir();
$upload_path = 'wp-content/uploads'.$subdir['subdir'].'/'.rand(1,2000).'test.pdf';
file_put_contents($upload_path, $output);
}

Thank you for giving your time!