<?php
require_once("./class/vendor/autoload.php");
use \Firebase\JWT\JWT;

class GAuth{
    private static $secret_key = 'Sdw1s9x8@';
    private static $encrypt = ['HS256'];
    private static $aud = null;
    
    public static function SignIn($data){
        $time = time();
        $token = array(
            'exp' => $time + (60*60),
            'aud' => self::Aud(),
            'data' => $data
        );

        return JWT::encode($token, self::$secret_key);
    }
    
    public static function Check($token){
        if(empty($token)){
            throw new GException("Vaya! ocurrio un problema en el sistema.<br/>Consulte con el Soporte Tecnico<br/>", 'Invalid token supplied.', '--');
        }
        
        $decode = JWT::decode(
            $token,
            self::$secret_key,
            self::$encrypt
        );
        if($decode->aud !== self::Aud()){
            throw new GException("Vaya! ocurrio un problema en el sistema.<br/>Consulte con el Soporte Tecnico<br/>", "Invalid user logged in.", '--');
        }
    }
    
    public static function GetData($token){
        return JWT::decode(
            $token,
            self::$secret_key,
            self::$encrypt
        )->data;
    }
    
    private static function Aud(){
        $aud = '';
        
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $aud = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $aud = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $aud = $_SERVER['REMOTE_ADDR'];
        }
        
        $aud .= @$_SERVER['HTTP_USER_AGENT'];
        $aud .= gethostname();
        
        return sha1($aud);
    }

    public static function getAuthorization(){
        if(!function_exists('apache_request_headers')){
            if(isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION'])){
                $a_token=explode(' ', $_SERVER['HTTP_AUTHORIZATION']);
            }
        }else{
            $headers = apache_request_headers();
            if(isset($headers['authorization']) || isset($headers['Authorization'])){
                $h_autorization=(isset($headers['authorization']))?$headers['authorization']:$headers['Authorization'];
                $a_token=explode(' ', $h_autorization);
            }
        }
        return (isset($a_token) && count($a_token)==2)?$a_token[1]:false;
    }
}
?>