Categories
aws optimization php static

Optimization – Store Static Files on AWS S3 with Git Hooks, AWS CLI tool

In this tutorial, we will learn on how to store your static files, like JS, CSS, JSON, images, etc. on AWS S3. This is going to make a drastic improvement for your web servers. The reason for improvement is for every page load, there are over tons of follow up such static file requests. Though, such requests are not processed (only then can be kept at S3 as it is a non-processing storage), these request still hit your web servers significantly. When kept on S3, it saves a lot of file power to the web servers. We are going to use Git Hooks, AWS CLI tool to achieve our goal.

The challenge is repeated uploads of your static files to S3, which, if done manual, is tedious. Here we can make use of Git Hooks and AWS CLI tool to work together to automate the syncing of your static files.

Git Hooks

Git Hooks, in simple terms, are the intermediate steps behind a git command. For example, git pre-push hook is a hook which executes on every git push command, but prior to pushing the code.

AWS CLI

AWS CLI tool in simple terms is a command line interface tool (full form actually) with various commands to communicate with AWS services like S3, EC2, etc.

Here we can write a command for aws using aws cli tool, in the pre-push hook.

The process is that, you can define a constant ASSET_URL for the static files base url location. For ex- for your test environment, it would be http://localhost/project/ and for production it should be your s3 address (or cloudfront url, https://cdn.example.com/, infront of s3). So, the static file urls would look like, ASSETS_URL.'assets/img/a.png', ASSETS_URL.'assets/css/a.css', ASSETS_URL.'assets/js/a.js', etc.

Now the testing and development process would remain same, as all the file copies remain on your local server. But on the production environment, it will look for these files on cdn address provided. So, before sending your code to production servers, you need to update all the new / modified files to the s3.

At this step, git hooks would come into picture. One of the git hook is pre-push hook, which you can edit/create with .git/hooks/pre-push. https://stackoverflow.com/a/14672883/2560576. Example sample for pre-push hook.

In the pre-push hook, you can add aws cli command to update your local assets folder to your s3 assets folder. For example- aws s3 sync assets/ s3://bucket/assets/ --profile aws_credential_profile --acl public-read

So, now when development is complete, and you can execute git push code to push your code to remote repository as usual. But with the help of Git pre-push hook, all the static files will be synced to your s3 bucket’s assets folder just before the actual push.

Now only processing requests are made to your web server, and all static file requests are routed to S3.

Hope this helps someone. Pl give your feedback to improve or add anything.

More- Automatic PWA Converter Platform

Thanks!

Categories
application linkedin login oauth2 php ubuntu

Login With LinkedIn Implementation in php with oauth 2.0

Hi Everyone, today we are going to implement login with linkedin feature in php with oauth 2.0. Nowadays, third party login systems are used a lot to ease the user on boarding process. Linkedin is yet another huge network, and a lot of platforms use their apis to onboard their user.

In order to login with linkedin, their user must be authenticated. To make this process as easy as possible, LinkedIn relies on the industry standard OAuth 2.0 protocol for granting access.

Create a linkedin application using your developer account.

1- Go to https://www.linkedin.com/secure/developer

2- Create a new application/ choose from any existing one.

3- After you have an application, note down its authentication keys, i.e., client id, client secret.

4- Select default application permissions (choose r_basicprofile, r_emailaddress).

5- Give absolute path to your redirect urls. A redirect url is the address of your apis, which handles the process after linkedin authenticates and responses back. You can give your corresponding local, development, production api absolute urls here.

6- Click on update to update your settings.

Use the application to implement login with linkedin feature.

7- On click of your login with linkedin button, redirect your user to https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=CLIENT_ID&redirect_uri=’+REDIRECT_URL_ABSOLUTE_PATH+’&state=’+UNIQUE_STRING+’&scope=r_basicprofile r_emailaddress

Above is a get request, with parameters and their values as, response_type=code, client_id= client id noted in step 3, redirect_uri=API path given in step 5, state=A unique string value of your choice that is hard to guess,Used to prevent CSRF(give it BGEeFWf45A53sdfKef424), scope=[r_basicprofile r_emailaddress]user information you wish to fetch from application(step 4)

8- If everything goes fine, the user should see a linkedin auth page. If not, fix the error you see. Usually, the error points are Relative redirect urls instead of absolute urls, scope value mismatch in step 4 and step 7.

login with linkedin

9- Click on allow, then you will be redirected to your redirect url with get parameters, code and state. You can use state value to confirm if it matches the value you sent to avoid any mitm attack, code value can be used to fetch the access token which in turn will be used to fetch data from linkedin application.
If clicked on cancel or some other error, you are still redirected to your redirect url with get parameter error explaining what had happpened.

10- If everything goes fine, make a post request to fetch access token at https://www.linkedin.com/oauth/v2/accessToken.
Also send post parameters, grant_type=authorization_code, code=code value received in step 9, redirect_uri=redirect_uri value used in step 7, client_id=client_id value used in step 7, client_secret=client secret value obtained in step 3.

public function send_req($url, $data, $method) {
$options = array(
‘http’ => array(
‘header’ => “Content-type: application/x-www-form-urlencoded\r\n”,
‘method’ => $method,
‘content’ => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
if (gettype($result) == ‘string’) {
$result = json_decode($result, true);
} else if (gettype($result) == ‘object’) {
$result = array($result);
}
return $result;
}
$url = ‘https://www.linkedin.com/oauth/v2/accessToken’;
$data_access_token = array(
‘grant_type’ => ‘authorization_code’,
‘code’ => $code,
‘redirect_uri’ => REDIRECT_URI,
‘client_id’ => CLIENT_ID,
‘client_secret’ => CLIENT_SECRET
);
$access_token = $this->send_req($url, $data_access_token, ‘POST’)[‘access_token’];

Now, when you have access token, you can fetch data from linkedin using that.

11- Make a get request to https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,public-profile-url,email-address)?format=json, to fetch your data. Pass in your access token as Authorization header. You will receive respective data in json format as asked.

public function fetch_linkedin_data($access_token) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => “https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,public-profile-url,email-address)?format=json”,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => “”,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => “GET”,
CURLOPT_HTTPHEADER => array(
“authorization: Bearer “.$access_token,
“cache-control: no-cache”,
“connection: Keep-Alive”
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
return “failed”;
} else {
$response = json_decode($response, true);
return $response;
}
}

If everything goes fine, you will receive json data of requested information. If sent a bad token, you will receive 401 error.

Now, you should be able to use the login with linkedin feature and must be having some clear idea of the same.

Github URL
LinkedIn Create Application
LinkedIn Implementation Guide

Categories
aws aws-sdk install php sms sns ubuntu

SMS Services : AWS SNS Implementation In PHP5 In Ubuntu 14.04

Hi Everyone, today we are going to implement one of the AWS service, SNS(Simple Notification Service) for SMS services in php.

SMS services are usually used for otp(One time password) features in various platforms. It is also used for marketing. There are various services which provide bulk sms services, like twilio, plivo, nexmo, etc. Among all of them, I found out that AWS SNS is a better one, with their offerings.

Install PHP SDK for AWS

1- Install Composer
curl -sS https://getcomposer.org/installer | php

2- Create a composer.json file into your project.
sudo touch composer.json

3- Edit composer.json with below content.
{
"require": {
"aws/aws-sdk-php": "3.*"
}
}

4- Run you composer command to install aws sdk.
php composer.phar install

This will install aws-sdk into your project. Now, you must be having a vendor folder in your project, which contains the aws-sdk. It also contains an autoload.php file, which is used to load the aws-sdk in your project.

Use Of PHP-SDK

1- Include the autoload.php into your file where you want to implement sns and specify SnsClient class to be used.
include 'vendor/autoload.php'; or include FCPATH.'vendor/autoloader.php';(for codeigniter)
use Aws\Sns\SnsClient;

2- Get an object of sns library, to use its functions.
$client = new SnsClient([
'version' => 'latest',
'region' => 'us-west-2',
'credentials' => [
'key' => 'KEY',
'secret' => 'SECRET KEY',
],
]);

In above replace, key and secret’s value with their correct value.

Now you are ready to send message using the above client object.

3- Create settings for your object.
$options = array(
'MessageAttributes' => array(
'AWS.SNS.SMS.SenderID' => array(
'DataType' => 'String',
'StringValue' => 'SENDERID'
),
'AWS.SNS.SMS.SMSType' => array(
'DataType' => 'String',
'StringValue' => 'SMSType'
)
),
'Message' => $message,
'PhoneNumber' => $phone
);

In above, replace SENDERID, with your desired sender id, SMSType with desired value(Transactional/Promotional), appropriate message, phone number.

4- Send the message, by calling the publish function of the object.
$result = $client->publish($options);

Result contains the response sent by aws sns.

At this point, you must be able to send a message using aws sns.
Github URL
AWS-SDK Tutorial
AWS-SDK Installation
Composer Commands