Completed
Push — master ( 506749...99ae87 )
by Jean-Christophe
03:59
created

RestServer::connect()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 7
ccs 6
cts 6
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Ubiquity\controllers\rest;
4
5
use Ubiquity\controllers\Startup;
6
use Ubiquity\cache\ClassUtils;
7
use Ubiquity\cache\CacheManager;
8
use Ubiquity\exceptions\RestException;
9
10
/**
11
 *
12
 * @author jc
13
 *
14
 */
15
class RestServer {
16
	/**
17
	 *
18
	 * @var array
19
	 */
20
	protected $config;
21
	protected $headers;
22
	protected $tokensFolder;
23
	protected $tokensCacheKey="_apiTokens";
24
	/**
25
	 *
26
	 * @var ApiTokens
27
	 */
28
	protected $apiTokens;
29
30 2
	public function __construct(&$config) {
31 2
		$this->config=$config;
32 2
		$this->headers=[ 'Access-Control-Allow-Origin' => 'http://127.0.0.1:4200','Access-Control-Allow-Credentials' => 'true','Access-Control-Max-Age' => '86400','Access-Control-Allow-Methods' => 'GET, POST, OPTIONS, PUT, DELETE, PATCH, HEAD' ];
33 2
	}
34
35 1
	public function connect(RestController $controller) {
36 1
		if (!isset($this->apiTokens)) {
37 1
			$this->apiTokens=$this->_getApiTokens();
38
		}
39 1
		$token=$this->apiTokens->addToken();
40 1
		$this->_addHeaderToken($token);
41 1
		echo $controller->_format([ "access_token" => $token,"token_type" => "Bearer","expires_in" => $this->apiTokens->getDuration() ]);
42 1
	}
43
44
	/**
45
	 * Check if token is valid
46
	 * @return boolean
47
	 */
48 1
	public function isValid() {
49 1
		$this->apiTokens=$this->_getApiTokens();
50 1
		$key=$this->_getHeaderToken();
51
		if ($this->apiTokens->isExpired($key)) {
52
			return false;
53
		} else {
54
			$this->_addHeaderToken($key);
55
			return true;
56
		}
57
	}
58
59 1
	public function _getHeaderToken() {
60 1
		$authHeader=$this->_getHeader("Authorization");
61 1
		if ($authHeader !== false) {
62
			list ( $type, $data )=explode(" ", $authHeader, 2);
63
			if (\strcasecmp($type, "Bearer") == 0) {
64
				return $data;
65
			} else {
66
				throw new RestException("Bearer is required in authorization header.");
67
			}
68
		} else {
69 1
			throw new RestException("The header Authorization is required in http headers.");
70
		}
71
	}
72
73 2
	public function finalizeTokens() {
74 2
		if (isset($this->apiTokens)) {
75 1
			$this->apiTokens->removeExpireds();
76 1
			$this->apiTokens->storeToCache();
77
		}
78 2
	}
79
80 1
	public function _getHeader($header) {
81 1
		$headers=getallheaders();
82 1
		if (isset($headers[$header])) {
83
			return $headers[$header];
84
		}
85 1
		return false;
86
	}
87
88 1
	public function _addHeaderToken($token) {
89 1
		$this->_header("Authorization", "Bearer " . $token);
90 1
	}
91
92
	/**
93
	 * To override for defining another ApiToken type
94
	 * @return ApiTokens
95
	 */
96 2
	public function _getApiTokens() {
97 2
		return ApiTokens::getFromCache(CacheManager::getAbsoluteCacheDirectory(). \DS, $this->tokensCacheKey);
98
	}
99
100
	/**
101
	 *
102
	 * @param string $headerField
103
	 * @param string $value
104
	 * @param boolean $replace
105
	 */
106 2
	public function _header($headerField, $value=null, $replace=null) {
107 2
		if (!isset($value)) {
108 2
			if (isset($this->headers[$headerField])) {
109 2
				$value=$this->headers[$headerField];
110
			} else
111
				return;
112
		}
113 2
		\header(trim($headerField) . ": " . trim($value), $replace);
114 2
	}
115
116
	/**
117
	 *
118
	 * @param string $contentType default application/json
119
	 * @param string $charset default utf8
120
	 */
121 2
	public function _setContentType($contentType, $charset=null) {
122 2
		$value=$contentType;
123 2
		if (isset($charset))
124
			$value.="; charset=" . $charset;
125 2
		$this->_header("Content-type", $value);
126 2
	}
127
128 2
	public function cors() {
129 2
		$this->_header('Access-Control-Allow-Origin');
130 2
		$this->_header('Access-Control-Allow-Credentials');
131 2
		$this->_header('Access-Control-Max-Age');
132 2
		if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
133
			if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
134
				$this->_header('Access-Control-Allow-Methods');
135
136
			if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
137
				$this->_header('Access-Control-Allow-Headers', $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
138
			} else {
139
				$this->_header('Access-Control-Allow-Headers', '*');
140
			}
141
			throw new RestException("cors exit normally");
142
		}
143 2
	}
144
145 1
	public static function getRestNamespace() {
146 1
		$config=Startup::getConfig();
147 1
		$controllerNS=$config["mvcNS"]["controllers"];
148 1
		$restNS="";
149 1
		if (isset($config["mvcNS"]["rest"])) {
150 1
			$restNS=$config["mvcNS"]["rest"];
151
		}
152 1
		return ClassUtils::getNamespaceFromParts([ $controllerNS,$restNS ]);
153
	}
154
}
155