Commit 92de9aa7 authored by Zohten's avatar Zohten

refactor auth (2/2)

parent f8092631
......@@ -101,8 +101,7 @@ class Request
{
return $this->data;
}
// returns JWT token in Authorization header or throw an exception
// Return JWT token (string)
// Return JWT token (string) in Authorization header or throw an exception
public function getJwtToken()
{
// Field names are case-insensitive : https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html
......@@ -119,11 +118,11 @@ class Request
return $jwt_token;
}
// Return array with decodedJWT or error message if decoding fails
public function verifyJwtToken()
{
try {
$jwt_token = $this->getJwtToken();
//print_r($jwt_token);die();
$decodedJWT = JWT::decode($jwt_token, JWT_BACKEND_KEY, array('HS256'));
$arrayResult = [
......
......@@ -40,8 +40,7 @@ class LoginController extends Controller
"iss" => JWT_ISSUER,
"data" => array(
"id" => $user->id(),
"firstname" => $user->firstname(),
"lastname" => $user->lastname(),
"role" => $user->role(),
"email" => $user->email()
)
);
......
......@@ -38,6 +38,20 @@ class UserController extends Controller
return Response::errorResponse($message);
}
public function authUser($id, $allowAdmin=True){
// Token phase
$verifyArray = $this->request->verifyJwtToken();
if ($verifyArray['message']!=="Valid token.") {
return Response::unauthorizedResponse($jsonResult);
}
// Auth phase
$data = $verifyArray['decodedJWT']->data;
if (($data->id != $id) && ($data->role != 2)) {
$message = json_encode(["message" => "You don't have access to this account."]);
return Response::unauthorizedResponse($message);
}
}
/**
* Get all users in USER table
*
......@@ -69,17 +83,11 @@ class UserController extends Controller
*/
protected function updateUser($array)
{
// Token phase
$verifyArray = $this->request->verifyJwtToken();
if ($verifyArray['message']!=="Valid token.") {
return Response::unauthorizedResponse($jsonResult);
// Auth with token phase
$authError = $this->authUser($array['id']);
if($authError){
return authError;
}
// Auth phase
if ($verifyArray['decodedJWT']->data->id != $array['id']) {
$message = json_encode(["message" => "You don't have access to this account."]);
return Response::unauthorizedResponse($message);
}
// Update phase
User::updateUser($array);
......
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