Skip to content
This repository was archived by the owner on Jun 8, 2019. It is now read-only.

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
rigwild committed Dec 5, 2018
1 parent d945b57 commit cc3fd41
Show file tree
Hide file tree
Showing 12 changed files with 275 additions and 1 deletion.
16 changes: 16 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true

# Matches multiple files with brace expansion notation
# Set default charset
[*.{js,py}]
charset = utf-8

# 4 space indentation
[*]
indent_style = space
indent_size = 2
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
models/DatabaseConfig.class.php
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2018
Copyright (c) 2018 rigwild <https://asauvage.fr/>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
11 changes: 11 additions & 0 deletions controllers/disconnect.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

require __DIR__.'/../lib/Util.class.php';

// Check if the user is logged in the API
Util::checkLoggedInAPI();

http_response_code(204);
session_destroy();

?>
10 changes: 10 additions & 0 deletions controllers/error.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

http_response_code($httpCode ?? 500);

header('Content-Type: application/json');
echo json_encode(['error' => $error ?? 'Unknown error']);

exit();

?>
40 changes: 40 additions & 0 deletions controllers/example.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

require __DIR__.'/../lib/Util.class.php';

// Check if the user is logged in the API
Util::checkLoggedInAPI();

// Get the body from the request
$json = Util::getJSON();

// API endpoint request method
$requestType = 'POST';

// Check if HTTP method matches
if ($_SERVER['REQUEST_METHOD'] !== $requestType) {
http_response_code(405);
exit();
}

// Check if the body of the request contains the needed data
if (!$json || !empty($json['sentData'])) {
http_response_code(400);
exit();
}


header('Content-Type: application/json');

$sentData = $json['sentData'];

require __DIR__.'/../models/getFromDatabaseExample.php';

// The database returned an error
if (isset($error))
require __DIR__.'/error.php';

// Everything is fine, send the result
echo json_encode($res);

?>
19 changes: 19 additions & 0 deletions controllers/login.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

/*
Here comes your login script.
When done, simply use this at the top of your controller :
require __DIR__.'/../lib/Util.class.php';
Util::checkLoggedInAPI();
It will send a 403 error if the user is not logged in.
*/


http_response_code(204);
$_SESSION['loggedIn'] = true;

?>
23 changes: 23 additions & 0 deletions index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

session_start();

$controller = $_GET['controller'] ?? null;

// Load the right controller
if (!empty($controller)) {
if (is_file('controllers/'.$controller.'.php'))
require 'controllers/'.$controller.'.php';
else {
$error = 'Unknown controller.';
$httpCode = 404;
require 'controllers/error.php';
}
}
else {
$error = 'You must specify a controller by using `?controller=requestedController`.';
$httpCode = 409;
require 'controllers/error.php';
}

?>
28 changes: 28 additions & 0 deletions lib/Util.class.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

class Util {
// Check if the user is logged in
public static function checkLoggedInAPI()
{
if (!(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'])) {
http_response_code(403);
exit();
}
}

// Escape bad HTML chars
public static function escapeHTML($content = "")
{
return htmlspecialchars($content, ENT_QUOTES, 'UTF-8');
}

// Get JSON sent to the server
public static function getJSON()
{
$json = file_get_contents('php://input');
$json = json_decode($json, true);
return json_last_error() === JSON_ERROR_NONE ? $json : null;
}
}

?>
73 changes: 73 additions & 0 deletions models/Database.class.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

/**
* Usage :
* $dbLink = new Database();
*
* $req1 = $dbLink->execute('SELECT * FROM users');
* $req2 = $dbLink->execute('SELECT * FROM users WHERE username = :username', ['username' => 'rigwild']);
*
* The link with the database is established once on each reload.
*
* @author rigwild - https://github.com/rigwild
* @see https://gist.github.com/rigwild/5d4660f3f6f979171496a11e548020d9
*/

require_once 'DatabaseConfig.class.php';

class Database {
private $dbCredentials = null;
private $connection = null;

public function __construct() {
$this->dbCredentials = Config::$DatabaseCredentials;
}

private function connect() {
if ($this->connection !== null)
return $this->connection;
$dbInfos = $this->dbCredentials['SGBD']
.':host='.$this->dbCredentials['host']
.';port='.$this->dbCredentials['port']
.';dbname='.$this->dbCredentials['dbName']
.';charset=utf8';
$username = $this->dbCredentials['username'];
$password = $this->dbCredentials['password'];
$conn = new PDO($dbInfos, $username, $password);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->connection = $conn;
return $conn;
}

/**
* Execute a select query
* @param query the SQL query to execute
* @param parametersArray an array of parameters
*
* @return boolean the result of the query
*/
public function select($query, $parametersArray = []) {
$conn = $this->connect();
$stmt = $conn->prepare($query);
if ($stmt->execute($parametersArray))
return $stmt->fetchAll();
return null;
}

/**
* Execute a query that doesn't return any tuples
* @param query the SQL query to execute
* @param parametersArray an array of parameters
*
* @return boolean the query worked
*/
public function execute($query, $parametersArray = []) {
$conn = $this->connect();
$stmt = $conn->prepare($query);
return ($stmt->execute($parametersArray));
}
}

?>
20 changes: 20 additions & 0 deletions models/DatabaseConfig.default.class.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/**
* Configure the connection to the database.
*
* @author rigwild - https://github.com/rigwild
* @see https://gist.github.com/rigwild/5d4660f3f6f979171496a11e548020d9
*/

class Config {
static public $DatabaseCredentials = [
'SGBD' => 'mysql',
'host' => 'localhost',
'port' => '3306',
'dbName' => 'dbName',
'username' => 'root',
'password' => ''
];
}
?>
33 changes: 33 additions & 0 deletions models/getFromDatabaseExample.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

require 'Database.class.php';

$dbLink = new Database();

// The controller `example.php` sent the variable `$sentData` !

// Check for errors
if ($sentData === 42) {
// Error : The anwser to the universe was sent
$httpCode = 409;
$error = 'You can\'t send the answer to the universe.';
return;
}

// No errors, add the data to the database
try {
$query = 'INSERT INTO numbers (a_number) VALUES (:a_number)';
$params = [
'a_number' => $sentData
];

// Commented for example purposes
// $res = $dbLink->execute($query, $params);

// $res will be sent back to `example.php`
$res = true;
} catch (PDOException $e) {
$error = $e->getMessage();
}

?>

0 comments on commit cc3fd41

Please sign in to comment.