oauth2.php 9.17 KB
Newer Older
Paul Bird's avatar
Paul Bird committed
1 2
<?php
class Oauth2 {
Tariq Khan's avatar
Tariq Khan committed
3
    private $operateUrl     = false;
Paul Bird's avatar
Paul Bird committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
    private $client         = false;
    private $clientSecret   = false;
    private $scope          = false;
    private $accessToken    = false;
    private $refreshToken   = false;
    public $trackingDevices = false;
    public $trackingEntries = false;
    public function __construct($config) {
        if (!is_array($config)) die('Oauth2 needs configuring.');
        foreach($config as $id => $value) {
            if( property_exists('Oauth2', $id) && is_string($value)
                && $id !== 'accessToken' && $id !== 'refreshToken'
            ) $this->$id = $value;
        }
        $this->session();
        $this->postHandler();

        if(isset($_GET['logout'])) $this->logout();
        elseif(isset($_GET['refreshToken'])) $this->refreshAccessToken(true);
        elseif(isset($_GET['entries'])) $this->getTrackingDeviceEntries($_GET['entries']);
        if($this->isUserAuthenticated()) $this->fetchAllDevices();
Tariq Khan's avatar
Tariq Khan committed
25 26
        // Use the following function to test response data for a give endpoint
        //if($this->isUserAuthenticated()) $this->testEndpoint('Calendar');
Paul Bird's avatar
Paul Bird committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    }
    public function __destruct() {
        $_SESSION['refreshToken'] = $this->refreshToken;
    }
    private function session() {
        $session = session_id();
        if(empty($session)) session_start();
        if(!empty($_SESSION['refreshToken'])) {
            $this->refreshToken = $_SESSION['refreshToken'];
            $this->refreshAccessToken();
        }
    }
    private function postHandler() {
        if(isset($_POST['login'])) {
            $this->login($_POST['user'], $_POST['pass']);
        } elseif(isset($_POST['create'])) {
            $this->createTrackingDevice($_POST['trackingdevicename'], $_POST['trackingtype'],
                                        $_POST['uniquedeviceid'], $_POST['siteid'], $_POST['active']);
        } elseif(isset($_POST['add'])) {
            $this->createTrackingDeviceEntry($_POST['trackingentriesname'], $_POST['trackingtype'],
                                        $_POST['contactid']);
        }
        unset($_POST);
    }
    private function logout() {
        $this->accessToken = $this->refreshToken = false;
        session_unset();
        session_destroy();
        header('Location: '.strtok($_SERVER["REQUEST_URI"],'?'));
        exit;
    }
    private function login($user, $pass, $responseHeaders = null) {
        $query = http_build_query(array(
            'grant_type'    => 'password',
            'response_type' => 'access_token',
            'client_id'     => $this->client,
            'client_secret' => $this->clientSecret,
            'scope'         => $this->scope,
            'username'      => $user,
            'password'      => $pass
        ), '', '&');
        $response = $this->httpRequest($this->getTokenEndpoint(), array(
            'method'        => 'POST',
            'header'        => array('Content-type: application/x-www-form-urlencoded'),
            'content'       => $query
        ), $responseHeaders);
        if($response) {
            $this->accessToken = $response->access_token;
            $this->refreshToken = $response->refresh_token;
            echo 'Login success - Response: <pre>'.var_export($response, true).'</pre>';
        } else {
            echo 'Login error - Response: <pre>'.var_export($responseHeaders, true).'</pre>';
        }
    }
    private function refreshAccessToken($manual = false) {
        $query = http_build_query(array(
            'grant_type'    => 'refresh_token',
            'client_id'     => $this->client,
            'client_secret' => $this->clientSecret,
            'scope'         => $this->scope,
            'refresh_token' => $this->refreshToken
        ), '', '&');
        $response = $this->httpRequest($this->getTokenEndpoint(), array(
            'method'        => 'POST',
            'header'        => array('Content-type: application/x-www-form-urlencoded'),
            'content'       => $query
        ), $responseHeaders);
        if($response) {
            $this->accessToken = $response->access_token;
            $this->refreshToken = $response->refresh_token;
            if($manual) echo 'Access token refreshed - Response: <pre>'.var_export($response, true).'</pre>';
        } else {
            echo 'Access token  error - Response: <pre>'.var_export($responseHeaders, true).'</pre>';
        }
    }
Tariq Khan's avatar
Tariq Khan committed
102 103 104 105 106 107 108 109
    private function testEndpoint($endpoint) {
        $options = array(
            'method'        => 'GET',
            'header'        => array(
                'Authorization: Bearer '.$this->accessToken,
                'Accept: application/json'
            )
        );
Tariq Khan's avatar
Tariq Khan committed
110
        $response = $this->httpRequest($this->operateUrl.'/api/1.0/'.$endpoint, $options, $responseHeaders);
Tariq Khan's avatar
Tariq Khan committed
111 112
        highlight_string("<?php\n".var_export($response ? $response->response : $responseHeaders, true).";\n?>");
    }
Paul Bird's avatar
Paul Bird committed
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    private function fetchAllDevices() {
        $options = array(
            'method'        => 'GET',
            'header'        => array(
                'Authorization: Bearer '.$this->accessToken,
                'Accept: application/json'
            )
        );
        $response = $this->httpRequest($this->getTrackingDeviceApiUri(), $options, $responseHeaders);
        if($response) {
            $this->trackingDevices = $response->response->trackingdevices;
        } else {
            echo 'Error fetching tracking devices - Response: <pre>'.var_export($responseHeaders, true).'</pre>';
        }
    }
    private function createTrackingDevice($trackingdevicename, $trackingtype, $uniquedeviceid, $siteid, $active) {
        $data = '[{'.
            "trackingdevicename:'{$trackingdevicename}',".
            "trackingtype:'{$trackingtype}',".
            "uniquedeviceid:'{$uniquedeviceid}',".
            "siteid:'{$siteid}',".
            "active:'{$active}'".
        '}]';
        $options = array(
            'method'        => 'PUT',
            'header'        => array(
                'Authorization: Bearer '.$this->accessToken,
                'Content-Type: text/plain',
                'Accept: application/json'
            ),
            'content'       => 'data={trackingdevices:'.$data.'}'
        );
        $response = $this->httpRequest($this->getTrackingDeviceApiUri(), $options, $responseHeaders);
        if($response) {
            echo 'Tracking device created - Response: <pre>'.var_export($response, true).'</pre>';
        } else {
            echo 'Error creating tracking device - Response: <pre>'.var_export($responseHeaders, true).'</pre>';
        }
    }
    private function getTrackingDeviceEntries($deviceId) {
        $options = array(
            'method'        => 'GET',
            'header'        => array(
                'Authorization: Bearer '.$this->accessToken,
                'Accept: application/json'
            )
        );
        $response = $this->httpRequest($this->getTrackingEntryApiUri()."?where=trackingdeviceid={$deviceId}", $options, $responseHeaders);
        if($response) {
            $this->trackingEntries = $response->response->trackingentriess;
            echo 'Tracking device entries fetched - Response: <code>'.var_export($this->trackingEntries, true).'</code>';
        } else {
            echo 'Error fetching tracking device entries - Response: <pre>'.var_export($responseHeaders, true).'</pre>';
        }
    }
    private function createTrackingDeviceEntry($trackingentriesname, $trackingtype, $contactid) {
        $data = '[{'.
            "trackingdeviceid:'{$_GET['add']}',".
            "trackingentriesname:'{$trackingentriesname}',".
            "trackingtype:'{$trackingtype}',".
            "contactid:'{$contactid}'".
        '}]';
        $options = array(
            'method'        => 'PUT',
            'header'        => array(
                'Authorization: Bearer '.$this->accessToken,
                'Content-Type: text/plain',
                'Accept: application/json'
            ),
            'content'       => 'data={trackingentries:'.$data.'}'
        );
        $response = $this->httpRequest($this->getTrackingEntryApiUri(), $options, $responseHeaders);
        if($response) {
            echo 'Entry created - Response: <pre>'.var_export($response, true).'</pre>';
        } else {
            echo 'Error fetching tracking devices - Response: <pre>'.var_export($responseHeaders, true).'</pre>';
        }
    }
    private function httpRequest($uri, $options = null, &$responseHeaders = null, $raw = false) {
        $context = null;
        if(!empty($options) && is_array($options)) {
            $context = stream_context_create(array('http' => $options));
        }
        $content = @file_get_contents($uri, false, $context);
        $responseHeaders = implode("\r\n", $http_response_header);
        return $raw ? $content : json_decode($content);
    }
    private function getTokenEndpoint() {
Tariq Khan's avatar
Tariq Khan committed
201
        return $this->operateUrl.'/oauth2/token';
Paul Bird's avatar
Paul Bird committed
202 203
    }
    private function getTrackingDeviceApiUri() {
Tariq Khan's avatar
Tariq Khan committed
204
        return $this->operateUrl.'/api/1.0/trackingdevice';
Paul Bird's avatar
Paul Bird committed
205 206
    }
    private function getTrackingEntryApiUri() {
Tariq Khan's avatar
Tariq Khan committed
207
        return $this->operateUrl.'/api/1.0/trackingentries';
Paul Bird's avatar
Paul Bird committed
208 209 210 211 212 213
    }
    public function isUserAuthenticated() {
        return $this->accessToken !== false;
    }
}
?>