Compare commits

...

14 Commits

Author SHA1 Message Date
fea0587ceb [add] Custom error handling 2018-08-05 20:42:45 -06:00
882a9ccad1 [add] Asserts 2018-08-05 20:37:31 -06:00
e033e1ce58 Merge pull request #2 from PootisPenserHere/loginService
Login service and project base
2018-08-05 20:14:37 -06:00
1a4440a99f [add] Applications added to auto load 2018-08-05 20:11:33 -06:00
816b1e356a [add] Endpoints to handle sessions 2018-08-05 20:06:43 -06:00
d7be1f1d9c [mod] Mysql connections moved to dependencies 2018-08-05 19:14:49 -06:00
09f11ebe49 [add] Injecting dependency 2018-08-05 04:30:50 -06:00
2920fdd89b [fix] Loading applciation 2018-08-05 10:02:24 +00:00
52a77c9029 [mod] Falling back to requiere
The namespace autoload was removed for the application to fix the error loading pdo
2018-08-05 03:55:55 -06:00
8b09f75d3a [add] Login endpoint 2018-08-05 03:40:05 -06:00
3fe49d894d [add] Users database 2018-08-05 00:29:00 -06:00
2773092cfc [mod] Typo 2018-08-04 21:00:19 -06:00
5ef983b4cc [add] Crypto methods 2018-08-04 20:37:53 -06:00
9f3ff51798 Merge pull request #1 from PootisPenserHere/settingUpTheFramework
Setting up the framework
2018-08-04 18:33:03 -06:00
10 changed files with 562 additions and 10 deletions

View File

@@ -15,7 +15,8 @@
"php": ">=5.5.0",
"slim/slim": "^3.1",
"slim/php-view": "^2.0",
"monolog/monolog": "^1.17"
"monolog/monolog": "^1.17",
"respect/validation": "^1.1"
},
"require-dev": {
"phpunit/phpunit": ">=4.8 < 6.0"
@@ -25,6 +26,12 @@
"Tests\\": "tests/"
}
},
"autoload": {
"psr-4": {
"App\\Service\\": "src/service",
"App\\Application\\": "src/application"
}
},
"config": {
"process-timeout" : 0
},

View File

@@ -4,8 +4,8 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"hash": "bea55e49da1d79bf5a4874824904525d",
"content-hash": "5e16cb7781829836a704bd8767830833",
"hash": "677ee7ce2e986cfa3ab0df77d78e0a4c",
"content-hash": "fddce0c9f8dd9b23d45f6d6e4b4b6310",
"packages": [
{
"name": "container-interop/container-interop",
@@ -358,6 +358,69 @@
],
"time": "2016-10-10 12:19:37"
},
{
"name": "respect/validation",
"version": "1.1.22",
"source": {
"type": "git",
"url": "https://github.com/Respect/Validation.git",
"reference": "19d6ec893994912d21b390c43d287816ab070772"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Respect/Validation/zipball/19d6ec893994912d21b390c43d287816ab070772",
"reference": "19d6ec893994912d21b390c43d287816ab070772",
"shasum": ""
},
"require": {
"php": ">=5.4",
"symfony/polyfill-mbstring": "^1.2"
},
"require-dev": {
"egulias/email-validator": "~1.2",
"mikey179/vfsstream": "^1.5",
"phpunit/phpunit": "~4.0",
"symfony/validator": "~2.6.9",
"zendframework/zend-validator": "~2.3"
},
"suggest": {
"egulias/email-validator": "Strict (RFC compliant) email validation",
"ext-bcmath": "Arbitrary Precision Mathematics",
"ext-mbstring": "Multibyte String Functions",
"friendsofphp/php-cs-fixer": "Fix PSR2 and other coding style issues",
"symfony/validator": "Use Symfony validator through Respect\\Validation",
"zendframework/zend-validator": "Use Zend Framework validator through Respect\\Validation"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.1-dev"
}
},
"autoload": {
"psr-4": {
"Respect\\Validation\\": "library/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD Style"
],
"authors": [
{
"name": "Respect/Validation Contributors",
"homepage": "https://github.com/Respect/Validation/graphs/contributors"
}
],
"description": "The most awesome validation engine ever created for PHP",
"homepage": "http://respect.github.io/Validation/",
"keywords": [
"respect",
"validation",
"validator"
],
"time": "2018-08-01 13:06:54"
},
{
"name": "slim/php-view",
"version": "2.2.0",
@@ -477,6 +540,65 @@
"router"
],
"time": "2018-04-19 19:29:08"
},
{
"name": "symfony/polyfill-mbstring",
"version": "v1.8.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-mbstring.git",
"reference": "3296adf6a6454a050679cde90f95350ad604b171"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/3296adf6a6454a050679cde90f95350ad604b171",
"reference": "3296adf6a6454a050679cde90f95350ad604b171",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"suggest": {
"ext-mbstring": "For best performance"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.8-dev"
}
},
"autoload": {
"psr-4": {
"Symfony\\Polyfill\\Mbstring\\": ""
},
"files": [
"bootstrap.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for the Mbstring extension",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"mbstring",
"polyfill",
"portable",
"shim"
],
"time": "2018-04-26 10:06:28"
}
],
"packages-dev": [
@@ -733,16 +855,16 @@
},
{
"name": "phpspec/prophecy",
"version": "1.7.6",
"version": "1.8.0",
"source": {
"type": "git",
"url": "https://github.com/phpspec/prophecy.git",
"reference": "33a7e3c4fda54e912ff6338c48823bd5c0f0b712"
"reference": "4ba436b55987b4bf311cb7c6ba82aa528aac0a06"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpspec/prophecy/zipball/33a7e3c4fda54e912ff6338c48823bd5c0f0b712",
"reference": "33a7e3c4fda54e912ff6338c48823bd5c0f0b712",
"url": "https://api.github.com/repos/phpspec/prophecy/zipball/4ba436b55987b4bf311cb7c6ba82aa528aac0a06",
"reference": "4ba436b55987b4bf311cb7c6ba82aa528aac0a06",
"shasum": ""
},
"require": {
@@ -754,12 +876,12 @@
},
"require-dev": {
"phpspec/phpspec": "^2.5|^3.2",
"phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.5"
"phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.5 || ^7.1"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.7.x-dev"
"dev-master": "1.8.x-dev"
}
},
"autoload": {
@@ -792,7 +914,7 @@
"spy",
"stub"
],
"time": "2018-04-18 13:57:24"
"time": "2018-08-05 17:53:17"
},
{
"name": "phpunit/php-code-coverage",

View File

@@ -17,6 +17,20 @@ session_start();
$settings = require __DIR__ . '/../src/settings.php';
$app = new \Slim\App($settings);
// Custom error handling
$c = $app->getContainer();
$c['errorHandler'] = function ($c) {
return function ($request, $response, $exception) use ($c) {
$data = [
'status' => 'error',
'message' => $exception->getMessage()
];
return $c['response']->withStatus(500)
->withHeader('Content-Type', 'application/json')
->write(json_encode($data));
};
};
// Set up dependencies
require __DIR__ . '/../src/dependencies.php';

View File

@@ -0,0 +1,98 @@
<?php
namespace App\Application;
use Exception;
class SessionApplication{
private $pdo;
private $cryptographyService;
private $asserts;
function __construct($mysql, $cryptographyService, $asserts){
$this->cryptographyService = $cryptographyService;
$this->pdo = $mysql;
$this->asserts = $asserts;
$this->databaseSelectQueryErrorMessage = 'There was an error inserting the record.';
}
/**
* @return bool
*/
function verifySession(){
return isset($_SESSION['userName']);
}
/**
* @return array
*/
function checkCurrentSession(){
$session = array();
$session['loggedIn'] = $this->verifySession();
if($this->verifySession()){
$session['userName'] = $_SESSION['userName'];
}
return $session;
}
/**
* @param $userName string
* @return mixed
*/
function getPassword($userName){
$this->asserts->userName($userName);
$stmt = $this->pdo->prepare("SELECT password FROM users WHERE name = :userName");
$stmt->execute(array(':userName' => $userName));
$results = $stmt->fetchAll();
if(!$results){
exit($this->databaseSelectQueryErrorMessage);
}
$stmt = null;
return $results[0]['password'];
}
/**
* @param $userName string
* @param $password string
* @return bool
* @throws Exception
*/
function newSession($userName, $password){
$this->asserts->userName($userName);
$this->asserts->password($password);
$storedPassword = $this->getPassword($userName);
// If the credentials don't match anything in the the records
if(!isset($storedPassword)){
throw new Exception('The user or password didnt match, please try again.');
}
// Already has a session
if($this->verifySession()){
return true;
}
if($this->cryptographyService->decryptPassword($password, $storedPassword)){
$_SESSION['userName'] = $userName;
return true;
}
else{
return false;
}
}
/**
* @return string
*/
function destroySession(){
session_destroy();
return "Sucessfully logged out.";
}
}
?>

View File

@@ -17,3 +17,48 @@ $container['logger'] = function ($c) {
$logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));
return $logger;
};
// Mysql connection
$container['mysql'] = function ($c) {
$mysqlSettings = $c->get('settings')['mysql'];
// The database parameters
$host = $mysqlSettings['host'];
$database = $mysqlSettings['database'];
$user = $mysqlSettings['user'];
$password = $mysqlSettings['password'];
$charset = $mysqlSettings['charset'];
$pdoConnectionOptions = $mysqlSettings['pdoConnectionOptions'];
// Generic error messages
$databaseConnectionErrorMessage = $mysqlSettings['databaseConnectionErrorMessage'];
// Initiate the connection
$dsn = "mysql:host=$host;dbname=$database;charset=$charset";
try {
$pdo = new PDO($dsn, $user, $password, $pdoConnectionOptions);
} catch (Exception $e) {
error_log($e->getMessage());
exit($databaseConnectionErrorMessage);
}
return $pdo;
};
// Cryto functions
$container['cryptographyService'] = function ($c) {
$cryptographySettings = $c->get('settings')['cryptography'];
$cryptographyService = new App\Service\CryptographyService($cryptographySettings);
return $cryptographyService;
};
// Assert functions
$container['asserts'] = function ($c) {
$asserts = new App\Service\Asserts();
return $asserts;
};
// The session application
$container['sessionApplication'] = function ($c) {
$sessionApplication = new App\Application\SessionApplication($c['mysql'], $c['cryptographyService'], $c['asserts']);
return $sessionApplication;
};

View File

@@ -12,3 +12,25 @@ $app->get('/[{name}]', function (Request $request, Response $response, array $ar
// Render index view
return $this->renderer->render($response, 'index.phtml', $args);
});
$app->get('/api/session', function (Request $request, Response $response, array $args) {
return $response->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write(json_encode($this->sessionApplication->checkCurrentSession()));
});
$app->post('/api/session/login', function ($request, $response) {
$RequestData = $request->getParsedBody();
$data = $this->sessionApplication->newSession($RequestData['userName'], $RequestData['password']);
return $response->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write(json_encode($data));
});
$app->post('/api/session/logout', function (Request $request, Response $response, array $args) {
return $response->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write(json_encode($this->sessionApplication->destroySession()));
});

View File

@@ -0,0 +1,84 @@
<?php
namespace App\Service;
use Exception;
use Respect\Validation\Validator as v;
class Asserts{
/**
* @param $string
* @throws Exception
*/
function userName($string){
$validateFirstName = v::stringType()->notEmpty()->length(1, 50)->validate($string);
if(!$validateFirstName){
throw new Exception('The user name must be a string between 1 and 50 characters');
}
}
/**
* @param $string
* @throws Exception
*/
function password($string){
$validateFirstName = v::stringType()->notEmpty()->length(1, 50)->validate($string);
if(!$validateFirstName){
throw new Exception('The password must be a string between 1 and 50 characters');
}
}
/**
* @param $string
* @throws Exception
*/
function firstName($string){
$validateFirstName = v::stringType()->notEmpty()->length(1, 100)->validate($string);
if(!$validateFirstName){
throw new Exception('The first name must be a string between 1 and 100 characters');
}
}
/**
* @param $string
* @throws Exception
*/
function middleName($string){
if(!v::stringType()->notEmpty()->length(1, 100)->validate($string)){
throw new Exception('The middle name must be a string between 1 and 100 characters');
}
}
/**
* @param $string
* @throws Exception
*/
function birthDate($string){
if(!v::date('Y-m-d')->notEmpty()->validate($string)){
throw new Exception('The birth date must be in the yyyy-mm-dd format');
}
}
/**
* @param $string
* @throws Exception
*/
function email($string){
if(!v::stringType()->notEmpty()->length(1, 100)->validate($string)){
throw new Exception('The email must be a string between 1 and 100 characters');
}
}
/**
* @param $string
* @throws Exception
*/
function phone($string){
if(!v::digit()->notEmpty()->length(10, 10)->validate($string)){
throw new Exception('The phone must be a numeric value of 10 digits');
}
}
}
?>

View File

@@ -0,0 +1,88 @@
<?php
namespace App\Service;
/**
* A collection of functions to securely handling sensitive data,
* passwords as well as making use of other crypto needs within
* the project
*
* @property settings
*/
class CryptographyService{
function __construct($cryptographySettings) {
$this->settings = $cryptographySettings;
}
/**
* Encrypts a string using the predefined algorithm, the resulting string will contain the
* concatenated iv used for salting as well as the cipher text, both in hex format
*
* @param $text string
* @return string
* @throws \Exception
*/
function encryptString($text){
try {
$iv = random_bytes($this->settings['ivSize']);
$ivInHex = bin2hex($iv);
$encryptedMessage = openssl_encrypt($text, $this->settings['encryptionAlgorithm'],
$this->settings['encryptionPassword'], 1, $iv);
$hexedCipherText = bin2hex($encryptedMessage);
return "$ivInHex$hexedCipherText";
} catch (Exception $e) {
throw new Exception('There was an error encrypting the string, contact the system administrator.');
$this->logger->warning("There was an error in the cryptographyService->encryptString caused by: $e ");
}
}
/**
* Decrypts a string using the predefined algorithm
*
* This method assumes that an iv with the length taken from the setting ivSize is present
* at the beginning of the string and this will be used to decrypt the cipher text
*
* @param $cipherText string
* @return string
*/
function decryptString($cipherText) {
$cipherText = hex2bin($cipherText);
$totalCharaters = strlen($cipherText);
$iv = substr($cipherText, 0, $this->settings['ivSize']);
$cipherTextWithIv = substr($cipherText, $this->settings['ivSize'], $totalCharaters);
return openssl_decrypt($cipherTextWithIv, $this->settings['encryptionAlgorithm'],
$this->settings['encryptionPassword'], 1, $iv);
}
/**
* Securely hashes a password for its coldstorage
*
* @param $password string
* @return string
*/
function encryptPassword($password) {
$options = [
'cost' => $this->settings['passwordHashCost'],
];
return password_hash($password, PASSWORD_BCRYPT, $options);
}
/**
* Compares a password given in plain text against the encrypted veersion to determined if they're
* the same password
*
* @param $plainPassword string
* @param $encryptedPassword string
* @return bool
*/
function decryptPassword($plainPassword, $encryptedPassword) {
return password_verify($plainPassword, $encryptedPassword);
}
}

View File

@@ -15,5 +15,30 @@ return [
'path' => isset($_ENV['docker']) ? 'php://stdout' : __DIR__ . '/../logs/app.log',
'level' => \Monolog\Logger::DEBUG,
],
// Cryptography settings
'cryptography' => [
'encryptionAlgorithm' => 'AES-256-CBC',
'encryptionPassword' => '7de431684c34cf2c898268cff71392f38c4175dde050c9ee69502b81571484e0',
'passwordHashCost' => '12',
'ivSize' => 16, // 128 bits
],
// Datanase settings
'mysql' => [
'host' => 'localhost',
'database' => 'payroll',
'user' => 'root',
'password' => '12345678',
'charset' => 'utf8',
'pdoConnectionOptions' => [
PDO::ATTR_EMULATE_PREPARES => true, // The querys will be prepared by pdo instead of the dbms
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // Errors will be returned as exceptions
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // Data will be returned in associative arrays
],
'databaseConnectionErrorMessage' => 'Unable to connect to the database.',
'databaseSelectQueryErrorMessage' => 'There was an error fetching the data.',
'databaseInsertQueryErrorMessage' => 'There was an error inserting the record.',
],
],
];

47
database/database.sql Normal file
View File

@@ -0,0 +1,47 @@
DROP DATABASE IF EXISTS payroll;
CREATE DATABASE payroll;
USE payroll;
DROP TABLE IF EXISTS persons;
CREATE TABLE IF NOT EXISTS `persons` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`firstName` varbinary(500) NOT NULL comment 'The name of the person',
`middleName` varbinary(500) NOT NULL comment 'The midle name of the person',
`lastName` varbinary(500) comment 'The last name of the person',
`birthDate` DATE NOT NULL DEFAULT '1900-01-01' comment 'Date of birth of the person',
`email` varbinary(500) NOT NULL comment 'The email adress of the person',
`phone` INT(10) UNSIGNED NOT NULL comment 'The phone number of the person should be the mobile one but leaves room for home ones',
`status` ENUM('ACTIVE', 'INACTIVE') NOT NULL DEFAULT 'ACTIVE',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP comment 'The date on which the registry was created',
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP comment 'The date of the last time the row was modified',
PRIMARY KEY (`id`),
UNIQUE (`phone`),
UNIQUE (`firstName`,`middleName`,`lastName`,`birthDate`)
);
INSERT INTO persons (firstName, middleName, lastName, birthDate, email, phone)
VALUES (
'0524a1848795041c2259ad658897913d25bc36e7ce54fa8465de767a03be8aaa957591c84d51dd85f1b58fc0826db835',
'b5293d82e3ebc1f36eb70f8c0007aaa2aa1cd3f1e2903e1e36fb35137e967d3a',
'b04e81e22a98c1abfcb85688926aa5fa12aea511f600424c25a7e9b14a0ac6f8',
'1991-06-06',
'205fbeba023a9b846a11492bfc6e039619bb6068030bcc13e45d30e638f6c51b4099911dee2b5644d55b43a38e8591f32f579ba0df9bd710b9e6bf66e0544184',
'0123456789');
DROP TABLE IF EXISTS users;
CREATE TABLE IF NOT EXISTS `users` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`idPerson` INT UNSIGNED NOT NULL comment 'Id of the person, this contains the name and other personal data',
`name` VARCHAR(50) NOT NULL comment 'Username',
`password` VARCHAR(500) NOT NULL comment 'Hashed password',
`status` ENUM('ACTIVE', 'INACTIVE') NOT NULL DEFAULT 'ACTIVE',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP comment 'The date on which the registry was created',
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP comment 'The date of the last time the row was modified',
PRIMARY KEY (`id`),
FOREIGN KEY (idPerson) REFERENCES persons(id),
UNIQUE (`name`)
);
INSERT INTO users (idPerson, name, password)
VALUES (1, 'sloth', '$2y$12$51mfESaLEGXDT4u9Bd9kiOHEpaJ1Bx4SEcVwsU5K6jVPMNkrnpJAa');