diff --git a/api-payroll/composer.json b/api-payroll/composer.json index 5ed5d2e..86aff1a 100644 --- a/api-payroll/composer.json +++ b/api-payroll/composer.json @@ -25,6 +25,12 @@ "Tests\\": "tests/" } }, + "autoload": { + "psr-4": { + "App\\Service\\": "src/service", + "App\\Application\\": "src/application" + } + }, "config": { "process-timeout" : 0 }, diff --git a/api-payroll/composer.lock b/api-payroll/composer.lock index 87831fe..6a094c8 100644 --- a/api-payroll/composer.lock +++ b/api-payroll/composer.lock @@ -4,7 +4,7 @@ "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", + "hash": "9f4397e11cb2603e7754216c4f59c7ad", "content-hash": "5e16cb7781829836a704bd8767830833", "packages": [ { @@ -733,16 +733,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 +754,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 +792,7 @@ "spy", "stub" ], - "time": "2018-04-18 13:57:24" + "time": "2018-08-05 17:53:17" }, { "name": "phpunit/php-code-coverage", diff --git a/api-payroll/src/application/SessionApplication.php b/api-payroll/src/application/SessionApplication.php new file mode 100644 index 0000000..b7091e0 --- /dev/null +++ b/api-payroll/src/application/SessionApplication.php @@ -0,0 +1,89 @@ +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."; + } +} +?> \ No newline at end of file diff --git a/api-payroll/src/dependencies.php b/api-payroll/src/dependencies.php index 4c20bf8..60ba341 100644 --- a/api-payroll/src/dependencies.php +++ b/api-payroll/src/dependencies.php @@ -17,3 +17,44 @@ $container['logger'] = function ($c) { $logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level'])); 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; +}; diff --git a/api-payroll/src/routes.php b/api-payroll/src/routes.php index 9363ec6..680333b 100644 --- a/api-payroll/src/routes.php +++ b/api-payroll/src/routes.php @@ -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())); +}); \ No newline at end of file diff --git a/api-payroll/src/service/CryptographyService.php b/api-payroll/src/service/CryptographyService.php new file mode 100644 index 0000000..41e3e5d --- /dev/null +++ b/api-payroll/src/service/CryptographyService.php @@ -0,0 +1,88 @@ +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); + } +} \ No newline at end of file diff --git a/api-payroll/src/settings.php b/api-payroll/src/settings.php index 2346883..54893f4 100644 --- a/api-payroll/src/settings.php +++ b/api-payroll/src/settings.php @@ -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.', + ], ], ]; diff --git a/database/database.sql b/database/database.sql new file mode 100644 index 0000000..930a97a --- /dev/null +++ b/database/database.sql @@ -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');