From e4f37f76869b1f37dfb620d101c20a1df8081eb5 Mon Sep 17 00:00:00 2001 From: JonatanRek Date: Sat, 25 Apr 2020 18:04:02 +0200 Subject: [PATCH] Authentication Endpoint --- app/Routes.php | 1 + app/api/AuthApi.php | 25 +++++++++++++++++++ app/class/{ApiManager.php => AuthManager.php} | 19 ++++++++++++-- library/ApiController.php | 4 +-- 4 files changed, 45 insertions(+), 4 deletions(-) create mode 100644 app/api/AuthApi.php rename app/class/{ApiManager.php => AuthManager.php} (71%) diff --git a/app/Routes.php b/app/Routes.php index a719639..6116d73 100644 --- a/app/Routes.php +++ b/app/Routes.php @@ -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'] : '')); diff --git a/app/api/AuthApi.php b/app/api/AuthApi.php new file mode 100644 index 0000000..ae8c00e --- /dev/null +++ b/app/api/AuthApi.php @@ -0,0 +1,25 @@ +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(){ + + } +} \ No newline at end of file diff --git a/app/class/ApiManager.php b/app/class/AuthManager.php similarity index 71% rename from app/class/ApiManager.php rename to app/class/AuthManager.php index f559040..24c76b4 100644 --- a/app/class/ApiManager.php +++ b/app/class/AuthManager.php @@ -1,7 +1,7 @@ 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; + } } diff --git a/library/ApiController.php b/library/ApiController.php index c4242d6..9ce05a0 100644 --- a/library/ApiController.php +++ b/library/ApiController.php @@ -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); }