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 (15)
Showing
with 1236 additions and 108 deletions
Header add Access-Control-Allow-Origin: *
Header add Access-Control-Allow-Methods: *
Header add Access-Control-Request-Headers: *
RewriteEngine On
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
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.
......@@ -36,13 +41,7 @@ This project is under development.
AllowOverride All
Require all granted
</Directory>
# Added automatically by LetsEncrypt
RewriteEngine on
RewriteCond %{SERVER_NAME} =api1.selfmade.ninja
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=307]
</VirtualHost>
```
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
mysql>
```
From here, we need to create a database called `apis`.
From here, we need to create a database called
```
mysql> CREATE DATABASE apis;
......@@ -115,5 +114,11 @@ $ cd /var
$ 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 @@
$clean_input[$k] = $this->cleanInputs($v);
}
}else{
$data = trim(stripslashes($data));
$data = strip_tags($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);
}
return $clean_input;
......@@ -115,4 +115,4 @@
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() 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");
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/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 {
......@@ -92,8 +94,16 @@ class API extends REST {
$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,400);
$this->response($data,$response_code);
}
public function __call($method, $args){
......@@ -106,19 +116,6 @@ class API extends REST {
/*************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(){
$data = $this->json(getallheaders());
$this->response($data,200);
......@@ -182,4 +179,4 @@ try {
$api->die($e);
}
?>
\ No newline at end of file
?>
<?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");
}
}
}
......@@ -4,7 +4,8 @@ require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/Auth.class.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/Database.class.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/User.class.php');
class OAuth {
class OAuth
{
private $db;
private $refresh_token = null;
private $access_token = null;
......@@ -16,12 +17,13 @@ class OAuth {
* Can construct without refresh token for new session
* Can construct with refresh token for refresh session
*/
public function __construct($token = NULL){
public function __construct($token = null)
{
$this->db = Database::getConnection();
if($token != NULL){
if($this->startsWith($token, 'a.')){
if ($token != null) {
if ($this->startsWith($token, 'a.')) {
$this->access_token = $token;
} else if($this->startsWith($token, 'r.')){
} elseif ($this->startsWith($token, 'r.')) {
$this->refresh_token = $token;
} else {
$this->setUsername($token);
......@@ -29,25 +31,28 @@ class OAuth {
}
}
public function setUsername($username){
public function setUsername($username)
{
$this->username = $username;
$this->user = new User($this->username);
}
public function getUsername(){
public function getUsername()
{
return $this->username;
}
public function authenticate(){
if($this->access_token != null){
public function authenticate()
{
if ($this->access_token != null) {
$query = "SELECT * FROM apis.session WHERE access_token = '$this->access_token';";
$result = mysqli_query($this->db, $query);
if($result){
if ($result) {
$data = mysqli_fetch_assoc($result);
$created_at = strtotime($data['created_at']);
$expires_at = $created_at + $data['valid_for'];
if(time() <= $expires_at){
if (time() <= $expires_at) {
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
......@@ -55,7 +60,7 @@ class OAuth {
$_SESSION['token'] = $this->access_token;
return true;
} else {
throw new Exception("Expired token");
throw new Exception("Expired token");
}
} else {
throw new Exception(mysqli_error($this->db));
......@@ -63,20 +68,21 @@ class OAuth {
}
}
public function newSession($valid_for = 7200, $reference_token = 'auth_grant'){
if($this->username == NULL){
public function newSession($valid_for = 7200, $reference_token = 'auth_grant')
{
if ($this->username == null) {
throw new Exception("Username not set for OAuth");
}
$this->valid_for = $valid_for;
$this->access_token = 'a.'.Auth::generateRandomHash(32);
if($reference_token == 'auth_grant'){
if ($reference_token == 'auth_grant') {
$this->refresh_token = 'r.'.Auth::generateRandomHash(32);
} else {
$this->refresh_token = 'd.'.Auth::generateRandomHash(16);
}
$query = "INSERT INTO `apis`.`session` (`username`, `access_token`, `refresh_token`, `valid_for`, `reference_token`)
$query = "INSERT INTO `session` (`username`, `access_token`, `refresh_token`, `valid_for`, `reference_token`)
VALUES ('$this->username', '$this->access_token', '$this->refresh_token', $this->valid_for, '$reference_token');";
if(mysqli_query($this->db, $query)){
if (mysqli_query($this->db, $query)) {
return array(
"access_token" => $this->access_token,
"valid_for" => $this->valid_for,
......@@ -89,14 +95,15 @@ class OAuth {
}
}
public function refreshAccess(){
if($this->refresh_token != NULL and !$this->startsWith($this->refresh_token, 'd.')){
public function refreshAccess()
{
if ($this->refresh_token != null and !$this->startsWith($this->refresh_token, 'd.')) {
$query = "SELECT * FROM apis.session WHERE refresh_token = '$this->refresh_token';";
$result = mysqli_query($this->db, $query);
if($result){
if ($result) {
$data = mysqli_fetch_assoc($result);
$this->username = $data['username'];
if($data['valid'] == 1){
if ($data['valid'] == 1) {
return $this->newSession(7200, $this->refresh_token);
} else {
throw new Exception("Expired token");
......@@ -109,8 +116,9 @@ class OAuth {
}
}
private function startsWith ($string, $startString){
private function startsWith($string, $startString)
{
$len = strlen($startString);
return (substr($string, 0, $len) === $startString);
}
}
\ No newline at end of file
}
<?php
//TODO: Homework - try to implement share options!
class Share{
public function __construct($id, $type){
if($type == "note" or $type == "folder"){
} else {
throw new Exception("Unknown share type");
}
}
public function shareWith($username) {
}
public function revoke($username) {
}
public function hasAccess($username) {
}
}
\ No newline at end of file
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/Database.class.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/Folder.class.php');
require $_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php';
//TODO Homework: find why ../vendor? it is the same reason why we use ../../env.json in config.
class Signup {
class Signup
{
private $username;
private $password;
private $email;
private $db;
public function __construct($username, $password, $email){
public function __construct($username, $password, $email)
{
$this->db = Database::getConnection();
$this->username = $username;
$this->password = $password;
$this->email = $email;
if($this->userExists()){
if ($this->userExists()) {
throw new Exception("User already exists");
}
$bytes = random_bytes(16);
$this->token = $token = bin2hex($bytes); //to verify users over email.
$password = $this->hashPassword();
//Homework - make a proper flow to throw username already exists
$query = "INSERT INTO `apis`.`auth` (`username`, `password`, `email`, `active`, `token`) VALUES ('$username', '$password', '$email', 0, '$token');";
if(!mysqli_query($this->db, $query)){
$query = "INSERT INTO `auth` (`username`, `password`, `email`, `active`, `token`) VALUES ('$username', '$password', '$email', 0, '$token');";
if (!mysqli_query($this->db, $query)) {
throw new Exception("Unable to signup, user account might already exist.");
} else {
$this->id = mysqli_insert_id($this->db);
$this->sendVerificationMail();
// $this->sendVerificationMail();
$f = new Folder();
session_start();
$_SESSION['username'] = $this->username;
$f->createNew('Default Folder');
}
}
function sendVerificationMail(){
$config_json = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/../env.json');
$config = json_decode($config_json, true);
$token = $this->token;
$email = new \SendGrid\Mail\Mail();
$email->setFrom("noreply@selfmade.ninja", "API Course by Selfmade");
$email->setSubject("Verify your account");
$email->addTo($this->email, $this->username);
$email->addContent("text/plain", "Please verify your account at: https://api1.selfmade.ninja/verify?token=$token");
$email->addContent(
"text/html", "<strong>Please verify your account by <a href=\"https://api1.selfmade.ninja/verify?token=$token\">clicking here</a> or open this URL manually: <a href=\"https://api1.selfmade.ninja/verify?token=$token\">https://api1.selfmade.ninja/verify?token=$token</a></strong>"
);
$sendgrid = new \SendGrid($config['email_api_key']);
try {
$response = $sendgrid->send($email);
// print $response->statusCode() . "\n";
// print_r($response->headers());
// print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
public function sendVerificationMail()
{
// $config_json = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/../env.json');
// $config = json_decode($config_json, true);
// $token = $this->token;
// $email = new \SendGrid\Mail\Mail();
// $email->setFrom("noreply@selfmade.ninja", "API Course by Selfmade");
// $email->setSubject("Verify your account");
// $email->addTo($this->email, $this->username);
// $email->addContent("text/plain", "Please verify your account at: https://api1.selfmade.ninja/verify?token=$token");
// $email->addContent(
// "text/html",
// "<strong>Please verify your account by <a href=\"https://api1.selfmade.ninja/verify?token=$token\">clicking here</a> or open this URL manually: <a href=\"https://api1.selfmade.ninja/verify?token=$token\">https://api1.selfmade.ninja/verify?token=$token</a></strong>"
// );
// $sendgrid = new \SendGrid($config['email_api_key']);
// try {
// $response = $sendgrid->send($email);
// // print $response->statusCode() . "\n";
// // print_r($response->headers());
// // print $response->body() . "\n";
// } catch (Exception $e) {
// echo 'Caught exception: '. $e->getMessage() ."\n";
// }
}
public function getInsertID(){
public function getInsertID()
{
return $this->id;
}
public function userExists(){
public function userExists()
{
//TODO: Write the code to check if user exists.
return false;
}
public function hashPassword($cost = 10){
public function hashPassword($cost = 10)
{
//echo $this->password;
$options = [
"cost" => $cost
......@@ -74,20 +85,20 @@ class Signup {
return password_hash($this->password, PASSWORD_BCRYPT, $options);
}
public static function verifyAccount($token){
public static function verifyAccount($token)
{
$query = "SELECT * FROM apis.auth WHERE token='$token';";
$db = Database::getConnection();
$result = mysqli_query($db, $query);
if($result and mysqli_num_rows($result) == 1){
if ($result and mysqli_num_rows($result) == 1) {
$data = mysqli_fetch_assoc($result);
if($data['active'] == 1){
if ($data['active'] == 1) {
throw new Exception("Already Verified");
}
mysqli_query($db, "UPDATE `apis`.`auth` SET `active` = '1' WHERE (`token` = '$token');");
mysqli_query($db, "UPDATE `auth` SET `active` = '1' WHERE (`token` = '$token');");
return true;
} else {
return false;
}
}
}
\ No newline at end of file
}
<pre><?php
print_r($GLOBALS);
print_r($_SERVER);
print_r($_REQUEST);
print_r($_POST);
print_r($_GET);
print_r($_FILES);
print_r($_ENV);
print_r($_COOKIE);
print_r($_SESSION);
?></pre>
\ No newline at end of file