Test Failed
Push — master ( 7df265...08d2f1 )
by Jean-Christophe
06:27
created

RestServer::cors()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 7.456

Importance

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