Passed
Push — master ( 5df63f...4c57ea )
by Jean-Christophe
06:08
created

RestServer::_header()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

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