Ubiquity 2.5.2
php rapid development framework
Loading...
Searching...
No Matches
RestServer.php
Go to the documentation of this file.
1<?php
2
4
11
26 protected $config;
27 protected $headers;
28 protected $tokensFolder;
29 protected $tokenLength;
30 protected $tokenDuration;
31 protected $tokensCacheKey = '_apiTokens';
32 protected $allowedOrigins;
33
38 protected $apiTokens;
39
40 public function __construct(&$config, $headers = null) {
41 $this->config = $config;
42 $this->headers = [ 'Access-Control-Allow-Origin' => '*','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' ];
43 if (\is_array ( $headers )) {
44 $this->headers = \array_merge ( $this->headers, $headers );
45 }
46 }
47
48
49 private function tokenCallback($callback){
50 if (! isset ( $this->apiTokens )) {
51 $this->apiTokens = $this->_loadApiTokens ();
52 }
53 $token = $callback();
54 $this->_addHeaderToken ( $token );
55 return [ 'access_token' => $token,'token_type' => 'Bearer','expires_in' => $this->apiTokens->getDuration () ];
56 }
62 public function connect($datas=null) {
63 return $this->tokenCallback(function() use ($datas) {
64 return $this->apiTokens->addToken ($datas);
65 });
66 }
67
73 public function refreshToken(): array {
74 return $this->tokenCallback(function() {
75 $key=$this->_getHeaderToken();
76 return $this->apiTokens->refreshToken($key);
77 });
78 }
79
86 public function isValid($callback) {
87 $this->apiTokens = $this->_loadApiTokens ();
88 $key = $this->_getHeaderToken ();
89 if ($this->apiTokens->isExpired ( $key )) {
90 return false;
91 } else {
92 $token=$this->apiTokens->getToken($key);
93 if($callback($token['datas']??null)) {
94 $this->_addHeaderToken($key);
95 return true;
96 }
97 return false;
98 }
99 }
100
101 public function _getHeaderToken() {
102 $authHeader = $this->_getHeader ( 'Authorization' );
103 if ($authHeader !== false) {
104 $headerDatas = \explode ( ' ', $authHeader, 2 );
105 if (\count( $headerDatas ) === 2) {
106 list ( $type, $data ) = $headerDatas;
107 if (\strcasecmp ( $type, 'Bearer' ) == 0) {
108 return $data;
109 } else {
110 throw new RestException ( 'Bearer is required in authorization header.' );
111 }
112 } else {
113 throw new RestException ( 'The header Authorization is required in http headers.' );
114 }
115 } else {
116 throw new RestException ( 'The header Authorization is required in http headers.' );
117 }
118 }
119
120 public function finalizeTokens() {
121 if (isset ( $this->apiTokens )) {
122 $this->apiTokens->removeExpireds ();
123 $this->apiTokens->storeToCache ();
124 }
125 }
126
127 public function _getHeader($header) {
128 $headers = getallheaders ();
129 if (isset ( $headers [$header] )) {
130 return $headers [$header];
131 }
132 return false;
133 }
134
135 public function _addHeaderToken($token) {
136 $this->_header ( 'Authorization', 'Bearer ' . $token, true );
137 }
138
139 public function _loadApiTokens() {
140 return $this->getApiTokens ()->getFromCache ( CacheManager::getAbsoluteCacheDirectory () . \DS, $this->tokensCacheKey );
141 }
142
143 protected function getApiTokens() {
144 if (! isset ( $this->apiTokens )) {
145 $this->apiTokens = $this->newApiTokens ();
146 }
147 return $this->apiTokens;
148 }
149
155 protected function newApiTokens() {
156 return new ApiTokens ( $this->tokenLength, $this->tokenDuration );
157 }
158
159 protected function getAllowedOrigin() {
160 $http_origin = URequest::getOrigin ();
161 if (\is_array ( $this->allowedOrigins )) {
162 if (\array_search ( $http_origin, $this->allowedOrigins ) !== false) {
163 return $http_origin;
164 }
165 return 'null';
166 }
167 return '*';
168 }
169
171 $origin = $this->getAllowedOrigin ();
172 unset ( $this->headers ['Access-Control-Allow-Origin'] );
173 \header ( 'Access-Control-Allow-Origin: ' . $origin, true );
174 }
175
176 protected function addOtherHeaders() {
177 foreach ( $this->headers as $k => $v ) {
178 $this->_header ( $k, $v );
179 }
180 }
181
188 public function _header($headerField, $value = null, bool $replace = true) {
189 if (! isset ( $value )) {
190 if (isset ( $this->headers [$headerField] )) {
191 $value = $this->headers [$headerField];
192 unset ( $this->headers [$headerField] );
193 } else
194 return;
195 }
196 \header ( \trim ( $headerField ) . ": " . \trim ( $value ), $replace );
197 }
198
204 public function _setContentType($contentType = null, $charset = null) {
205 $value = $contentType;
206 if (isset ( $charset )){
207 $value .= '; charset=' . $charset;
208 }
209 $this->_header ( 'Content-type', $value );
210 }
211
212 public function cors() {
213 $this->setAccessControlAllowOriginHeader ();
214 $this->_header ( 'Access-Control-Allow-Credentials' );
215 $this->_header ( 'Access-Control-Max-Age' );
216 if ($_SERVER ['REQUEST_METHOD'] == 'OPTIONS') {
217 if (isset ( $_SERVER ['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] )){
218 $this->_header ( 'Access-Control-Allow-Methods' );
219 }
220 if (isset ( $_SERVER ['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] )) {
221 $this->_header ( 'Access-Control-Allow-Headers', $_SERVER ['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] );
222 } else {
223 $this->_header ( 'Access-Control-Allow-Headers', '*' );
224 }
225 Logger::info ( 'Rest', 'cors exit normally', 'Cors' );
226 }
227 $this->addOtherHeaders ();
228 }
229
230 public static function getRestNamespace() {
231 $config = Startup::getConfig ();
232 $controllerNS = Startup::getNS('controllers');
233 $restNS = $config ['mvcNS']['rest']??"";
234 return ClassUtils::getNamespaceFromParts ( [ $controllerNS,$restNS ] );
235 }
236
242 public function setAllowedOrigin($address = '*') {
243 if ($address !== '*') {
244 $this->allowedOrigins = [ $address ];
245 } else {
246 $this->allowedOrigins = [ ];
247 }
248 }
249
255 public function setAllowedOrigins($addresses) {
256 $this->allowedOrigins = $addresses;
257 }
258
264 public function addAllowedOrigin($address) {
265 $this->allowedOrigins = [ $address ];
266 }
267
272 public function setTokenLength($tokenLength) {
273 $this->tokenLength = $tokenLength;
274 }
275
280 public function setTokenDuration($tokenDuration) {
281 $this->tokenDuration = $tokenDuration;
282 }
283}
Manager for caches (Router, Rest, models).
Manipulates class and namespace names Ubiquity\cache$ClassUtils This class is part of Ubiquity.
Starts the framework.
Definition Startup.php:19
Manage the token api for the Rest part.
Definition ApiTokens.php:16
newApiTokens()
To override for defining another ApiToken type.
setAllowedOrigin($address=' *')
Adds an unique allowed origin for access control.
refreshToken()
Refresh an active token.
addAllowedOrigin($address)
Adds an allowed origin for access control.
setAllowedOrigins($addresses)
Sets the allowed origins for access control.
_setContentType($contentType=null, $charset=null)
isValid($callback)
Check if token is valid.
__construct(&$config, $headers=null)
_header($headerField, $value=null, bool $replace=true)
connect($datas=null)
Establishes the connection with the server, returns an added token in the Authorization header of the...
Exceptions for Rest service.
Abstract class for logging Ubiquity\log$Logger This class is part of Ubiquity.
Definition Logger.php:14
Http Request utilities, wrapper for accessing to $_GET, $_POST and php://input.
Definition URequest.php:18