<?php
namespace Extension;
 use TCMS\HookExtension;
 class ApiAuthHookDefault extends HookExtension {
 private $isAPI = false;
 public function startup() {
 include_once(CONFIG_PATH . 'role.php');
 $auth = load_auth();
 if($auth) {
 $this->isAPI = true;
 if(full_url() == $auth->loginUrl) {
 $this->getApiToken($auth);
 }
 }
 }
 private function getApiToken(\TCMS\AuthExtension $auth) {
 header("Access-Control-Allow-Origin: *");
 header("Content-Type: application/json; charset=UTF-8");
 header("Access-Control-Allow-Methods: POST,GET,PUT,DELETE,PATCH");
 header("Access-Control-Max-Age: 3600");
 header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
 if(!\Request::isPost()) {
 http_response_code(405);
 exit();
 }
 $username = \Request::get('username');
 if($username === false) {
 http_response_code(401);
 exit();
 }
 $password = \Request::get('password');
 if($password === false) {
 http_response_code(401);
 exit();
 }
 $res = $auth->login((string)$username, (string)$password);
 if($res != null) {
 http_response_code(200);
 echo json_encode( $res );
 }
 else {
 http_response_code(401);
 }
 exit();
 }
 public function beforeModuleLoad($module) {
 if($this->isAPI) {
 $auth = load_auth();
 if($auth) {
 $user = $auth->auth();
 if($user) {
 if($module->middleware(route_name(), $auth) === false) {
 if(\RoleGlobal::$role->lastRoleCalled) {
 $r = \RoleGlobal::$role->getRole(\RoleGlobal::$role->lastRoleCalled);
 throw new \TCMS\TException(lang('unauthorized.authorized'). ' ' . $r->name . ' ' . $r->group, 401);
 }
 else {
 if(strpos(route_name(), 'index') !== false) throw new \TCMS\TException(lang('unauthorized.view'), 401);
 else if(strpos(route_name(), 'create') !== false) throw new \TCMS\TException(lang('unauthorized.create'), 401);
 else if(strpos(route_name(), 'update') !== false) throw new \TCMS\TException(lang('unauthorized.update'), 401);
 else if(strpos(route_name(), 'delete') !== false) throw new \TCMS\TException(lang('unauthorized.delete'), 401);
 else throw new \TCMS\TException(lang('unauthorized.unauthorized'), 401);
 }
 }
 return;
 }
 throw new \TCMS\TException('Vui lòng đăng nhập', 401);
 }
 }
 }
 }
 ?>