Request.class.php 4.7 KB
Newer Older
Zohten's avatar
Zohten committed
1
<?php
Zohten's avatar
Zohten committed
2 3 4 5 6 7 8

include_once __ROOT_DIR . '/libs/php-jwt/src/BeforeValidException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/ExpiredException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/SignatureInvalidException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/JWT.php';
use \Firebase\JWT\JWT;

Zohten's avatar
Zohten committed
9 10
class Request
{
Zohten's avatar
Zohten committed
11 12 13 14 15
    protected $controllerName;
    protected $uriParameters;
    protected $data;
    protected static $_instance;

Zohten's avatar
Zohten committed
16 17 18 19 20
    public static function getCurrentRequest()
    {
        if (is_null(self::$_instance)) {
            self::$_instance = new Request();
        }
Zohten's avatar
Zohten committed
21
      
Zohten's avatar
Zohten committed
22 23 24 25 26 27 28 29
        return self::$_instance;
    }

    public function __construct()
    {
        $this->initBaseURI();
        $this->initControllerAndParametersFromURI();
        $this->initData();
Zohten's avatar
Zohten committed
30 31
    }

Zohten's avatar
Zohten committed
32 33 34 35 36 37 38
    // intialise baseURI
    // e.g. http://eden.imt-lille-douai.fr/~luc.fabresse/api.php => __BASE_URI = /~luc.fabresse
    // e.g. http://localhost/CDAW/api.php => __BASE_URI = /CDAW
    protected function initBaseURI()
    {
        $this->baseURI = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
    }
Zohten's avatar
Zohten committed
39

Zohten's avatar
Zohten committed
40 41 42 43 44 45 46 47 48 49 50
    // intialise controllerName et uriParameters
    // controllerName contient chaîne 'default' ou le nom du controleur s'il est présent dans l'URI (la requête)
    // uriParameters contient un tableau vide ou un tableau contenant les paramètres passés dans l'URI (la requête)
    // e.g. http://eden.imt-lille-douai.fr/~luc.fabresse/api.php
    //    => controllerName == 'default'
    //       uriParameters == []
    // e.g. http://eden.imt-lille-douai.fr/~luc.fabresse/api.php/user/1
    //    => controllerName == 'user'
    //       uriParameters == [ 1 ]
    protected function initControllerAndParametersFromURI()
    {
Zohten's avatar
Zohten committed
51 52 53 54
        $prefix = $_SERVER['SCRIPT_NAME'];
        $uriParameters = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

        $i=0;
Zohten's avatar
Zohten committed
55 56 57 58 59
        while ($i<strlen($prefix) && $i<strlen($uriParameters)) {
            if ($prefix[$i]===$uriParameters[$i]) {
                $i++;
            }
        }
Zohten's avatar
Zohten committed
60 61 62 63 64 65 66 67 68 69

        $uriParameters = substr($uriParameters, $i);

        $uriParameters = trim($uriParameters, '/');
        $uriSegments = explode('/', $uriParameters);

        $this->controllerName = array_shift($uriSegments) ?: "default";
        $this->uriParameters = $uriSegments;
    }

Zohten's avatar
Zohten committed
70 71 72
    // ==============
    // Public API
    // ==============
Zohten's avatar
Zohten committed
73 74

    // retourne le name du controleur qui doit traiter la requête courante
Zohten's avatar
Zohten committed
75 76 77 78
    public function getControllerName()
    {
        return $this->controllerName;
    }
Zohten's avatar
Zohten committed
79

Zohten's avatar
Zohten committed
80 81 82 83
    public function getUriParams()
    {
        return $this->uriParameters;
    }
Zohten's avatar
Zohten committed
84

Zohten's avatar
Zohten committed
85 86 87 88 89 90 91 92 93 94 95 96 97
    public function initData()
    {
        if ($this->getHttpMethod() === 'PUT' || $this->getHttpMethod() === 'POST') {
            $jsondata=file_get_contents("php://input");
            $this->data = json_decode($jsondata, true);
        }
    }
   
    // retourne la méthode HTTP utilisée dans la requête courante
    public function getHttpMethod()
    {
        return $_SERVER["REQUEST_METHOD"];
    }
Zohten's avatar
Zohten committed
98

Zohten's avatar
Zohten committed
99 100 101 102
    public function getData()
    {
        return $this->data;
    }
Zohten's avatar
Zohten committed
103
    // Return JWT token (string) in Authorization header or throw an exception
Zohten's avatar
Zohten committed
104 105
    public function getJwtToken()
    {
Zohten's avatar
Zohten committed
106 107
        // Field names are case-insensitive : https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html
        $headers = array_change_key_case(getallheaders());
Zohten's avatar
Zohten committed
108 109 110
        if (!isset($headers['authorization'])) {
            throw new Exception("Missing Authorization field");
        }
Zohten's avatar
Zohten committed
111
        $autorization = $headers['authorization'];
Zohten's avatar
Zohten committed
112
        $arr = explode(" ", $autorization);
Zohten's avatar
Zohten committed
113

Zohten's avatar
Zohten committed
114 115 116
        if (count($arr)<2) {
            throw new Exception("Missing JWT token");
        }
Zohten's avatar
Zohten committed
117

Zohten's avatar
Zohten committed
118
        $jwt_token = $arr[1];
Zohten's avatar
Zohten committed
119

Zohten's avatar
Zohten committed
120 121
        return $jwt_token;
    }
Zohten's avatar
Zohten committed
122

Zohten's avatar
Zohten committed
123
    // Return array with decodedJWT or error message if decoding fails
Zohten's avatar
Zohten committed
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
    public function verifyJwtToken()
    {
        try {
            $jwt_token = $this->getJwtToken();
            $decodedJWT = JWT::decode($jwt_token, JWT_BACKEND_KEY, array('HS256'));
            
            $arrayResult = [
                "message" => "Valid token.",
                "decodedJWT" => $decodedJWT
            ];
        } catch (Exception $e) {
            header('WWW-Authenticate: Bearer realm="'.JWT_ISSUER.'"');
   
            $arrayResult = [
                "message" => "Access denied.",
                "error" => $e->getMessage()
            ];
        }
        return $arrayResult;
    }
144

Zohten's avatar
Zohten committed
145
    public function getIpAddr()
146 147 148 149 150 151 152 153 154 155 156
    { 
        if(!empty($_SERVER['HTTP_CLIENT_IP'])){ 
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ 
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; 
        }else{ 
            $ip = $_SERVER['REMOTE_ADDR']; 
        }

        return $ip; 
    } 
Zohten's avatar
Zohten committed
157
}