Commit f8092631 authored by Zohten's avatar Zohten

refactor auth (1/2)

parent 5f9b4bc7
<?php
include_once __ROOT_DIR . '/libs/php-jwt/src/BeforeValidException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/ExpiredException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/SignatureInvalidException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/JWT.php';
use \Firebase\JWT\JWT;
class Request
{
protected $controllerName;
......@@ -95,6 +102,7 @@ class Request
return $this->data;
}
// returns JWT token in Authorization header or throw an exception
// Return JWT token (string)
public function getJwtToken()
{
// Field names are case-insensitive : https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html
......@@ -110,4 +118,26 @@ class Request
return $jwt_token;
}
public function verifyJwtToken()
{
try {
$jwt_token = $this->getJwtToken();
//print_r($jwt_token);die();
$decodedJWT = JWT::decode($jwt_token, JWT_BACKEND_KEY, array('HS256'));
$arrayResult = [
"message" => "Valid token.",
"decodedJWT" => $decodedJWT
];
} catch (Exception $e) {
header('WWW-Authenticate: Bearer realm="'.JWT_ISSUER.'"');
$arrayResult = [
"message" => "Access denied.",
"error" => $e->getMessage()
];
}
return $arrayResult;
}
}
<?php
include_once __ROOT_DIR . '/libs/php-jwt/src/BeforeValidException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/ExpiredException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/SignatureInvalidException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/JWT.php';
use \Firebase\JWT\JWT;
class UserController extends Controller
{
......@@ -75,21 +70,12 @@ class UserController extends Controller
protected function updateUser($array)
{
// Token phase
try {
$jwt_token = $this->request->getJwtToken();
$decodedJWT = JWT::decode($jwt_token, JWT_BACKEND_KEY, array('HS256'));
} catch (Exception $e) {
header('WWW-Authenticate: Bearer realm="'.JWT_ISSUER.'"');
$jsonResult = json_encode(array(
"message" => "Access denied.",
"error" => $e->getMessage()
));
$verifyArray = $this->request->verifyJwtToken();
if ($verifyArray['message']!=="Valid token.") {
return Response::unauthorizedResponse($jsonResult);
}
// Auth phase
if ($decodedJWT->data->id != $array['id']) {
if ($verifyArray['decodedJWT']->data->id != $array['id']) {
$message = json_encode(["message" => "You don't have access to this account."]);
return Response::unauthorizedResponse($message);
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment