Browse Source

project init

develop
Carmine De Rosa 5 years ago
parent
commit
98f70f6e63
  1. 4
      .gitignore
  2. 3
      README.md
  3. 7
      api/config/bootstrap.php
  4. 61
      api/config/codes.php
  5. 11
      api/config/config.php
  6. 24
      api/config/database.php
  7. 76
      api/config/token.php
  8. 75
      api/login.php
  9. 56
      api/register.php
  10. 60
      api/users.php
  11. 5
      composer.json

4
.gitignore

@ -0,0 +1,4 @@
composer\.lock
vendor/

3
README.md

@ -1 +1,4 @@
rest_api rest_api
reference: https://www.techiediaries.com/amp/php-jwt-authentication-tutorial
composer require firebase/php-jwt

7
api/config/bootstrap.php

@ -0,0 +1,7 @@
<?php
include_once './config/config.php';
include_once './config/codes.php';
include_once './config/database.php';
include_once './config/token.php';
?>

61
api/config/codes.php

@ -0,0 +1,61 @@
<?php
$codes = array(
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => 'Switch Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
418 => 'I\'m a teapot',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
425 => 'Unordered Collection',
426 => 'Upgrade Required',
449 => 'Retry With',
450 => 'Blocked by Windows Parental Controls',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
509 => 'Bandwidth Limit Exceeded',
510 => 'Not Extended',
);
?>

11
api/config/config.php

@ -0,0 +1,11 @@
<?php
$CONF['CLAIM']['SECRET'] = "SECRET_KEY_1234567890";
$CONF['CLAIM']['ISSUER'] = "http://rest.local";
$CONF['CLAIM']['AUDIENCE'] = "http://rest.local";
$CONF['CLAIM']['ISSUE_DATE'] = time();
$CONF['CLAIM']['NOT_BEFORE'] = $CONF['CLAIM']['ISSUE_DATE'] + 10;
$CONF['CLAIM']['EXPIRE'] = $CONF['CLAIM']['ISSUE_DATE'] + 60000;
?>

24
api/config/database.php

@ -0,0 +1,24 @@
<?php
// used to get mysql database connection
class DatabaseService {
private $db_host = "localhost";
private $db_name = "jwt";
private $db_user = "root";
private $db_password = "root";
private $connection;
public function getConnection(){
$this->connection = null;
try{
$this->connection = new PDO("mysql:host=" . $this->db_host . ";dbname=" . $this->db_name, $this->db_user, $this->db_password);
}catch(PDOException $exception){
echo "Connection failed: " . $exception->getMessage();
}
return $this->connection;
}
}
?>

76
api/config/token.php

@ -0,0 +1,76 @@
<?php
use \Firebase\JWT\JWT;
class AuthenticationToken {
private $auth;
private $token;
private $response;
/*
public function getAuthorizationHeader(){
$headers = null;
if (isset($_SERVER['Authorization'])) {
$headers = trim($_SERVER["Authorization"]);
}
else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
} elseif (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
//print_r($requestHeaders);
if (isset($requestHeaders['Authorization'])) {
$headers = trim($requestHeaders['Authorization']);
}
}
return $headers;
}*/
public function tokenGet() {
$this->auth = null;
$requestHeaders = apache_request_headers();
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
if(isset($requestHeaders['Authorization'])) {
$headers = trim($requestHeaders['Authorization']);
}
if(!empty($headers)) {
if(preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
$this->auth = $matches[1];
}
}
return $this->auth;
}
public function tokenCheck($secret) {
$this->token = $this->tokenGet();
$this->response = array();
try {
$decoded = JWT::decode($this->token, $secret, array('HS256'));
$this->response = array(
"status" => 200,
"access" => "GRANTED",
"token" => $this->token//$decoded
);
} catch(Exception $e) {
$this->response = array(
"status" => 401,
"access" => "DENIED",
"error" => $e->getMessage()
);
}
return $this->response;
}
}
?>

75
api/login.php

@ -0,0 +1,75 @@
<?php
include_once './config/bootstrap.php';
require "../vendor/autoload.php";
use \Firebase\JWT\JWT;
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$email = '';
$password = '';
$databaseService = new DatabaseService();
$conn = $databaseService->getConnection();
$data = json_decode(file_get_contents("php://input"));
$email = trim($data->email);
$password = trim($data->password);
$query = "SELECT id, first_name, last_name, password
FROM users
WHERE email = :email
LIMIT 0,1";
$stmt = $conn->prepare( $query );
$stmt->bindParam(':email', $email);
$stmt->execute();
$num = $stmt->rowCount();
if($num > 0) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$id = $row['id'];
$firstname = $row['first_name'];
$lastname = $row['last_name'];
$password2 = $row['password'];
if(password_verify($password, $password2)) {
$token = array(
"iss" => $CONF['CLAIM']['ISSUER'],
"aud" => $CONF['CLAIM']['AUDIENCE'],
"iat" => $CONF['CLAIM']['ISSUE_DATE'],
"nbf" => $CONF['CLAIM']['NOT_BEFORE'],
"exp" => $CONF['CLAIM']['EXPIRE'],
"data" => array(
"id" => $id,
"firstname" => $firstname,
"lastname" => $lastname,
"email" => $email
));
http_response_code(200);
$jwt = JWT::encode($token, $CONF['CLAIM']['SECRET']);
echo json_encode(
array(
"message" => "Successful login.",
"jwt" => $jwt,
"email" => $email,
"expireAt" => $CONF['CLAIM']['EXPIRE']
));
} else {
http_response_code(401);
echo json_encode(array("message" => "Login failed"));
}
} else {
http_response_code(401);
echo json_encode(array("message" => "Login failed"));
}
?>

56
api/register.php

@ -0,0 +1,56 @@
<?php
include_once './config/bootstrap.php';
header("Access-Control-Allow-Origin: * ");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$firstName = '';
$lastName = '';
$email = '';
$password = '';
$conn = null;
$databaseService = new DatabaseService();
$conn = $databaseService->getConnection();
/*
$data = json_decode(file_get_contents("php://input"));
$firstName = $data->first_name;
$lastName = $data->last_name;
$email = $data->email;
$password = $data->password;
*/
$firstName = $_POST['first_name'];
$lastName = $_POST['last_name'];
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO users
SET first_name = :firstname,
last_name = :lastname,
email = :email,
password = :password";
$stmt = $conn->prepare($query);
$stmt->bindParam(':firstname', $firstName);
$stmt->bindParam(':lastname', $lastName);
$stmt->bindParam(':email', $email);
$password_hash = password_hash($password, PASSWORD_BCRYPT);
$stmt->bindParam(':password', $password_hash);
if($stmt->execute()) {
http_response_code(200);
echo json_encode(array("message" => "User was successfully registered."));
} else {
http_response_code(400);
echo json_encode(array("message" => "Unable to register the user."));
}
?>

60
api/users.php

@ -0,0 +1,60 @@
<?php
include_once './config/bootstrap.php';
require "../vendor/autoload.php";
use \Firebase\JWT\JWT;
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$authToken = new AuthenticationToken();
$tokenCheck = $authToken->tokenCheck($CONF['CLAIM']['SECRET']);
if($tokenCheck['access'] == "GRANTED") {
echo json_encode($tokenCheck);
} else {
echo json_encode($tokenCheck);
}
//$jwt = getBearerToken();//$arr[1];
//"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9yZXN0LmxvY2FsIiwiYXVkIjoiaHR0cDpcL1wvcmVzdC5sb2NhbCIsImlhdCI6MTU4NzY1MTA2NCwibmJmIjoxNTg3NjUxMDc0LCJleHAiOjE1ODc3MTEwNjQsImRhdGEiOnsiaWQiOiIxIiwiZmlyc3RuYW1lIjoiQ2FybWluZSIsImxhc3RuYW1lIjoiRGUgUm9zYSIsImVtYWlsIjoiZHNsYWt5QGdtYWlsLmNvbSJ9fQ.l9uPKJuqGlnRD8prKzcEDWTf_fuqEZarje-mFANaBZM";
/*
echo $jwt;
if($jwt){
try {
$decoded = JWT::decode($jwt, $secret_key, array('HS256'));
print_r($decoded);
// Access is granted. Add code of the operation here
echo json_encode(array(
"message" => "Access granted:",
"error" => "aaa"
));
} catch (Exception $e){
http_response_code(401);
echo json_encode(array(
"message" => "Access denied.",
"error" => $e->getMessage()
));
}
} else {
echo json_encode(array(
"message" => "Access denied.",
"error" => "no token"
));
}*/
?>

5
composer.json

@ -0,0 +1,5 @@
{
"require": {
"firebase/php-jwt": "^5.2"
}
}
Loading…
Cancel
Save