Authentication Endpoint

This commit is contained in:
JonatanRek 2020-04-25 18:04:02 +02:00
parent 8300e47b76
commit e4f37f7686
4 changed files with 45 additions and 4 deletions

View File

@ -19,5 +19,6 @@ $router->any('/log', 'Log');
$router->any('/rooms', 'Rooms');
$router->get('/api/devices', 'DevicesApi@getAllDevices');
$router->get('/api/login', 'AuthApi@login');
$router->run($_SERVER['REQUEST_METHOD'], '/'.(isset($_GET['url']) ? $_GET['url'] : ''));

25
app/api/AuthApi.php Normal file
View File

@ -0,0 +1,25 @@
<?php
class AuthApi {
static function login(){
$token = (new ApiManager)->getToken($this->input->username,$this->input->password);
if (!$token) {
throw new Exception("Auth failed", 401);
}
$this->response(['token' => $token]);
}
static function logout(){
$authenticationBearrer = $_SERVER['HTTP_AUTHORIZATION'];
if (!(new ApiManager)->deleteToken($authenticationBearrer)) {
throw new Exception("logout Failed", 401);
}
}
static function registration(){
}
static function restartPassword(){
}
}

View File

@ -1,7 +1,7 @@
<?php
class ApiManager {
public function generateToken($username, $password){
class AuthManager {
public function getToken($username, $password){
$userManager = new UserManager();
if ($username != '' || $password != ''){
$userLogedIn = $userManager->loginNew($username, $password);
@ -27,4 +27,19 @@ class ApiManager {
}
return false;
}
public function deleteToken($token){
Db::command ('DELETE FROM tokens WHERE token=?', array ($token));
return true;
}
public function validateToken($token){
$tokens = Db::loadAll('SELECT * FROM tokens WHERE token = ? AND expire >= CURRENT_TIMESTAMP AND blocked = 0;', array($token));
if (count($tokens) == 1) {
return true;
} else if (count($tokens) == 0) {
return false;
};
return false;
}
}

View File

@ -18,10 +18,10 @@ class ApiController {
}
protected function requireAuth(){
if (isset($this->headers['HTTP_AUTHORIZATION'])) {
if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
// TODO: call appropriate class/method
$authManager = new AuthManager();
$this->authenticated = $authManager>validateToken($this->headers['HTTP_AUTHORIZATION']);
$this->authenticated = $authManager>validateToken($_SERVER['HTTP_AUTHORIZATION']);
if(!$this->authenticated){
throw new Exception("Auth required", 401);
}