Merge pull request #2 from PootisPenserHere/loginService

Login service and project base
This commit is contained in:
Jose Pablo Domingo Aramburo Sanchez 2018-08-05 20:14:37 -06:00 committed by GitHub
commit e033e1ce58
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 326 additions and 8 deletions

View File

@ -25,6 +25,12 @@
"Tests\\": "tests/" "Tests\\": "tests/"
} }
}, },
"autoload": {
"psr-4": {
"App\\Service\\": "src/service",
"App\\Application\\": "src/application"
}
},
"config": { "config": {
"process-timeout" : 0 "process-timeout" : 0
}, },

View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"hash": "bea55e49da1d79bf5a4874824904525d", "hash": "9f4397e11cb2603e7754216c4f59c7ad",
"content-hash": "5e16cb7781829836a704bd8767830833", "content-hash": "5e16cb7781829836a704bd8767830833",
"packages": [ "packages": [
{ {
@ -733,16 +733,16 @@
}, },
{ {
"name": "phpspec/prophecy", "name": "phpspec/prophecy",
"version": "1.7.6", "version": "1.8.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/phpspec/prophecy.git", "url": "https://github.com/phpspec/prophecy.git",
"reference": "33a7e3c4fda54e912ff6338c48823bd5c0f0b712" "reference": "4ba436b55987b4bf311cb7c6ba82aa528aac0a06"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/phpspec/prophecy/zipball/33a7e3c4fda54e912ff6338c48823bd5c0f0b712", "url": "https://api.github.com/repos/phpspec/prophecy/zipball/4ba436b55987b4bf311cb7c6ba82aa528aac0a06",
"reference": "33a7e3c4fda54e912ff6338c48823bd5c0f0b712", "reference": "4ba436b55987b4bf311cb7c6ba82aa528aac0a06",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@ -754,12 +754,12 @@
}, },
"require-dev": { "require-dev": {
"phpspec/phpspec": "^2.5|^3.2", "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", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "1.7.x-dev" "dev-master": "1.8.x-dev"
} }
}, },
"autoload": { "autoload": {
@ -792,7 +792,7 @@
"spy", "spy",
"stub" "stub"
], ],
"time": "2018-04-18 13:57:24" "time": "2018-08-05 17:53:17"
}, },
{ {
"name": "phpunit/php-code-coverage", "name": "phpunit/php-code-coverage",

View File

@ -0,0 +1,89 @@
<?php
namespace App\Application;
class SessionApplication{
private $pdo;
private $cryptographyService;
function __construct($mysql, $cryptographyService){
$this->cryptographyService = $cryptographyService;
$this->pdo = $mysql;
$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){
$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){
$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,44 @@ $container['logger'] = function ($c) {
$logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level'])); $logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));
return $logger; return $logger;
}; };
// Mysql connecrion
$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'];
$databaseSelectQueryErrorMessage = $mysqlSettings['databaseSelectQueryErrorMessage'];
$databaseInsertQueryErrorMessage = $mysqlSettings['databaseInsertQueryErrorMessage'];
// 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;
};
// The session application
$container['sessionApplication'] = function ($c) {
$sessionApplication = new App\Application\SessionApplication($c['mysql'], $c['cryptographyService']);
return $sessionApplication;
};

View File

@ -12,3 +12,25 @@ $app->get('/[{name}]', function (Request $request, Response $response, array $ar
// Render index view // Render index view
return $this->renderer->render($response, 'index.phtml', $args); 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,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', 'path' => isset($_ENV['docker']) ? 'php://stdout' : __DIR__ . '/../logs/app.log',
'level' => \Monolog\Logger::DEBUG, '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');