apollosc/api/application/helpers/authorization_helper.php
2018-09-18 12:57:06 +05:30

93 lines
3.1 KiB
PHP

<?php
class AUTHORIZATION
{
public static function validateTimestamp()
{
$CI =& get_instance();
$headersData = getallheaders();
if (!array_key_exists("Token",$headersData))
{
set_status_header(REST_CONTROLLER::HTTP_OK,"OK");
$response['status']=false;
$response['error']="Token required!";
// echo json_encode($response);
exit;
}
else{
$token = self::validateToken($headersData['Token']);
//echo "else";
// echo now() . "===". $token->exp ."====".($CI->config->item('token_timeout') *60);
// die;
if($token != false && (now() - $token->exp < ($CI->config->item('token_timeout') * 60))){
echo "if";
set_status_header(200,"OK");
return $token;
}
else if($token == false){
echo "else";
set_status_header(REST_CONTROLLER::HTTP_UNAUTHORIZED,"Unauthorized");
$response['status']=false;
$response['error']="Invalid token!";
echo json_encode($response);
exit;
}
// if ($token != false && (now() - $token->iat < ($CI->config->item('token_timeout') * 60))) {
// return $token;
// }
else{
//set_status_header(REST_CONTROLLER::HTTP_UNAUTHORIZED,"Unauthorized");
//$tokenData['status'] = false;
$tokenData['ID'] = $token->ID;
$tokenData['UserType'] = $token->UserType;
$tokenData['MobileNumber'] = $token->MobileNumber;
$tokenData['BranchCode'] = $token->BranchCode;
$tokenData['Admin'] = $token->Admin;
$tokenData['iat'] = strtotime("now");
$tokenData['exp'] = strtotime("+2 minutes");
$response['token'] = self::generateToken($tokenData);
$response['status'] = false;
$CI->response($response);
//exit;
}
}
}
public static function validateToken($token)
{
$CI =& get_instance();
return JWT::decode($token, $CI->config->item('jwt_key'));
}
public static function generateToken($data)
{
$CI =& get_instance();
return JWT::encode($data, $CI->config->item('jwt_key'));
}
//check authorization user or not
public static function checkAuthorizationUser($routingName){
$CI =& get_instance();
$headersData = getallheaders();
if (!array_key_exists("Authorization",$headersData) OR $headersData['Authorization']!=$CI->config->item('authorization_key'))
{
set_status_header(REST_CONTROLLER::HTTP_UNAUTHORIZED,"Unauthorized");
$response['status']=false;
$response['error']="Access denied!";
echo json_encode($response);
exit;
}
else if($routingName!=ROUTE_LOGIN){
$validateToken = self::validateTimestamp();
return $validateToken;
}
else{
return true;
}
}
}