Thursday, February 1, 2018

Exchanging credentials for bearer token

Lufthansa API gives bearer token with expiration time. So you need to exchange client secret, client id and grant type for bearer token. Here's the PHP script. Don't forget to place you credentials.


<?php
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL,"https://api.lufthansa.com/v1/oauth/token/");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_POSTFIELDS, 'client_id=****&client_secret=****&grant_type=client_credentials');
 $headers = [
        'Content-Type: application/x-www-form-urlencoded'
 ];
 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
 $data = curl_exec($ch);
 curl_close($ch);

 // Handle response data
 $response = json_decode($data);
 // get bearer token
 $tok = $response->access_token;
 
 $ch = curl_init();
 // end-point
 curl_setopt($ch, CURLOPT_URL,"https://api.lufthansa.com/v1/references/countries/DK?limit=20&offset=0");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 $headers = [
     'Accept: application/json',
     'Authorization: Bearer '.$tok,
     'X-Originating-Ip: '.$_SERVER['SERVER_ADDR']
 ];
 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
 $server_output = curl_exec ($ch);
 curl_close ($ch);
 $response = json_decode($server_output,true);
 echo"<pre>"; 
 var_dump($response);

PHP script for Yelp API v3


Yelp provides bearer token with no expiration date when you register your app. Place it in third line.

<?php
 // place your bearer token from Yelp API
 $token = '';
 if($token == "") die ("place your credentials");
 $unsigned_url = "https://api.yelp.com/v3/businesses/search?term=hotel&location=sf&limit=20";
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $unsigned_url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 $headers = [
     'Authorization: Bearer ' . $token
 ];
 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
 $data = curl_exec($ch); // Yelp response
 curl_close($ch);

 // Handle Yelp response data
 $response = json_decode($data);

 // maximal number of API calls reached?
 if(isset($response->error->id) && $response->error->id = "EXCEEDED_REQS") die ("You have reached maximum API calls");
 
 // handle no search results
 if($response->businesses[0]->name == NULL) die ('<h1>No search results match your query.</h1>');

 // dump name, url, location, address, latitude and longitude
 echo"<p>name, url, location, address, latitude and longitude</p>";
 echo"<pre>";
 var_dump(
  $response->businesses[0]->name,
  $response->businesses[0]->url,
  $response->businesses[0]->location->display_address[0],
  $response->businesses[0]->location->display_address[1],
  $response->businesses[0]->coordinates->latitude,
  $response->businesses[0]->coordinates->longitude
 );
?>

Wednesday, January 31, 2018

PHP generates JWT

This script generates basic JWT token

<?php
$decode = file_get_contents('php://input');
$arr = json_decode($decode, true);
if ($arr['email'] == 'me@example.com' && $arr['password'] == '123') {
    $key = 'very-secret-value-only-on-server';
    // header
    $h = ["alg" => "HS256", "typ" => "JWT"];
    $h = base64_encode(json_encode($h));
    
    //payload
    $p = ["username" => "username", "role" => "admin"];
    $p = base64_encode(json_encode($p));
    
    // encryption and signing
    $signature = hash_hmac('sha256', "$h.$p", $key, true);
    $signature = base64_encode($signature);

    $token = "$h.$p.$signature";
    echo $token;
}

You should add iat and exp to payload. Debugger for JWT.

Thursday, November 9, 2017

MongoDB Search Collections

Document:
{
    "_id" : ObjectId("5a046e1151c456a18a6146f5"),
    "name" : [ 
        "bmw", 
        "bav motor wagen"
    ],
    "class" : {
        "usa" : "suv",
        "europe" : "compact"
    },
    "speed" : [ 
        {"mph" : 100}, 
        {"kph" : 120}
    ]
}
search query width and criteria, array match, object match
db.getCollection('cars').find({
    "name":"bmw",
    "class.usa": "suv",
    $and :[ 
        {"speed.0.mph": { $eq:100 }}, 
        {"speed.1.kph": { $eq:120 }} 
   ]
}
)

Friday, November 3, 2017

Install and Test Symfony Application with Node.JS

This will automate the process. You only need to enter passwords for mysql root or other mysql user and database name in install node.
To speed up symfony instalation and testing use package.json
{
  "scripts":{
    "install":"git clone https://github.com/nikola-bodrozic/sym28-patterns sym28 && cd sym28 && composer install && mysql -u root -p test < database.sql",
    "test":"cd sym28 && php phpunit-5.7.phar -c app/"
  }
}

in console run

npm install
npm test

Saturday, October 21, 2017

Run Local Node.JS Dependancies

From Command Line


Install dependency locally

npm install live-server

Create folder public with index.html and file called run-server.js. Here's the structure:

node_modules/
public/
   index.html
run-server.js

Content of run-server.js:

var liveServer = require("live-server");

var params = {
 port: 8181, // Set the server port. Defaults to 8080.
 host: "0.0.0.0", // Set the address to bind to
 root: "./public", // Set root directory that's being served. Defaults to cwd.
 open: true, // When false, it won't load your browser by default.
 logLevel: 2, // 0 = errors only, 1 = some, 2 = lots
};

liveServer.start(params);

in console run live-server

node run-server.js
or on Linux
node node_modules/.bin/live-server --open=public/

Using package.json

in console
npm init
npm install -D live-server
npm install --save cowsay

this will generate file package.json:
{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "cowsay -b mooooooooo >> index.html && live-server --port=8085"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "live-server": "^1.2.0"
  },
  "dependencies": {
    "cowsay": "^1.2.1"
  }
}

to create index.html and run server
npm test

if you want to do clone a git repo and run in in live-server replace yellow line with:

"test": "git clone https://github.com/nikola-bodrozic/Bootstrap-Boilerplate-v3.3.7.git tb337 && live-server --watch=tb337 --open=tb337 --ignore=tb337/.git"

this will watch for file changes in tb337 folder but not in tb337/.git folder

another example
{
  "scripts": {
    "less-gen": "lessc -l public/css/style.less && lessc public/css/style.less public/css/style.css && exit 0",
    "lint-css": "csslint --ignore=ids,order-alphabetical  public/css && exit 0",
    "lint-js": "eslint public/js && exit 0",
    "test": "node run-w3cvalid.js && npm run less-gen && npm run lint-css && npm run lint-js && echo \"Tests finished\" && exit 0",
    "start": "node run-server.js"
  },
  "dependencies": {
    "csslint": "^1.0.5",
    "html-validator": "^2.2.3",
    "less": "^3.0.0-alpha.3",
    "live-server": "^1.2.0"
  },
  "devDependencies": {
    "eslint": "^4.10.0"
  }
}
Inside script.test and script.start we can run js files.

Friday, October 13, 2017

Usefull Shell Commands

Pack folder and backup database

Backup folder. Run as sudo, other users will change the original permissions
tar -zcf wp03.tar.gz wp03/
Backup database
mysqldump -u root -p -C albert > albert.sql.tgz

Create user with home folder, shell & password

sudo useradd -m -d /home/mike -s /bin/bash -c "Mike" -U mike
sudo passwd mike
Enter new UNIX password: 
Retype new UNIX password: 
passwd: password updated successfully

Numeric permissions in console

$ ls -la | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf("%0o ",k);print}'
775 drwxrwxr-x  9 3173 3173   4096 Oct 12 20:01 .
755 drwxr-xr-x  4 3173 3173   4096 Oct 12 21:54 ..
755 drwxr-xr-x  6 3173 3173   4096 Oct 12 19:08 app
755 drwxr-xr-x  2 3173 3173   4096 Oct  9 15:46 bin
644 -rw-r--r--  1 3173 3173   2111 Mar 11  2017 composer.json
664 -rw-rw-r--  1 3173 3173 102342 Oct 12 19:08 composer.lock

Search file names and file content

find file that begins with example case insensitive search
find . -iname "example*" -print

finds string `getcol` in js files in current folder and it`s subfolders, print file name, line number and the line
find . -type f -name "*.js" -exec grep -in --with-filename getcol {} \;

Set permissions for files and folders

sudo find /var/www -type d -exec chmod 775 {} \;  # rwxrwxr-x
sudo find /var/www -type f -exec chmod 664 {} \;  # rw-rw-r--