Skip to content

Commit 63bf6af

Browse files
committed
Primo commitì
Fatta la classe che recupera il token ed istanzia le altre classi
0 parents  commit 63bf6af

8 files changed

Lines changed: 473 additions & 0 deletions

File tree

OpenApi.php

Lines changed: 319 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,319 @@
1+
<?php namespace OpenApi;
2+
if (session_status() == PHP_SESSION_NONE) {session_start();}
3+
class OpenApi {
4+
5+
6+
/**
7+
* @param array $scopes Array con gli scopes da utilizzare nel formato: ["domain"=>"ws.ufficiopostale.com", "method"=>"comuni","mode"=>"GET"] oppure "GET:ws.ufficiopostale.com/comuni NOTA: il dominio NON deve mai avere lo stage
8+
* @param string $username Username openapi
9+
* @param string $apikey ApiKey openapi
10+
* @param mixed $environment='test' uno tra: dev, test (default), production
11+
*/
12+
function __construct(array $scopes, string $username, string $apikey, $environment='test'){
13+
14+
$this->cache = new \OpenApi\classes\utility\DummyCache;
15+
$this->header = null;
16+
$this->rawResponse = null;
17+
$realScopes = [];
18+
$prefix = $environment=="production"?"":$environment.".";
19+
$domains = [];
20+
foreach($scopes as $s){
21+
if(is_array($s)){
22+
$domain = $s['domain'];
23+
$realScope = $s['mode'].":".$prefix.$s['domain']."/".$s['method'];
24+
}else{
25+
$realScope = str_replace(":",":{$prefix}", $s) ;
26+
$domain = explode(":", $s)[1];
27+
$domain = explode("/", $domain)[0];
28+
}
29+
if(!in_array($domain, $domains)){
30+
$domains[] = $domain;
31+
}
32+
if(!in_array($realScope,$realScopes)){
33+
$realScopes[] = $realScope;
34+
}
35+
}
36+
$this->username = $username;
37+
$this->apikey = $apikey;
38+
$this->prefix = $prefix;
39+
$this->scopes = $realScopes;
40+
$token = $this->getToken();
41+
42+
43+
$moduli['ws.ufficiopostale.com'] = "\\OpenApi\\classes\\UfficioPostale";
44+
$nomi['ws.ufficiopostale.com'] = "ufficiopostale";
45+
$moduli['imprese.altravia.com'] = "\\OpenApi\\classes\\Imprese";
46+
$nomi['imprese.altravia.com'] = "imprese";
47+
$clients = [];
48+
foreach($domains as $d){
49+
if(isset($moduli[$d])){
50+
$modulo = $moduli[$d];
51+
$nome = $nomi[$d];
52+
$this->$nome = new $modulo($token->token, $this->cache);
53+
$clients[] = $this->$nome;
54+
}
55+
}
56+
}
57+
58+
59+
/**
60+
* Imposta la calsse da utilizzare sistema di cache, deve essere una classe che estende
61+
* {@see OpenApi\clasess\utility\DummyCache}
62+
*
63+
* @param mixed $cacheSys Istanza della classe da usare come sistema di cache
64+
* @return void
65+
*/
66+
function setCacheSystem($cacheSys){
67+
$this->cache = $cacheSys;
68+
foreach($this->clients as $c){
69+
$c->setCacheSystem($cacheSys);
70+
}
71+
}
72+
73+
74+
/**
75+
*
76+
* Restituisce il token attualemnte in sessione, se non presente o non più valido lo rigenera
77+
*
78+
* @param boolean $force=FALSE Se impostato a TRUE forza la rigenerazione del token
79+
* @return object il token
80+
*/
81+
function getToken($force=FALSE){
82+
if(!$force && !$this->isTokenCompatible()){
83+
84+
//TODO: Controllare se il token è ancora valido
85+
if(!$this->mustRfreshToken()){
86+
return $_SESSION['openapi']['token'];
87+
}
88+
$this->renewToken();
89+
90+
return $_SESSION['openapi']['token'];
91+
}
92+
if($this->getOldToken()){
93+
if(!$this->mustRfreshToken()){
94+
return $_SESSION['openapi']['token'];
95+
}
96+
$this->renewToken();
97+
return $_SESSION['openapi']['token'];
98+
}
99+
return $this->generateNewToken();
100+
}
101+
102+
103+
/**
104+
* Rinnova il token in sessione
105+
*
106+
* @return object
107+
*/
108+
private function renewToken(){
109+
$param = ["expire" => 86400, "scopes" => $this->scopes];
110+
//var_dump($param);exit;
111+
112+
$token = $this->connect("token/".$_SESSION['openapi']['token']->token,$param,"PUT");
113+
114+
if($token == NULL){
115+
throw new \OpenApi\classes\exception\OpenApiTokenException("REnew Token: Connection Error",40001);
116+
}
117+
if($token->success == false){
118+
$message = "REnew Token: unknow error";
119+
if(isset($token->message)) {
120+
$message = "REnew Token: $token->message";
121+
}
122+
$except = new \OpenApi\classes\exception\OpenApiTokenException($message,40002);
123+
$except->setServerResponse($token, $this->header, $this->rawResponse);
124+
125+
throw $except;
126+
}
127+
if(isset($token->data) && isset($token->data[0]))
128+
{
129+
$token = $token->data[0];
130+
$_SESSION['openapi']['token'] = $token;
131+
return $token;
132+
}
133+
134+
}
135+
136+
137+
/**
138+
* Controlla se il token in sessione deve essere o meno rinnovato in base alla sua data di scadenza
139+
*
140+
* @return bool
141+
*/
142+
private function mustRfreshToken(){
143+
$token = $_SESSION['openapi']['token'];
144+
$diff = $token->expire-date("U");
145+
if($diff <= 6000){
146+
return TRUE;
147+
}
148+
return FALSE;
149+
}
150+
151+
152+
/**
153+
*
154+
* Recupera la lista di token per verificare se esiste uno utilizzabile con gli scopes di interesse,
155+
* se si lo mette in sessione e ritorna TRUE
156+
*
157+
* @return boolean
158+
*/
159+
function getOldToken(){
160+
$param = ["scopes" => $this->scopes];
161+
$token = $this->connect("token",$param,"GET");
162+
$finded_token = NULL;
163+
164+
if($token != NULL && isset($token->data)){
165+
foreach($token->data AS $token){
166+
if($this->hasValidScopes($token)){
167+
$finded_token = $token;
168+
break 1;
169+
}
170+
}
171+
172+
if($finded_token != NULL){
173+
$_SESSION['openapi']['token'] = $finded_token;
174+
$_SESSION['openapi']['apikey'] = $this->apikey;
175+
$_SESSION['openapi']['scopes'] = serialize($this->scopes);
176+
$_SESSION['openapi']['username'] = $this->username;
177+
$_SESSION['openapi']['prefix'] = $this->prefix;
178+
return TRUE;
179+
}
180+
return FALSE;
181+
}
182+
}
183+
184+
function hasValidScopes($token){
185+
foreach($this->scopes as $s){
186+
if(!in_array($s, $token->scopes)){
187+
return false;
188+
}
189+
}
190+
return true;
191+
}
192+
193+
/**
194+
* Genera un nuovo token
195+
* @return object il token
196+
*/
197+
private function generateNewToken(){
198+
$param = ["scopes" => $this->scopes];
199+
$token = $this->connect("token",$param,"POST");
200+
if($token == NULL){
201+
throw new \OpenApi\classes\exception\OpenApiTokenException("Getting Token: Connection Error",40001);
202+
}
203+
if($token->success == false){
204+
$message = "Getting Token: unknow error";
205+
if(isset($token->message)) {
206+
$message = "Getting Token: $token->message";
207+
}
208+
$except = new \OpenApi\classes\exception\OpenApiTokenException($message,40002);
209+
$except->setServerResponse($token, $this->header, $this->rawResponse);
210+
211+
throw $except;
212+
}
213+
214+
$invalid_scopes = [];
215+
foreach($this->scopes as $s){
216+
if(!in_array($s, $token->scopes)){
217+
$invalid_scopes[] = $s;
218+
}
219+
}
220+
if(count($invalid_scopes)>0){
221+
$message = "Getting Token: unknow error";
222+
if(isset($token->message)) {
223+
224+
}
225+
$message = "Getting Token: invalid scopes (".implode($invalid_scopes).")";
226+
$except = new \OpenApi\classes\exception\OpenApiTokenException($message,40003);
227+
$except->setServerResponse($token, $this->header, $this->rawResponse);
228+
throw $except;
229+
}
230+
$_SESSION['openapi']['token'] = $token;
231+
$_SESSION['openapi']['apikey'] = $this->apikey;
232+
$_SESSION['openapi']['scopes'] = serialize($this->scopes);
233+
$_SESSION['openapi']['username'] = $this->username;
234+
$_SESSION['openapi']['prefix'] = $this->prefix;
235+
return $token;
236+
}
237+
238+
239+
/**
240+
*
241+
* Constrolla se il token in sessione è compatibile con la richiesta
242+
*
243+
* @return boolean
244+
*/
245+
private function isTokenCompatible() {
246+
if(!isset($_SESSION['openapi'])|| !isset($_SESSION['openapi']['token'])){
247+
return TRUE;
248+
}
249+
if($_SESSION['openapi']['prefix'] != $this->prefix || $_SESSION['openapi']['apikey'] != $this->apikey || $_SESSION['openapi']['username'] != $this->username){
250+
return TRUE;
251+
}
252+
$sessionScopes = unserialize($_SESSION['openapi']['scopes']);
253+
if(!is_array($sessionScopes)){
254+
return TRUE;
255+
}
256+
foreach($this->scopes as $s){
257+
if(!in_array($s, $sessionScopes)){
258+
return TRUE;
259+
}
260+
}
261+
return FALSE;
262+
}
263+
264+
265+
/**
266+
* Effettua una connessione al server oauth
267+
*
268+
* @param string $endpoint path da recuperare
269+
* @param array $param Lista dei parametri da passare
270+
* @param mixed $mode metodo http da usare per la chiamata
271+
* @return object
272+
*/
273+
private function connect(string $endpoint, $param = [], $mode="POST"){
274+
275+
$this->header = null;
276+
$this->rawResponse = null;
277+
$basePath = "https://".$this->prefix."oauth.altravia.com";
278+
$url = $basePath."/".$endpoint;
279+
280+
281+
$ch = curl_init($url);
282+
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $mode);
283+
if($mode == "POST" || $mode == "PUT")
284+
{
285+
curl_setopt($ch, CURLOPT_POST, TRUE);
286+
}
287+
if($mode == "GET")
288+
{
289+
$param = http_build_query($param);
290+
$url .= "?".$param;
291+
292+
}else{
293+
$param = json_encode($param);
294+
295+
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
296+
}
297+
298+
$baseauth = base64_encode($this->username.":".$this->apikey);
299+
$headers = array(
300+
'Content-Type:application/json',
301+
'Authorization: Basic '. $baseauth // <---
302+
);
303+
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
304+
305+
306+
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
307+
308+
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
309+
curl_setopt($ch, CURLOPT_HEADER, 1);
310+
$response = curl_exec($ch);
311+
$this->rawResponse = $response;
312+
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
313+
$this->header = substr($response, 0, $header_size);
314+
$return = substr($response, $header_size);
315+
316+
curl_close($ch);
317+
return json_decode($return);
318+
}
319+
}

classes/Imprese.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<?php
2+
namespace OpenApi\classes;
3+
class Imprese extends OpenApiBase {
4+
5+
}

classes/OpenApiBase.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
namespace OpenApi\classes;
3+
class OpenApiBase {
4+
function __construct($token, $cache){
5+
$this->token = $token;
6+
$this->token = $cache;
7+
}
8+
9+
/**
10+
* Imposta la calsse da utilizzare sistema di cache, deve essere una classe che estende
11+
* {@see OpenApi\clasess\utility\DummyCache}
12+
*
13+
* @param mixed $cacheSys Istanza della classe da usare come sistema di cache
14+
* @return void
15+
*/
16+
function setCacheSystem($cacheSys){
17+
$this->cache = $cacheSys;
18+
}
19+
20+
}

classes/UfficioPostale.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<?php
2+
namespace OpenApi\classes;
3+
class UfficioPostale extends OpenApiBase {
4+
5+
function getCitiesByCap($cap){
6+
echo "QUI";
7+
var_dump($cap);
8+
}
9+
10+
}

0 commit comments

Comments
 (0)