Skip to content
Snippets Groups Projects
Commit d5fc41d8 authored by Sibidharan's avatar Sibidharan :speech_balloon:
Browse files

labs continuity

parent 72044cb8
No related branches found
No related tags found
No related merge requests found
......@@ -83,7 +83,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;
......
......@@ -6,41 +6,49 @@ require_once $_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php';
use Carbon\Carbon;
class Folder extends Share{
class Folder extends Share
{
private $db;
private $data = null;
private $id = null;
public function __construct($id = null){
public function __construct($id = null)
{
parent::__construct($id, 'folder');
$this->db = Database::getConnection();
if($id!=null){
if ($id!=null) {
$this->id = $id;
$this->refresh();
}
}
public function getName(){
if($this->data and isset($this->data['name'])){
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 getId()
{
if ($this->id) {
return $this->id;
}
}
public function createdAt(){
if($this->data and isset($this->data['created_at'])){
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 `apis`.`folders` (`name`, `owner`) VALUES ('$name', '$_SESSION[username]');";
if(mysqli_query($this->db, $query)){
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;
}
......@@ -49,13 +57,14 @@ class Folder extends Share{
}
}
public function refresh(){
if($this->id != null){
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){
if ($result && mysqli_num_rows($result) == 1) {
$this->data = mysqli_fetch_assoc($result);
if($this->getOwner() != $_SESSION['username']){
if ($this->getOwner() != $_SESSION['username']) {
throw new Exception("Unauthorized");
}
$this->id = $this->data['id'];
......@@ -65,15 +74,17 @@ class Folder extends Share{
}
}
public function getOwner(){
if($this->data and isset($this->data['owner'])){
public function getOwner()
{
if ($this->data and isset($this->data['owner'])) {
return $this->data['owner'];
}
}
public function rename($name){
if($this->id){
$query = "UPDATE `apis`.`folders` SET `name` = '$name' WHERE (`id` = '$this->id');";
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;
......@@ -82,12 +93,13 @@ class Folder extends Share{
}
}
public function getAllNotes(){
public function getAllNotes()
{
$query = "SELECT * FROM notes WHERE folder_id=$this->id";
$result = mysqli_query($this->db, $query);
if($result){
if ($result) {
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
for($i=0; $i<count($data); $i++){
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);
......@@ -101,25 +113,27 @@ class Folder extends Share{
}
}
public function countNotes(){
public function countNotes()
{
$query = "SELECT COUNT(*) FROM notes WHERE folder_id=$this->id";
$result = mysqli_query($this->db, $query);
if($result){
if ($result) {
$data = mysqli_fetch_assoc($result);
return $data['COUNT(*)'];
}
}
public function delete(){
if(isset($_SESSION['username']) and $this->getOwner() == $_SESSION['username']){
public function delete()
{
if (isset($_SESSION['username']) and $this->getOwner() == $_SESSION['username']) {
$notes = $this->getAllNotes();
foreach($notes as $note){
foreach ($notes as $note) {
$n = new Notes($note['id']);
$n->delete();
}
if($this->id){
$query = "DELETE FROM `apis`.`folders` WHERE (`id` = '$this->id');";
if ($this->id) {
$query = "DELETE FROM `folders` WHERE (`id` = '$this->id');";
$result = mysqli_query($this->db, $query);
return $result;
} else {
......@@ -130,13 +144,14 @@ class Folder extends Share{
}
}
public static function getAllFolders(){
public static function getAllFolders()
{
$db = Database::getConnection();
$query = "SELECT * FROM folders WHERE owner='$_SESSION[username]'";
$result = mysqli_query($db, $query);
if($result){
if ($result) {
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
for($i=0; $i<count($data); $i++){
for ($i=0; $i<count($data); $i++) {
$date = $data[$i]['created_at'];
$c = new Carbon($date);
$data[$i]['created'] = $c->diffForHumans();
......@@ -148,4 +163,4 @@ class Folder extends Share{
return [];
}
}
}
\ No newline at end of file
}
......@@ -6,23 +6,26 @@ require_once $_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php';
use Carbon\Carbon;
class Notes extends Share{
public function __construct($id=null){
class Notes extends Share
{
public function __construct($id=null)
{
parent::__construct($id, 'note');
$this->db = Database::getConnection();
if($id!=null){
if ($id!=null) {
$this->id = $id;
$this->refresh();
}
}
public function refresh(){
if($this->id != null){
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){
if ($result && mysqli_num_rows($result) == 1) {
$this->data = mysqli_fetch_assoc($result);
if($this->getOwner() != $_SESSION['username']){
if ($this->getOwner() != $_SESSION['username']) {
throw new Exception("Unauthorized");
}
$this->id = $this->data['id'];
......@@ -32,52 +35,60 @@ class Notes extends Share{
}
}
public function getOwner(){
if($this->data and isset($this->data['owner'])){
public function getOwner()
{
if ($this->data and isset($this->data['owner'])) {
return $this->data['owner'];
}
}
public function getID(){
public function getID()
{
return $this->id;
}
public function getBody(){
if($this->data and isset($this->data['body'])){
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'])){
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'])){
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'])){
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'])){
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 `apis`.`notes` SET `body` = '$body' WHERE (`id` = '$this->id');";
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();
......@@ -90,10 +101,11 @@ class Notes extends Share{
}
}
public function setTitle($title){
if(isset($_SESSION['username']) and $this->getOwner() == $_SESSION['username']){
if($this->id){
$query = "UPDATE `apis`.`notes` SET `title` = '$title' WHERE (`id` = '$this->id');";
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();
......@@ -106,16 +118,16 @@ class Notes extends Share{
}
}
private function setUpdated(){
if(isset($_SESSION['username']) and $this->getOwner() == $_SESSION['username']){
if($this->id){
$query = "UPDATE `apis`.`notes` SET `updated_at` = '".date("Y-m-d H:i:s")."' WHERE (`id` = '$this->id');";
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) {
if ($result) {
$this->refresh();
return $result;
}
else {
} else {
throw new Exception("Something is not right");
}
} else {
......@@ -126,10 +138,11 @@ class Notes extends Share{
}
}
public function delete(){
if(isset($_SESSION['username']) and $this->getOwner() == $_SESSION['username']){
if($this->id){
$query = "DELETE FROM `apis`.`notes` WHERE (`id` = '$this->id');";
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 {
......@@ -139,13 +152,14 @@ class Notes extends Share{
throw new Exception("Unauthorized ");
}
}
public function createNew($title, $body, $folder){
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 `apis`.`notes` (`title`, `body`, `owner`, `folder_id`) VALUES ('$title', '$body', '$_SESSION[username]', '$folder');";
if(mysqli_query($this->db, $query)){
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;
......@@ -157,4 +171,4 @@ class Notes extends Share{
throw new Exception("Unauthorized");
}
}
}
\ No newline at end of file
}
......@@ -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
}
......@@ -3,75 +3,82 @@
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';
$config_json = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/../env.json');
$config = json_decode($config_json, true);
//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
......@@ -79,20 +86,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
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment