Search

Nov 25, 2015

Install JWT (JSON Web Token) - PHP

JWT.php


<?php

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

/**
 * JSON Web Token implementation, based on this spec:
 * http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06
 *
 * PHP version 5
 *
 * @category Authentication
 * @package  Authentication_JWT
 * @author   Neuman Vong <neuman@twilio.com>
 * @author   Anant Narayanan <anant@php.net>
 * @license  http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
 * @link     https://github.com/firebase/php-jwt
 */
class JWT
{

    /**
     * When checking nbf, iat or expiration times,
     * we want to provide some extra leeway time to
     * account for clock skew.
     */
    public static $leeway = 0;

    public static $supported_algs = array(
        'HS256' => array('hash_hmac', 'SHA256'),
        'HS512' => array('hash_hmac', 'SHA512'),
        'HS384' => array('hash_hmac', 'SHA384'),
        'RS256' => array('openssl', 'SHA256'),
    );

    /**
     * Decodes a JWT string into a PHP object.
     *
     * @param string            $jwt            The JWT
     * @param string|array|null $key            The key, or map of keys.
     *                                          If the algorithm used is asymmetric, this is the public key
     * @param array             $allowed_algs   List of supported verification algorithms
     *                                          Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
     *
     * @return object The JWT's payload as a PHP object
     *
     * @throws DomainException              Algorithm was not provided
     * @throws UnexpectedValueException     Provided JWT was invalid
     * @throws SignatureInvalidException    Provided JWT was invalid because the signature verification failed
     * @throws BeforeValidException         Provided JWT is trying to be used before it's eligible as defined by 'nbf'
     * @throws BeforeValidException         Provided JWT is trying to be used before it's been created as defined by 'iat'
     * @throws ExpiredException             Provided JWT has since expired, as defined by the 'exp' claim
     *
     * @uses jsonDecode
     * @uses urlsafeB64Decode
     */
    public static function decode($jwt, $key, $allowed_algs = array())
    {
        if (empty($key)) {
            throw new InvalidArgumentException('Key may not be empty');
        }
        $tks = explode('.', $jwt);
        if (count($tks) != 3) {
            throw new UnexpectedValueException('Wrong number of segments');
        }
        list($headb64, $bodyb64, $cryptob64) = $tks;
        if (null === ($header = JWT::jsonDecode(JWT::urlsafeB64Decode($headb64)))) {
            throw new UnexpectedValueException('Invalid header encoding');
        }
        if (null === $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64))) {
            throw new UnexpectedValueException('Invalid claims encoding');
        }
        $sig = JWT::urlsafeB64Decode($cryptob64);
        
        if (empty($header->alg)) {
            throw new DomainException('Empty algorithm');
        }
        if (empty(self::$supported_algs[$header->alg])) {
            throw new DomainException('Algorithm not supported');
        }
        if (!is_array($allowed_algs) || !in_array($header->alg, $allowed_algs)) {
            throw new DomainException('Algorithm not allowed');
        }
        if (is_array($key) || $key instanceof \ArrayAccess) {
            if (isset($header->kid)) {
                $key = $key[$header->kid];
            } else {
                throw new DomainException('"kid" empty, unable to lookup correct key');
            }
        }

        // Check the signature
        if (!JWT::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) {
            throw new SignatureInvalidException('Signature verification failed');
        }

        // Check if the nbf if it is defined. This is the time that the
        // token can actually be used. If it's not yet that time, abort.
        if (isset($payload->nbf) && $payload->nbf > (time() + self::$leeway)) {
            throw new BeforeValidException(
                'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
            );
        }

        // Check that this token has been created before 'now'. This prevents
        // using tokens that have been created for later use (and haven't
        // correctly used the nbf claim).
        if (isset($payload->iat) && $payload->iat > (time() + self::$leeway)) {
            throw new BeforeValidException(
                'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
            );
        }

        // Check if this token has expired.
        if (isset($payload->exp) && (time() - self::$leeway) >= $payload->exp) {
            throw new ExpiredException('Expired token');
        }

        return $payload;
    }

    /**
     * Converts and signs a PHP object or array into a JWT string.
     *
     * @param object|array  $payload    PHP object or array
     * @param string        $key        The secret key.
     *                                  If the algorithm used is asymmetric, this is the private key
     * @param string        $alg        The signing algorithm.
     *                                  Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
     * @param array         $head       An array with header elements to attach
     *
     * @return string A signed JWT
     *
     * @uses jsonEncode
     * @uses urlsafeB64Encode
     */
    public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null)
    {
        $header = array('typ' => 'JWT', 'alg' => $alg);
        if ($keyId !== null) {
            $header['kid'] = $keyId;
        }
        if ( isset($head) && is_array($head) ) {
            $header = array_merge($head, $header);
        }
        $segments = array();
        $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($header));
        $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($payload));
        $signing_input = implode('.', $segments);

        $signature = JWT::sign($signing_input, $key, $alg);
        $segments[] = JWT::urlsafeB64Encode($signature);

        return implode('.', $segments);
    }

    /**
     * Sign a string with a given key and algorithm.
     *
     * @param string            $msg    The message to sign
     * @param string|resource   $key    The secret key
     * @param string            $alg    The signing algorithm.
     *                                  Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
     *
     * @return string An encrypted message
     *
     * @throws DomainException Unsupported algorithm was specified
     */
    public static function sign($msg, $key, $alg = 'HS256')
    {
        if (empty(self::$supported_algs[$alg])) {
            throw new DomainException('Algorithm not supported');
        }
        list($function, $algorithm) = self::$supported_algs[$alg];
        switch($function) {
            case 'hash_hmac':
                return hash_hmac($algorithm, $msg, $key, true);
            case 'openssl':
                $signature = '';
                $success = openssl_sign($msg, $signature, $key, $algorithm);
                if (!$success) {
                    throw new DomainException("OpenSSL unable to sign data");
                } else {
                    return $signature;
                }
        }
    }

    /**
     * Verify a signature with the message, key and method. Not all methods
     * are symmetric, so we must have a separate verify and sign method.
     *
     * @param string            $msg        The original message (header and body)
     * @param string            $signature  The original signature
     * @param string|resource   $key        For HS*, a string key works. for RS*, must be a resource of an openssl public key
     * @param string            $alg        The algorithm
     *
     * @return bool
     *
     * @throws DomainException Invalid Algorithm or OpenSSL failure
     */
    private static function verify($msg, $signature, $key, $alg)
    {
        if (empty(self::$supported_algs[$alg])) {
            throw new DomainException('Algorithm not supported');
        }

        list($function, $algorithm) = self::$supported_algs[$alg];
        switch($function) {
            case 'openssl':
                $success = openssl_verify($msg, $signature, $key, $algorithm);
                if (!$success) {
                    throw new DomainException("OpenSSL unable to verify data: " . openssl_error_string());
                } else {
                    return $signature;
                }
            case 'hash_hmac':
            default:
                $hash = hash_hmac($algorithm, $msg, $key, true);
                if (function_exists('hash_equals')) {
                    return hash_equals($signature, $hash);
                }
                $len = min(self::safeStrlen($signature), self::safeStrlen($hash));

                $status = 0;
                for ($i = 0; $i < $len; $i++) {
                    $status |= (ord($signature[$i]) ^ ord($hash[$i]));
                }
                $status |= (self::safeStrlen($signature) ^ self::safeStrlen($hash));

                return ($status === 0);
        }
    }

    /**
     * Decode a JSON string into a PHP object.
     *
     * @param string $input JSON string
     *
     * @return object Object representation of JSON string
     *
     * @throws DomainException Provided string was invalid JSON
     */
    public static function jsonDecode($input)
    {
        if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
            /** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you
             * to specify that large ints (like Steam Transaction IDs) should be treated as
             * strings, rather than the PHP default behaviour of converting them to floats.
             */
            $obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
        } else {
            /** Not all servers will support that, however, so for older versions we must
             * manually detect large ints in the JSON string and quote them (thus converting
             *them to strings) before decoding, hence the preg_replace() call.
             */
            $max_int_length = strlen((string) PHP_INT_MAX) - 1;
            $json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input);
            $obj = json_decode($json_without_bigints);
        }

        if (function_exists('json_last_error') && $errno = json_last_error()) {
            JWT::handleJsonError($errno);
        } elseif ($obj === null && $input !== 'null') {
            throw new DomainException('Null result with non-null input');
        }
        return $obj;
    }

    /**
     * Encode a PHP object into a JSON string.
     *
     * @param object|array $input A PHP object or array
     *
     * @return string JSON representation of the PHP object or array
     *
     * @throws DomainException Provided object could not be encoded to valid JSON
     */
    public static function jsonEncode($input)
    {
        $json = json_encode($input);
        if (function_exists('json_last_error') && $errno = json_last_error()) {
            JWT::handleJsonError($errno);
        } elseif ($json === 'null' && $input !== null) {
            throw new DomainException('Null result with non-null input');
        }
        return $json;
    }

    /**
     * Decode a string with URL-safe Base64.
     *
     * @param string $input A Base64 encoded string
     *
     * @return string A decoded string
     */
    public static function urlsafeB64Decode($input)
    {
        $remainder = strlen($input) % 4;
        if ($remainder) {
            $padlen = 4 - $remainder;
            $input .= str_repeat('=', $padlen);
        }
        return base64_decode(strtr($input, '-_', '+/'));
    }

    /**
     * Encode a string with URL-safe Base64.
     *
     * @param string $input The string you want encoded
     *
     * @return string The base64 encode of what you passed in
     */
    public static function urlsafeB64Encode($input)
    {
        return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
    }

    /**
     * Helper method to create a JSON error.
     *
     * @param int $errno An error number from json_last_error()
     *
     * @return void
     */
    private static function handleJsonError($errno)
    {
        $messages = array(
            JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
            JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
            JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON'
        );
        throw new DomainException(
            isset($messages[$errno])
            ? $messages[$errno]
            : 'Unknown JSON error: ' . $errno
        );
    }

    /**
     * Get the number of bytes in cryptographic strings.
     *
     * @param string
     *
     * @return int
     */
    private static function safeStrlen($str)
    {
        if (function_exists('mb_strlen')) {
            return mb_strlen($str, '8bit');
        }
        return strlen($str);
    }
}

Demo Example:



<?php
use \Firebase\JWT\JWT;

$key = "example_key";
$token = array(
    "iss" => "http://example.org",
    "aud" => "http://example.com",
    "iat" => 1356999524,
    "nbf" => 1357000000
);

/**
 * IMPORTANT:
 * You must specify supported algorithms for your application. See
 * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
 * for a list of spec-compliant algorithms.
 */
$jwt = JWT::encode($token, $key);
$decoded = JWT::decode($jwt, $key, array('HS256'));

print_r($decoded);

/*
 NOTE: This will now be an object instead of an associative array. To get
 an associative array, you will need to cast it as such:
*/

$decoded_array = (array) $decoded;

/**
 * You can add a leeway to account for when there is a clock skew times between
 * the signing and verifying servers. It is recommended that this leeway should
 * not be bigger than a few minutes.
 *
 * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef
 */
JWT::$leeway = 60; // $leeway in seconds
$decoded = JWT::decode($jwt, $key, array('HS256'));

?>

Nov 20, 2015

Get timing compared to the current time (php + javascript)

PHP Code
/**
 * Get timing compared to the current time
 * @param $time
 * @return string
 */
function toTimeNotify($time)
{
    $timeMinus = time() - $time;
    $timeMinus = ($timeMinus < 2) ? 2 : $timeMinus;

    if ($timeMinus <= 24 * 3600) {
        $interval = floor($timeMinus / 3600);
        if ($interval > 1) return $interval . " hours ago";
        $interval = floor($timeMinus / 60);
        if ($interval > 1) return $interval . " minutes ago";
        return floor($timeMinus) . " seconds ago";
    } else {
        return date('d.m.y H:i',$time);
    }
}

Javascript Code

/**
 * Convert string time for notification
 * @param time - the seconds since midnight, 1 Jan 1970
 * @returns {string} - time
 */
var toTimeNotify = function (time) {
    var current = new Date().getTime() / 1000;
    current = parseInt(current);
    var timeMinus = current - time;
    timeMinus = (timeMinus < 1) ? 2 : timeMinus;

    if (timeMinus <= 24 * 3600) {
        var interval = Math.floor(timeMinus / 3600);
        if (interval > 1) return interval + " hours ago";
        interval = Math.floor(timeMinus / 60);
        if (interval > 1) return interval + " minutes ago";
        return Math.floor(timeMinus) + " seconds ago";
    } else {
        var createDate = new Date(time * 1000);
        var dd = createDate.getDate(),
            mm = createDate.getMonth(),
            y = createDate.getFullYear(),
            hh = createDate.getHours(),
            ii = createDate.getMinutes();
        return (dd + '.' + mm + '.' + y + ' ' + hh + ':' + ii);
    }
};

Nov 12, 2015

Notification, Socket IO, Node JS server

File server.js
/**
 * Notification - NodeJS server
 * Created by UTC.KongLtn on 11/5/2015.
 * @author UTC.KongLtn
 */


var app       =     require("express")();
var mysql     =     require("mysql");
var http      =     require("http").Server(app);
var io        =     require("socket.io")(http);
var async = require("async");


/**
 * Object stores all socket.
 * @type {{sockets: {}, addSocket: Function, removeSocket: Function, getSocketByName: Function}}
 */
var allSockets = {
    /**
     * A storage object to hold the sockets
     */
    sockets: {},

    /**
     * Adds a socket to the storage object so it can be located by name
     * @param socket
     * @param name
     */
    addSocket: function(socket, name) {
        if (this.sockets[name] === undefined) {
            console.log("new array ");
            this.sockets[name] = [];
        }
        console.log("push socket "+ name + " - total: "+this.sockets[name].length);
        this.sockets[name].push(socket);
    },
    /**
     * Removes a socket from the storage object based on its name
     * @param name
     */
    removeSocket: function(name) {
        if (this.sockets[name] !== undefined) {
            this.sockets[name] = null;
            delete this.sockets[name];
        }
    },
    /**
     * Throws an exception if the name is not valid
     * @param name
     * @returns {*} Returns a socket from the storage object based on its name
     */
    getSocketByName: function(name) {
        if (this.sockets[name] !== undefined) {
            return this.sockets[name];
        } else {
            throw new Error("A socket with the name '"+name+"' does not exist");
        }
    },
    /**
     * Check exists of Socket by id
     * @param name
     * @returns {boolean}
     */
    existsSocket: function(name) {
        return (this.sockets[name] !== undefined);
    }
};

/**
 * Creating POOL MySQL connection.
 */
var pool    =    mysql.createPool({
    connectionLimit   :   100,
    host              :   '192.168.2.135',
    user              :   'root',
    password          :   'root',
    database          :   'mentor'
});

/**
 * Default Namespace
 */
app.get("/",function(req,res){
    res.sendFile(__dirname + '/index.html');
});

/**
 *  This is auto initiated event when Client connects to Your server.
 */
io.on('connection',function(socket){
    // When user login, f5, ...
    socket.on('getSocketUser', function(data){
        allSockets.addSocket(socket.id, data.userId);
        countMessage(data.userId,function(data2){
            socket.emit("countMessages",data2);
        });
    });

    socket.on('userCreateNewMessage', function(data){
        console.log('userCreateNewMessage');
        console.log(data);
        if (data.relatedIds !== undefined && data.relatedIds.length > 0) {
            data.relatedIds.forEach(function(userId){
                countMessForSocketsByUserId(userId, function(cb){
                    if (cb) console.log("done => "+userId);
                });
                pushMessage(userId,data.idMessage);
            })
        }

    });

    // When user exit
    socket.on('disconnect', function () {
        console.log("id of socket: " + socket.id );
        console.log("disconnected - count clients "+io.engine.clientsCount);
        for(var uId in allSockets.sockets) {
            if (allSockets.sockets.hasOwnProperty(uId) && allSockets.existsSocket(uId)) {
                var socketIndex = allSockets.sockets[uId].indexOf(socket.id);
                allSockets.sockets[uId].splice(socketIndex, 1);
            }
        }
        countClients();
    });
    countClients();
});

/**
 * Push message to related clients ny userId
 * @param userId
 * @param idMessage
 */
function pushMessage(userId,idMessage){
    if (allSockets.sockets.hasOwnProperty(userId) && allSockets.existsSocket(userId)) {
        var sockets = allSockets.getSocketByName(userId);
        sockets.forEach(function (socId) {
            console.log("socket cua userId  "+socId);
            if (io.sockets.connected[socId] !== undefined) {
                io.sockets.connected[socId].emit("pushMessages", idMessage);
            }
        });
    }
}

/**
 * Count clients
 */
function countClients(){
    console.log("Clients "+ io.engine.clientsCount);
}

/**
 * Count message and emit to all socket by user id
 * @param uId
 * @param cb - finish pointer
 */
function countMessForSocketsByUserId(uId, cb){
    if (allSockets.sockets.hasOwnProperty(uId) && allSockets.existsSocket(uId)) {
        var sockets = allSockets.getSocketByName(uId);

        countMessage(uId, function (count) {
            console.log('dem truoc khi go '+sockets.length);
            sockets.forEach(function (socId) {
                console.log('go '+socId);
                if (io.sockets.connected[socId] !== undefined) {
                    io.sockets.connected[socId].emit("countMessages", count);
                }
            });
            cb(true);
        });
    }
}

/**
 * Test store notifications to Database
 * @param userId
 * @param callback
 * @return undefined
 */
var countMessage = function (userId,callback) {
    pool.getConnection(function(err,connection){
        if (err) {
            connection.release();
            callback(false);
            return;
        }
        var queryCountMessage = 'select count(*) as numMess from notify_user nu ' +
            ' inner join users u on nu.userId= u.idUser ' +
            ' inner join ( '+
            ' select n.*,u2.firstName as createFirstName,u2.lastName as createLastName '+
            ' from notify n '+
            ' inner join users u2 on n.createUserId= u2.idUser '+
            ') temp on nu.notifyId = temp.notifyId ' +
            ' where nu.userId = ' +userId +' and temp.typeNotify = "MESS" and nu.isRead =0;';

        connection.query(queryCountMessage,function(err,rows){
            connection.release();
            if(!err) {
                callback(JSON.stringify(rows));
            }
        });
        //connection.on('error', function(err) {
        //    callback(false);
        //    if (err) console.log(err);
        //});
    });
};

/**
 * Sever is running on port 3000
 */
http.listen(3000,function(){
    console.log("Listening on 3000");
});


File index.html


<html>
<head>
    <title>Socket.io</title>
    <script src="/socket.io/socket.io.js"></script>
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
    <div style = "padding:20px;">
        Hello! This is NodeJS server.
    </div>
</body>
</html>

File socket_client.js


/**
 * Socket IO client
 * @author UTC.KongLtn
 * Created by UTC.KongLtn on 11/11/2015.
 */


/**
 * Variables of socket Event
 * @type {{wrapId: string, createMessagesButton: string, messageMenu: string}}
 */
var socketEventId = {
    wrapId: "#notify_wrap",
    createMessagesButton: "#createMessagesButton",
    messageMenu: "#messageMenu",
    createMessagesForm: "#createMessagesForm"
};
var socket = null;
/**
 * Socket Event
 * @type {{init: Function, connectSocket: Function}}
 */
var socketEvent = {
    init: function(){
        var isGuest = $('#isGuest').val();
        if (isGuest !== "0") {
            this.connectSocket(isGuest);
        }
    },
    /**
     * Create socket connect to nodeJS server
     * @param userId
     */
    connectSocket: function(userId) {
        // Create a connection to NodeJS server port 3000
        socket = io.connect('http://127.0.0.1:3000');

        /**
         * Post userId to NodeJS server
         * @return undefined
         */
        socket.on('connect', function (data) {
            socket.emit('getSocketUser',{ userId:userId });
        });

        /**
         * Show message total
         * @param result
         * @return undefined
         */
        socket.on('countMessages', function(result){
            var data = JSON.parse(result);
            var count = data[0].numMess;
            socketEvent.showMessageTotal(count);
        });

        socket.on('pushMessages', function(idMessage){
            infoMessagesFormEvent.pushContentMessage(idMessage);
        });

        /**
         * Event create message on current socket.
         * @return undefined
         */
    },
    socketEmitCountMess:function(idArray,idMessage) {
        console.log(idMessage);
        console.log(idArray);
        socket.emit('userCreateNewMessage', {idMessage: idMessage, relatedIds: idArray});
    },
    /**
     * Show Message Total
     * @param count
     * @return undefined
     */
    showMessageTotal: function(count){
        $(socketEventId.messageMenu +' > span').remove();
        if (count !== undefined && count > 0) {
            $(socketEventId.messageMenu).append("<span>"+count+"</span>");
        }
    }
};


$(document).ready(function(){
    'use strict';
    socketEvent.init();

});