PHP_SMART_HOME_V3/library/ApiController.php

43 lines
1.1 KiB
PHP
Raw Normal View History

2020-04-24 18:37:05 +02:00
<?php
2020-04-24 21:22:24 +02:00
class ApiController {
2020-04-24 21:57:04 +02:00
protected $input;
2020-05-04 21:19:14 +02:00
protected $authenticated = false;
2020-04-24 18:37:05 +02:00
2020-07-21 10:46:57 +02:00
//TODO: Add Local Switch Only
2020-04-24 18:58:00 +02:00
function __construct() {
2020-04-24 21:22:24 +02:00
$input = file_get_contents('php://input');
2020-05-04 21:19:14 +02:00
2020-04-24 21:22:24 +02:00
if(empty($input)){
$this->input = NULL;
}else{
$this->input = json_decode($input, true);
if(json_last_error() != JSON_ERROR_NONE){
throw new Exception("Invalid request payload", 400);
}
}
}
2020-04-24 18:37:05 +02:00
2020-04-24 21:57:04 +02:00
protected function requireAuth(){
2020-04-25 18:04:02 +02:00
if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
2020-04-24 21:22:24 +02:00
// TODO: call appropriate class/method
$authManager = new AuthManager();
2020-05-25 21:21:38 +02:00
$this->authenticated = $authManager->validateToken($_SERVER['HTTP_AUTHORIZATION']);
2020-04-24 21:22:24 +02:00
if(!$this->authenticated){
2020-04-25 11:38:06 +02:00
throw new Exception("Authorization required", 401);
2020-04-24 21:22:24 +02:00
}
2020-04-24 18:37:05 +02:00
} else {
2020-04-25 11:38:06 +02:00
throw new Exception("Authorization required", 401);
2020-04-24 18:37:05 +02:00
}
2020-04-24 21:22:24 +02:00
}
2020-04-24 18:37:05 +02:00
2020-07-14 19:59:18 +02:00
protected function response($data = [], $httpCode = '200', $contentType = 'application/json', $jsonEncode = true){
header('Content-Type: ' . $contentType);
2020-04-24 21:22:24 +02:00
http_response_code($httpCode);
2020-07-14 19:59:18 +02:00
if ($jsonEncode) {
echo json_encode($data, JSON_UNESCAPED_UNICODE);
} else {
echo $data;
}
2020-04-24 18:37:05 +02:00
}
2020-04-24 21:22:24 +02:00
}