Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • sibidharan/api-development-course-apr-2021
  • krithikramraja/api-development-course-apr-2021
  • monish-palanikumar/api-development-course-apr-2021
  • Pranesh/api-development-course-apr-2021
  • ganesha005/api-development-course-apr-2021
  • selva1011/api-development-course-apr-2021
  • hema/api-development-course-apr-2021
  • Kartheeekn/api-development-course-apr-2021
  • GopiKrishnan/api-development-course-apr-2021
  • Mhd_khalid/api-development-course-apr-2021
  • sibivarma/api-development-course-apr-2021
  • ramanajsr1/api-development-course-apr-2021
  • rahulprem2k2910/api-development-course-apr-2021
  • sabarinathanfb/api-development-course-apr-2021
  • hariharanrd/api-development-course-apr-2021
  • Akram24/api-development-course-apr-2021
  • At_muthu__/api-development-course-apr-2021
  • rii/api-development-course-apr-2021
  • harishvarmaj7/api-development-course-apr-2021
  • moovendhan/rest-api
  • k3XD16/api-development-course-apr-2021
  • vimal/api-development-course-apr-2021
  • shiva007/api-development-course-apr-2021
  • Amudhan/api-development-course-apr-2021
  • abinayacyber604/api-development-course-apr-2021
  • subash_19/api
  • Saransaran/api-development-course-apr-2021
27 results
Show changes
Commits on Source (19)
Showing
with 1278 additions and 57 deletions
Header add Access-Control-Allow-Origin: * Header add Access-Control-Allow-Origin: *
Header add Access-Control-Allow-Methods: *
Header add Access-Control-Request-Headers: *
RewriteEngine On RewriteEngine On
RewriteBase / RewriteBase /
......
{
"info": {
"_postman_id": "d5528f1e-e6ac-4f7d-965a-9fc81825a7fb",
"name": "API Development Apr 2021",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "Folder",
"item": [
{
"name": "List Folders",
"request": {
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "a.fd99999df21f5ff9d26be0a9e08788f6ee0bf8c61628e161788d73962cf121da",
"type": "string"
}
]
},
"method": "GET",
"header": [],
"url": {
"raw": "https://api1.selfmade.ninja/api/folder/list",
"protocol": "https",
"host": [
"api1",
"selfmade",
"ninja"
],
"path": [
"api",
"folder",
"list"
]
}
},
"response": []
},
{
"name": "Get All Notes in Folder",
"request": {
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "a.fd99999df21f5ff9d26be0a9e08788f6ee0bf8c61628e161788d73962cf121da",
"type": "string"
}
]
},
"method": "POST",
"header": [],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "id",
"value": "5",
"type": "text"
}
]
},
"url": {
"raw": "https://api1.selfmade.ninja/api/folder/get_all_notes",
"protocol": "https",
"host": [
"api1",
"selfmade",
"ninja"
],
"path": [
"api",
"folder",
"get_all_notes"
]
}
},
"response": []
},
{
"name": "New Folder",
"request": {
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "a.fd99999df21f5ff9d26be0a9e08788f6ee0bf8c61628e161788d73962cf121da",
"type": "string"
}
]
},
"method": "POST",
"header": [],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "name",
"value": "Personal Notes",
"type": "text"
}
]
},
"url": {
"raw": "https://api1.selfmade.ninja/api/folder/new",
"protocol": "https",
"host": [
"api1",
"selfmade",
"ninja"
],
"path": [
"api",
"folder",
"new"
]
}
},
"response": []
},
{
"name": "Delete Folder",
"request": {
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "a.3bc2650a4dd2416df5ddaa0957528a210dea83c22109305e554c173fe1a90880",
"type": "string"
}
]
},
"method": "POST",
"header": [],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "id",
"value": "2",
"type": "text"
}
]
},
"url": {
"raw": "https://api1.selfmade.ninja/api/folder/delete",
"protocol": "https",
"host": [
"api1",
"selfmade",
"ninja"
],
"path": [
"api",
"folder",
"delete"
]
}
},
"response": []
}
]
},
{
"name": "List",
"item": [
{
"name": "Get Note",
"request": {
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "a.3bc2650a4dd2416df5ddaa0957528a210dea83c22109305e554c173fe1a90880",
"type": "string"
}
]
},
"method": "POST",
"header": [],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "id",
"value": "15",
"type": "text"
}
]
},
"url": {
"raw": "https://api1.selfmade.ninja/api/notes/get",
"protocol": "https",
"host": [
"api1",
"selfmade",
"ninja"
],
"path": [
"api",
"notes",
"get"
]
}
},
"response": []
},
{
"name": "New Note",
"request": {
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "a.3bc2650a4dd2416df5ddaa0957528a210dea83c22109305e554c173fe1a90880",
"type": "string"
}
]
},
"method": "POST",
"header": [],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "title",
"value": "New note",
"type": "text"
},
{
"key": "body",
"value": "new body",
"type": "text"
},
{
"key": "folder",
"value": "200",
"type": "text"
}
]
},
"url": {
"raw": "https://api1.selfmade.ninja/api/notes/new",
"protocol": "https",
"host": [
"api1",
"selfmade",
"ninja"
],
"path": [
"api",
"notes",
"new"
]
}
},
"response": []
},
{
"name": "Delete Note",
"request": {
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "a.3bc2650a4dd2416df5ddaa0957528a210dea83c22109305e554c173fe1a90880",
"type": "string"
}
]
},
"method": "POST",
"header": [],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "id",
"value": "14",
"type": "text"
}
]
},
"url": {
"raw": "https://api1.selfmade.ninja/api/notes/delete",
"protocol": "https",
"host": [
"api1",
"selfmade",
"ninja"
],
"path": [
"api",
"notes",
"delete"
]
}
},
"response": []
},
{
"name": "Edit Note",
"request": {
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "a.3bc2650a4dd2416df5ddaa0957528a210dea83c22109305e554c173fe1a90880",
"type": "string"
}
]
},
"method": "POST",
"header": [],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "id",
"value": "14",
"type": "text"
},
{
"key": "title",
"value": "New Title 2",
"type": "text"
},
{
"key": "body",
"value": "New Body 1",
"type": "text"
}
]
},
"url": {
"raw": "https://api1.selfmade.ninja/api/notes/edit",
"protocol": "https",
"host": [
"api1",
"selfmade",
"ninja"
],
"path": [
"api",
"notes",
"edit"
]
}
},
"response": []
}
]
},
{
"name": "Verify Auth Test",
"request": {
"method": "POST",
"header": [],
"url": {
"raw": "http://api1.selfmade.ninja/api/test",
"protocol": "http",
"host": [
"api1",
"selfmade",
"ninja"
],
"path": [
"api",
"test"
]
}
},
"response": []
},
{
"name": "Signup",
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "username",
"value": "sibi1995",
"type": "text"
},
{
"key": "email",
"value": "sibidharan@icloud.com",
"type": "text"
},
{
"key": "password",
"value": "Adidas@321",
"type": "text"
}
]
},
"url": {
"raw": "https://api1.selfmade.ninja/api/auth/signup",
"protocol": "https",
"host": [
"api1",
"selfmade",
"ninja"
],
"path": [
"api",
"auth",
"signup"
]
}
},
"response": []
},
{
"name": "Login",
"request": {
"auth": {
"type": "noauth"
},
"method": "POST",
"header": [],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "username",
"value": "sibi1995",
"type": "text"
},
{
"key": "email",
"value": "sibidharan@icloud.com",
"type": "text",
"disabled": true
},
{
"key": "password",
"value": "Adidas@321",
"type": "text"
}
]
},
"url": {
"raw": "https://api1.selfmade.ninja/api/auth/login",
"protocol": "https",
"host": [
"api1",
"selfmade",
"ninja"
],
"path": [
"api",
"auth",
"login"
]
}
},
"response": []
},
{
"name": "Refresh Access",
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "refresh_token",
"value": "r.786906ede70648bccc44af4d13a461f87e0331d080565fbe1fd2ac21ea2e524c",
"type": "text"
}
]
},
"url": {
"raw": "https://api1.selfmade.ninja/api/auth/refresh",
"protocol": "https",
"host": [
"api1",
"selfmade",
"ninja"
],
"path": [
"api",
"auth",
"refresh"
],
"query": [
{
"key": "username",
"value": "sibi1995",
"disabled": true
},
{
"key": "password",
"value": "Adidas@321",
"disabled": true
}
]
}
},
"response": []
},
{
"name": "Current User",
"request": {
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "a.89bf515cbb06dd83ff6face31a91c1f42993419474f236cc3ec746d89648f907",
"type": "string"
}
]
},
"method": "POST",
"header": [],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "token",
"value": "a.89bf515cbb06dd83ff6face31a91c1f42993419474f236cc3ec746d89648f907",
"type": "text",
"disabled": true
}
]
},
"url": {
"raw": "https://api1.selfmade.ninja/api/auth/current",
"protocol": "https",
"host": [
"api1",
"selfmade",
"ninja"
],
"path": [
"api",
"auth",
"current"
]
}
},
"response": []
}
]
}
\ No newline at end of file
### API Development Course by LAHTP ### API Development Course by LAHTP
To get started, clone this repository to a proper document root. For XAMPP, this is `htdocs`. For private apache setup, its upto you how you configiure. To get started, clone this repository to a proper document root. For XAMPP, this is `htdocs`. For private apache setup, its upto you how you configure.
This code is right now accessible at: https://api1.selfmade.ninja This code is right now deployed at: https://api1.selfmade.ninja - (depricated server)
This code is hosted again in SNA Labs at https://apicourse.selfmade.buzz
API Documentation for the development can be found at the [Wiki Section](https://git.selfmade.ninja/sibidharan/api-development-course-apr-2021/-/wikis/home) of this repo.
Thanks to [Manickam Venkatachalam](https://git.selfmade.ninja/Manic) for making the API documentation happen.
Right outside the document root, create a file called `env.json` and keep the contents of the file similar to the following. Right outside the document root, create a file called `env.json` and keep the contents of the file similar to the following.
...@@ -36,13 +41,7 @@ This project is under development. ...@@ -36,13 +41,7 @@ This project is under development.
AllowOverride All AllowOverride All
Require all granted Require all granted
</Directory> </Directory>
# Added automatically by LetsEncrypt
RewriteEngine on
RewriteCond %{SERVER_NAME} =api1.selfmade.ninja
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=307]
</VirtualHost> </VirtualHost>
``` ```
In the above configuration, `env.json` should sit exactly `/var/www/env.json` here. In the above configuration, `env.json` should sit exactly `/var/www/env.json` here.
...@@ -85,7 +84,7 @@ Enter the password you have given for root during `mysql_secure_installation` an ...@@ -85,7 +84,7 @@ Enter the password you have given for root during `mysql_secure_installation` an
mysql> mysql>
``` ```
From here, we need to create a database called `apis`. From here, we need to create a database called
``` ```
mysql> CREATE DATABASE apis; mysql> CREATE DATABASE apis;
...@@ -115,5 +114,11 @@ $ cd /var ...@@ -115,5 +114,11 @@ $ cd /var
$ sudo chown $(whoami):$(whoami) -R www $ sudo chown $(whoami):$(whoami) -R www
``` ```
Now update the `env.json` file with the user and database info created. All set, your code should be accessible at http://localhost 6. Now import the database export locaked at `database/export.sql` into the database you just created and we have all the tables.
Now update the `env.json` file with the user and database info created. All set, your code should be accessible at http://localhost or whereever you configured it to work.
### Security
All the data that you get with `$this->_request[]` inside the APIs are secured with `mysqli_real_escape_string` during the API initialization. Look for the function called `REST::cleanInputs()` inside `api/REST.api.php` and here is where it happens. So this development is considered secured from MySQLi injections. If you access `$_GET` or `$_POST` anywhere else directly without `$this->_request[]`, then you might just need to filter the inputs yourself and make them secure.
...@@ -102,9 +102,9 @@ ...@@ -102,9 +102,9 @@
$clean_input[$k] = $this->cleanInputs($v); $clean_input[$k] = $this->cleanInputs($v);
} }
}else{ }else{
$data = trim(stripslashes($data));
$data = strip_tags($data);
$data = mysqli_real_escape_string(Database::getConnection(), $data); $data = mysqli_real_escape_string(Database::getConnection(), $data);
//$data = trim(stripslashes($data)); //This reverses the effect of mysqli_real_escape_string so dont use this unless you know what you are doing.
$data = strip_tags($data);
$clean_input = trim($data); $clean_input = trim($data);
} }
return $clean_input; return $clean_input;
...@@ -115,4 +115,4 @@ ...@@ -115,4 +115,4 @@
header("Content-Type:".$this->_content_type); header("Content-Type:".$this->_content_type);
} }
} }
?> ?>
\ No newline at end of file
<?php
${basename(__FILE__, '.php')} = function(){
if($this->get_request_method() == "POST" and $this->isAuthenticated()){
try{
$data = [
"username" => $this->getUsername(),
];
$data = $this->json($data);
$this->response($data, 200);
} catch(Exception $e){
$data = [
"error" => $e->getMessage()
];
$data = $this->json($data);
$this->response($data, 403);
}
} else {
$data = [
"error" => "Bad request"
];
$data = $this->json($data);
$this->response($data, 400);
}
};
\ No newline at end of file
<?php <?php
${basename(__FILE__, '.php')} = function(){ ${basename(__FILE__, '.php')} = function(){
if($this->isAuthenticated()){
$data = [
"error" => "Already logged in"
];
$data = $this->json($data);
$this->response($data, 400);
}
if($this->get_request_method() == "POST" and isset($this->_request['username']) and isset($this->_request['password'])){ if($this->get_request_method() == "POST" and isset($this->_request['username']) and isset($this->_request['password'])){
$username = $this->_request['username']; $username = $this->_request['username'];
$password = $this->_request['password']; $password = $this->_request['password'];
...@@ -8,7 +15,7 @@ ${basename(__FILE__, '.php')} = function(){ ...@@ -8,7 +15,7 @@ ${basename(__FILE__, '.php')} = function(){
$auth = new Auth($username, $password); $auth = new Auth($username, $password);
$data = [ $data = [
"message" => "Login success", "message" => "Login success",
"token" => $auth->getAuthToken() "tokens" => $auth->getAuthTokens()
]; ];
$data = $this->json($data); $data = $this->json($data);
$this->response($data, 200); $this->response($data, 200);
......
<?php
${basename(__FILE__, '.php')} = function(){
if($this->get_request_method() == "POST" and isset($this->_request['refresh_token'])){
$refresh_token = $this->_request['refresh_token'];
try {
$auth = new OAuth($refresh_token);
$data = [
"message" => "Refresh Success",
"tokens" => $auth->refreshAccess()
];
$data = $this->json($data);
$this->response($data, 200);
} catch(Exception $e){
$data = [
"error" => $e->getMessage()
];
$data = $this->json($data);
$this->response($data, 406);
}
} else {
$data = [
"error" => "Bad request"
];
$data = $this->json($data);
$this->response($data, 400);
}
};
\ No newline at end of file
<?php
${basename(__FILE__, '.php')} = function(){
if($this->get_request_method() == "POST" and $this->isAuthenticated() and isset($this->_request['id'])){
$f = new Folder($this->_request['id']);
if($f->delete()){
$data = [
'message' => 'success',
];
$data = $this->json($data);
$this->response($data, 200);
} else {
$data = [
'message' => 'error',
];
$data = $this->json($data);
$this->response($data, 400);
}
} else {
$data = [
"error" => "Bad request"
];
$data = $this->json($data);
$this->response($data, 400);
}
};
\ No newline at end of file
<?php
${basename(__FILE__, '.php')} = function(){
if($this->get_request_method() == "POST" and $this->isAuthenticated() and isset($this->_request['id'])){
$f = new Folder($this->_request['id']);
$data = [
'count' => $f->countNotes(),
'notes' => $f->getAllNotes()
];
$data = $this->json($data);
$this->response($data, 200);
} else {
$data = [
"error" => "Bad request"
];
$data = $this->json($data);
$this->response($data, 400);
}
};
\ No newline at end of file
<?php
${basename(__FILE__, '.php')} = function(){
if($this->isAuthenticated()){
$data = Folder::getAllFolders();
$data = $this->json($data);
$this->response($data, 200);
} else {
$data = [
"error" => "Bad request"
];
$data = $this->json($data);
$this->response($data, 400);
}
};
\ No newline at end of file
<?php
${basename(__FILE__, '.php')} = function(){
if($this->get_request_method() == "POST" and $this->isAuthenticated() and isset($this->_request['name'])){
$f = new Folder();
$id = $f->createNew($this->_request['name']);
$data = [
'folder_id' => $id
];
$data = $this->json($data);
$this->response($data, 200);
} else {
$data = [
"error" => "Bad request"
];
$data = $this->json($data);
$this->response($data, 400);
}
};
\ No newline at end of file
<?php
${basename(__FILE__, '.php')} = function(){
if($this->get_request_method() == "POST" and $this->isAuthenticated() and isset($this->_request['id']) and isset($this->_request['name'])){
$f = new Folder($this->_request['id']);
if($f->rename($this->_request['name'])){
$data = [
"message" => "success"
];
$data = $this->json($data);
$this->response($data, 200);
}
} else {
$data = [
"error" => "Bad request"
];
$data = $this->json($data);
$this->response($data, 400);
}
};
\ No newline at end of file
<?php
${basename(__FILE__, '.php')} = function(){
if($this->isAuthenticated() and isset($this->_request['id'])){
$n = new Notes($this->_request['id']);
if($n->delete()){
$data = [
'message'=> 'success',
];
$data = $this->json($data);
$this->response($data, 200);
} else {
$data = [
"error" => "Cannot delete"
];
$data = $this->json($data);
$this->response($data, 400);
}
} else {
$data = [
"error" => "Bad request"
];
$data = $this->json($data);
$this->response($data, 400);
}
};
\ No newline at end of file
<?php
${basename(__FILE__, '.php')} = function(){
if($this->get_request_method() == "POST" and $this->isAuthenticated() and isset($this->_request['id']) and isset($this->_request['title']) and isset($this->_request['body'])){
$n = new Notes($this->_request['id']);
$n->setTitle($this->_request['title']);
$n->setBody($this->_request['body']);
$data = [
'id' => $n->getId(),
'title' => $n->getTitle(),
'body' => $n->getBody(),
'created' => $n->createdAt(),
'updated' => $n->updatedAt()
];
$data = $this->json($data);
$this->response($data, 200);
} else {
$data = [
"error" => "Bad request"
];
$data = $this->json($data);
$this->response($data, 400);
}
};
\ No newline at end of file
<?php
${basename(__FILE__, '.php')} = function(){
if($this->isAuthenticated() and isset($this->_request['id'])){
$n = new Notes($this->_request['id']);
$data = [
'id'=>$n->getID(),
'title' => $n->getTitle(),
'body' => $n->getBody(),
'created' => $n->createdAt(),
'updated' => $n->updatedAt()
];
$data = $this->json($data);
$this->response($data, 200);
} else {
$data = [
"error" => "Bad request"
];
$data = $this->json($data);
$this->response($data, 400);
}
};
\ No newline at end of file
<?php
${basename(__FILE__, '.php')} = function(){
if($this->get_request_method() == "POST" and $this->isAuthenticated() and isset($this->_request['title']) and isset($this->_request['body']) and isset($this->_request['folder'])){
$f = new Notes();
$id = $f->createNew($this->_request['title'], $this->_request['body'], $this->_request['folder']);
$data = [
'note_id' => $id
];
$data = $this->json($data);
$this->response($data, 200);
} else {
$data = [
"error" => "Bad request"
];
$data = $this->json($data);
$this->response($data, 400);
}
};
\ No newline at end of file
...@@ -5,6 +5,8 @@ require_once($_SERVER['DOCUMENT_ROOT']."/api/lib/Database.class.php"); ...@@ -5,6 +5,8 @@ require_once($_SERVER['DOCUMENT_ROOT']."/api/lib/Database.class.php");
require_once($_SERVER['DOCUMENT_ROOT']."/api/lib/Signup.class.php"); require_once($_SERVER['DOCUMENT_ROOT']."/api/lib/Signup.class.php");
require_once($_SERVER['DOCUMENT_ROOT']."/api/lib/User.class.php"); require_once($_SERVER['DOCUMENT_ROOT']."/api/lib/User.class.php");
require_once($_SERVER['DOCUMENT_ROOT']."/api/lib/Auth.class.php"); require_once($_SERVER['DOCUMENT_ROOT']."/api/lib/Auth.class.php");
require_once($_SERVER['DOCUMENT_ROOT']."/api/lib/Notes.class.php");
require_once($_SERVER['DOCUMENT_ROOT']."/api/lib/Folder.class.php");
class API extends REST { class API extends REST {
...@@ -12,6 +14,7 @@ class API extends REST { ...@@ -12,6 +14,7 @@ class API extends REST {
private $db = NULL; private $db = NULL;
private $current_call; private $current_call;
private $auth = null;
public function __construct(){ public function __construct(){
parent::__construct(); // Init parent contructor parent::__construct(); // Init parent contructor
...@@ -31,27 +34,78 @@ class API extends REST { ...@@ -31,27 +34,78 @@ class API extends REST {
else { else {
if(isset($_GET['namespace'])){ if(isset($_GET['namespace'])){
$dir = $_SERVER['DOCUMENT_ROOT'].'/api/apis/'.$_GET['namespace']; $dir = $_SERVER['DOCUMENT_ROOT'].'/api/apis/'.$_GET['namespace'];
$methods = scandir($dir); $file = $dir.'/'.$func.'.php';
//var_dump($methods); if(file_exists($file)){
foreach($methods as $m){ include $file;
if($m == "." or $m == ".."){ $this->current_call = Closure::bind(${$func}, $this, get_class());
continue; $this->$func();
} } else {
$basem = basename($m, '.php'); $this->response($this->json(['error'=>'method_not_found']),404);
//echo "Trying to call $basem() for $func()\n";
if($basem == $func){
include $dir."/".$m;
$this->current_call = Closure::bind(${$basem}, $this, get_class());
$this->$basem();
}
} }
/**
* Use the following snippet if you want to include multiple files
*/
// $methods = scandir($dir);
// //var_dump($methods);
// foreach($methods as $m){
// if($m == "." or $m == ".."){
// continue;
// }
// $basem = basename($m, '.php');
// //echo "Trying to call $basem() for $func()\n";
// if($basem == $func){
// include $dir."/".$m;
// $this->current_call = Closure::bind(${$basem}, $this, get_class());
// $this->$basem();
// }
// }
} else { } else {
//we can even process functions without namespace here. //we can even process functions without namespace here.
$this->response($this->json(['error'=>'methood_not_found']),404); $this->response($this->json(['error'=>'method_not_found']),404);
} }
} }
} }
public function auth(){
$headers = getallheaders();
if(isset($headers['Authorization'])){
$token = explode(' ', $headers['Authorization']);
$this->auth = new Auth($token[1]);
}
}
public function isAuthenticated(){
if($this->auth == null){
return false;
}
if($this->auth->getOAuth()->authenticate() and isset($_SESSION['username'])){
return true;
} else {
return false;
}
}
public function getUsername(){
return $_SESSION['username'];
}
public function die($e){
$data = [
"error" => $e->getMessage()
];
$response_code = 400;
if($e->getMessage() == "Expired token" || $e->getMessage() == "Unauthorized"){
$response_code = 403;
}
if($e->getMessage() == "Not found"){
$response_code = 404;
}
$data = $this->json($data);
$this->response($data,$response_code);
}
public function __call($method, $args){ public function __call($method, $args){
if(is_callable($this->current_call)){ if(is_callable($this->current_call)){
return call_user_func_array($this->current_call, $args); return call_user_func_array($this->current_call, $args);
...@@ -62,19 +116,6 @@ class API extends REST { ...@@ -62,19 +116,6 @@ class API extends REST {
/*************API SPACE START*******************/ /*************API SPACE START*******************/
private function about(){
if($this->get_request_method() != "POST"){
$error = array('method'=> $this->get_request_method(), 'status' => 'WRONG_CALL', "msg" => "The type of call cannot be accepted by our servers.");
$error = $this->json($error);
$this->response($error,406);
}
$data = array('method'=> $this->get_request_method(),'version' => $this->_request['version'], 'desc' => 'This API is created by Blovia Technologies Pvt. Ltd., for the public usage for accessing data about vehicles.');
$data = $this->json($data);
$this->response($data,200);
}
private function test(){ private function test(){
$data = $this->json(getallheaders()); $data = $this->json(getallheaders());
$this->response($data,200); $this->response($data,200);
...@@ -131,5 +172,11 @@ class API extends REST { ...@@ -131,5 +172,11 @@ class API extends REST {
// Initiiate Library // Initiiate Library
$api = new API; $api = new API;
$api->processApi(); try {
?> $api->auth();
\ No newline at end of file $api->processApi();
} catch (Exception $e){
$api->die($e);
}
?>
...@@ -2,13 +2,15 @@ ...@@ -2,13 +2,15 @@
require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/Database.class.php'); require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/Database.class.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/User.class.php'); require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/User.class.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/OAuth.class.php');
require $_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php'; require $_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php';
class Auth { class Auth {
private $db; private $db;
private $isTokenAuth = false; private $isTokenAuth = false;
private $loginToken = null; private $loginTokens = null;
private $oauth;
public function __construct($username, $password = NULL){ public function __construct($username, $password = NULL){
$this->db = Database::getConnection(); $this->db = Database::getConnection();
...@@ -23,7 +25,8 @@ class Auth { ...@@ -23,7 +25,8 @@ class Auth {
} }
if($this->isTokenAuth){ if($this->isTokenAuth){
throw new Exception("Not Implemented"); $this->oauth = new OAuth($this->token);
$this->oauth->authenticate();
} else { } else {
$user = new User($this->username); $user = new User($this->username);
$hash = $user->getPasswordHash(); $hash = $user->getPasswordHash();
...@@ -32,26 +35,37 @@ class Auth { ...@@ -32,26 +35,37 @@ class Auth {
if(!$user->isActive()){ if(!$user->isActive()){
throw new Exception("Please check your email and activate your account."); throw new Exception("Please check your email and activate your account.");
} }
$this->loginToken = $this->addSession(); $this->loginTokens = $this->addSession(7200);
} else { } else {
throw new Exception("Password Mismatch"); throw new Exception("Password Mismatch");
} }
} }
} }
public function getAuthToken(){ /**
return $this->loginToken; * Returns the username of authenticated user
*/
public function getUsername(){
if($this->oauth->authenticate()){
return $this->oauth->getUsername();
} else {
return "a";
}
}
public function getOAuth(){
return $this->oauth;
}
public function getAuthTokens(){
return $this->loginTokens;
} }
private function addSession(){ private function addSession(){
$token = Auth::generateRandomHash(32); $oauth = new OAuth();
$query = "INSERT INTO `apis`.`session` (`username`, `token`) VALUES ('$this->username', '$token');"; $oauth->setUsername($this->username);
if(mysqli_query($this->db, $query)){ $session = $oauth->newSession();
return $token; return $session;
} else {
throw new Exception(mysqli_error($this->db));
}
} }
public static function generateRandomHash($len){ public static function generateRandomHash($len){
......
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/Database.class.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/Share.class.php');
require_once $_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php';
use Carbon\Carbon;
class Folder extends Share
{
private $db;
private $data = null;
private $id = null;
public function __construct($id = null)
{
parent::__construct($id, 'folder');
$this->db = Database::getConnection();
if ($id!=null) {
$this->id = $id;
$this->refresh();
}
}
public function getName()
{
if ($this->data and isset($this->data['name'])) {
return $this->data['name'];
}
}
public function getId()
{
if ($this->id) {
return $this->id;
}
}
public function createdAt()
{
if ($this->data and isset($this->data['created_at'])) {
$c = new Carbon($this->data['created_at'], date_default_timezone_get());
return $c->diffForHumans();
}
}
public function createNew($name='Default Folder')
{
if (isset($_SESSION['username']) and strlen($name) >= 5 and strlen($name) <=45) {
$query = "INSERT INTO `folders` (`name`, `owner`) VALUES ('$name', '$_SESSION[username]');";
if (mysqli_query($this->db, $query)) {
$this->id = mysqli_insert_id($this->db);
return $this->id;
}
} else {
throw new Exception("Cannot create default folderse");
}
}
public function refresh()
{
if ($this->id != null) {
$query = "SELECT * FROM folders WHERE id=$this->id";
$result = mysqli_query($this->db, $query);
if ($result && mysqli_num_rows($result) == 1) {
$this->data = mysqli_fetch_assoc($result);
if ($this->getOwner() != $_SESSION['username']) {
throw new Exception("Unauthorized");
}
$this->id = $this->data['id'];
} else {
throw new Exception("Not found");
}
}
}
public function getOwner()
{
if ($this->data and isset($this->data['owner'])) {
return $this->data['owner'];
}
}
public function rename($name)
{
if ($this->id) {
$query = "UPDATE `folders` SET `name` = '$name' WHERE (`id` = '$this->id');";
$result = mysqli_query($this->db, $query);
$this->refresh();
return $result;
} else {
throw new Exception("Not found");
}
}
public function getAllNotes()
{
$query = "SELECT * FROM notes WHERE folder_id=$this->id";
$result = mysqli_query($this->db, $query);
if ($result) {
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
for ($i=0; $i<count($data); $i++) {
$c_at = $data[$i]['created_at'];
$u_at = $data[$i]['updated_at'];
$c_c = new Carbon($c_at);
$u_c = new Carbon($u_at);
$data[$i]['created'] = $c_c->diffForHumans();
$data[$i]['updated'] = $u_c->diffForHumans();
}
return $data;
} else {
return [];
}
}
public function countNotes()
{
$query = "SELECT COUNT(*) FROM notes WHERE folder_id=$this->id";
$result = mysqli_query($this->db, $query);
if ($result) {
$data = mysqli_fetch_assoc($result);
return $data['COUNT(*)'];
}
}
public function delete()
{
if (isset($_SESSION['username']) and $this->getOwner() == $_SESSION['username']) {
$notes = $this->getAllNotes();
foreach ($notes as $note) {
$n = new Notes($note['id']);
$n->delete();
}
if ($this->id) {
$query = "DELETE FROM `folders` WHERE (`id` = '$this->id');";
$result = mysqli_query($this->db, $query);
return $result;
} else {
throw new Exception("Not found");
}
} else {
throw new Exception("Unauthorized");
}
}
public static function getAllFolders()
{
$db = Database::getConnection();
$query = "SELECT * FROM folders WHERE owner='$_SESSION[username]'";
$result = mysqli_query($db, $query);
if ($result) {
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
for ($i=0; $i<count($data); $i++) {
$date = $data[$i]['created_at'];
$c = new Carbon($date);
$data[$i]['created'] = $c->diffForHumans();
$f = new Folder($data[$i]['id']);
$data[$i]['count'] = $f->countNotes();
}
return $data;
} else {
return [];
}
}
}
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/Database.class.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/Share.class.php');
require_once $_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php';
use Carbon\Carbon;
class Notes extends Share
{
public function __construct($id=null)
{
parent::__construct($id, 'note');
$this->db = Database::getConnection();
if ($id!=null) {
$this->id = $id;
$this->refresh();
}
}
public function refresh()
{
if ($this->id != null) {
$query = "SELECT * FROM notes WHERE id=$this->id";
$result = mysqli_query($this->db, $query);
if ($result && mysqli_num_rows($result) == 1) {
$this->data = mysqli_fetch_assoc($result);
if ($this->getOwner() != $_SESSION['username']) {
throw new Exception("Unauthorized");
}
$this->id = $this->data['id'];
} else {
throw new Exception("Not found");
}
}
}
public function getOwner()
{
if ($this->data and isset($this->data['owner'])) {
return $this->data['owner'];
}
}
public function getID()
{
return $this->id;
}
public function getBody()
{
if ($this->data and isset($this->data['body'])) {
return $this->data['body'];
}
}
public function getFolderID()
{
if ($this->data and isset($this->data['folder_id'])) {
return $this->data['folder_id'];
}
}
public function getTitle()
{
if ($this->data and isset($this->data['title'])) {
return $this->data['title'];
}
}
public function createdAt()
{
if ($this->data and isset($this->data['created_at'])) {
$c = new Carbon($this->data['created_at'], date_default_timezone_get());
return $c->diffForHumans();
}
}
public function updatedAt()
{
if ($this->data and isset($this->data['updated_at'])) {
$c = new Carbon($this->data['updated_at'], date_default_timezone_get());
return $c->diffForHumans();
}
}
public function setBody($body)
{
if (isset($_SESSION['username']) and $this->getOwner() == $_SESSION['username']) {
if ($this->id) {
$query = "UPDATE `notes` SET `body` = '$body' WHERE (`id` = '$this->id');";
$result = mysqli_query($this->db, $query);
$this->setUpdated();
$this->refresh();
return $result;
} else {
throw new Exception("Not found");
}
} else {
throw new Exception("Unauthorized");
}
}
public function setTitle($title)
{
if (isset($_SESSION['username']) and $this->getOwner() == $_SESSION['username']) {
if ($this->id) {
$query = "UPDATE `notes` SET `title` = '$title' WHERE (`id` = '$this->id');";
$result = mysqli_query($this->db, $query);
$this->setUpdated();
$this->refresh();
return $result;
} else {
throw new Exception("Not found");
}
} else {
throw new Exception("Unauthorized");
}
}
private function setUpdated()
{
if (isset($_SESSION['username']) and $this->getOwner() == $_SESSION['username']) {
if ($this->id) {
$query = "UPDATE `notes` SET `updated_at` = '".date("Y-m-d H:i:s")."' WHERE (`id` = '$this->id');";
$result = mysqli_query($this->db, $query);
if ($result) {
$this->refresh();
return $result;
} else {
throw new Exception("Something is not right");
}
} else {
throw new Exception("Not found");
}
} else {
throw new Exception("Unauthorized");
}
}
public function delete()
{
if (isset($_SESSION['username']) and $this->getOwner() == $_SESSION['username']) {
if ($this->id) {
$query = "DELETE FROM `notes` WHERE (`id` = '$this->id');";
$result = mysqli_query($this->db, $query);
return $result;
} else {
throw new Exception("Note not loaded");
}
} else {
throw new Exception("Unauthorized ");
}
}
public function createNew($title, $body, $folder)
{
$f = new Folder($folder);
if ($f->getOwner() == $_SESSION['username']) {
if (isset($_SESSION['username']) and strlen($title) <= 45) {
$query = "INSERT INTO `notes` (`title`, `body`, `owner`, `folder_id`) VALUES ('$title', '$body', '$_SESSION[username]', '$folder');";
if (mysqli_query($this->db, $query)) {
$this->id = mysqli_insert_id($this->db);
$this->refresh();
return $this->id;
}
} else {
throw new Exception("Cannot create note");
}
} else {
throw new Exception("Unauthorized");
}
}
}