Skip to content

Commit

Permalink
Merge pull request #4 from likel/unit-tests
Browse files Browse the repository at this point in the history
Unit tests
  • Loading branch information
likel authored Oct 12, 2017
2 parents 2f38435 + fd4be22 commit 73ecb8e
Show file tree
Hide file tree
Showing 6 changed files with 298 additions and 63 deletions.
28 changes: 22 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ This package is designed to store PHP sessions in a MySQL database so that you c

### Installing on your server

Create a session table in your MySQL database by running [install/setup.sql](install/setup.sql)
1. Create a session table in your MySQL database by running [install/setup.sql](install/setup.sql)

```
CREATE TABLE `likel_sessions` (
Expand All @@ -25,20 +25,36 @@ CREATE TABLE `likel_sessions` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```

Step 2
2. Move the files under /src into a directory on your server such as "session"

```
Example
e.g. session/ini, session/models, session/autoload.php, session/example.php
```

Run example.php
3. Move the [ini/credentials.ini](ini/credentials.ini) file to a location not accessible by the public

```
e.g. $ mv ini/credentials /var/www/html/
```

4. Update the database information in the credentials.ini file

5. Ensure that when you create a new session you specify the new credentials.ini location

```
$session = new Likel\Session\Handler(array(
'credentials_location' => "/path/to/new/credentials.ini"
));
```

6. Run [src/example.php](src/example.php) and check your database for the newly created session

## Running the tests

Run [file] with PHPUnit
Run [test/SessionHandlerTest.php](test/SessionHandlerTest.php) with PHPUnit

```
$ phpunit Test.php
$ phpunit SessionHandlerTest.php
```

## Author
Expand Down
31 changes: 24 additions & 7 deletions src/autoload.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
<?php
/**
* Load the models
*
* Sadly we can't use an autoloader here in the case that the end-user
* is using one. Multiple autoloaders can cause conflicts
* PSR-4 autoload
*
* After registering this autoload function with require_once()
* Likel/Session/Handler can be called like this:
*
* $session = new Likel\Session\Handler();
Expand All @@ -17,6 +15,25 @@
* @version 1.0.0
*/

// Require the models
require_once(__DIR__ . '/models/DB.php');
require_once(__DIR__ . '/models/Session/Handler.php');
// Require the models when called
spl_autoload_register(function ($class_name) {
// Change these depending on the project
$project_prefix = 'Likel\\';
$models_dir = __DIR__ . '/models/';

// Helper variables used in the autoloader
$project_prefix_length = strlen($project_prefix);
$relative_class = substr($class_name, $project_prefix_length);

// Return if the requested class does not include the prefix
if (strncmp($project_prefix, $class_name, $project_prefix_length) !== 0) {
return;
}

// Replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the class name and append with .php
$file = $models_dir . str_replace('\\', '/', $relative_class) . '.php';
if (file_exists($file)) {
require_once($file);
}
});
15 changes: 15 additions & 0 deletions src/ini/.htaccess
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# It is highly suggested to move credentials.ini to a directory not
# accessible by the public, such as /var/www/html on linux
#
# If you need to keep the credentials.ini accessible, ensure that you
# give the file '600' permissions '$ chmod 600 credentials.ini' and
# that you have this .htaccess file to deny access or redirect if accessed
#
# @package php-simple-sessions
# @author Liam Kelly <https://github.com/likel>
# @copyright 2017 Liam Kelly
# @license MIT License <https://github.com/likel/php-simple-sessions/blob/master/LICENSE>
# @link https://github.com/likel/php-simple-sessions
# @version 1.0.0

deny from all
48 changes: 29 additions & 19 deletions src/models/DB.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
* @copyright 2017 Liam Kelly
* @license MIT License <https://github.com/likel/php-simple-sessions/blob/master/LICENSE>
* @link https://github.com/likel/php-simple-sessions
* @version 1.0.0
* @version 1.0.1
*/
namespace Likel;

Expand All @@ -28,11 +28,9 @@ class DB
public function __construct($credentials_location)
{
try {
$db_credentials = parse_ini_file($credentials_location, true);
$this->database_handler = $this->loadDatabase($db_credentials["likel_db"]);
$this->table_prefix = $db_credentials["likel_db"]["table_prefix"];
$this->database_handler = $this->loadDatabase($credentials_location);
} catch (\Exception $ex) {
throw $ex;
echo $ex->getMessage();
}
}

Expand All @@ -44,27 +42,34 @@ public function __construct($credentials_location)
* @throws \Exception If credentials empty or not found
* @throws \PDOException If PDO connection is unsuccessful
*/
private function loadDatabase($credentials)
private function loadDatabase($credentials_location)
{
if(!empty($credentials)){
try {
$dsn = 'mysql:host=' . $credentials['host'] . ';dbname=' . $credentials['db_name'];
if(file_exists($credentials_location)) {
$db_credentials = parse_ini_file($credentials_location, true);
$credentials = $db_credentials["likel_db"];

$options = array(
\PDO::ATTR_PERSISTENT => true,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
);
if(!empty($credentials)){
try {
$dsn = 'mysql:host=' . $credentials['host'] . ';dbname=' . $credentials['db_name'];

$pdo_object = new \PDO($dsn, $credentials['username'], $credentials['password'], $options);
$options = array(
\PDO::ATTR_PERSISTENT => true,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
);

return $pdo_object;
$pdo_object = new \PDO($dsn, $credentials['username'], $credentials['password'], $options);

} catch(\PDOException $e) {
throw new \Exception($e->getMessage());
}
$this->table_prefix = $db_credentials["likel_db"]["table_prefix"];

return $pdo_object;
} catch(\PDOException $e) {
throw new \Exception($e->getMessage());
}
} else {
throw new \Exception('The likel_db parameter in the credentials file cannot be found.');
}
} else {
throw new \Exception('The credential file could not be located or is empty.');
throw new \Exception('The credential file could not be located.');
}
}

Expand Down Expand Up @@ -222,4 +227,9 @@ public function dumpStatement()
{
$this->statement->debugDumpParams();
}

public function databaseInitialised()
{
return !empty($this->database_handler);
}
}
76 changes: 45 additions & 31 deletions src/models/Session/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
* @copyright 2017 Liam Kelly
* @license MIT License <https://github.com/likel/php-simple-sessions/blob/master/LICENSE>
* @link https://github.com/likel/php-simple-sessions
* @version 1.0.0
* @version 1.0.1
*/
namespace Likel\Session;

Expand All @@ -32,24 +32,56 @@ class Handler implements \ArrayAccess
*/
function __construct($parameters = array())
{
if(!is_array($parameters)) {
$parameters = array();
}

// Defaults
$parameters["session_name"] = empty($parameters["session_name"]) ? "likel_session" : $parameters["session_name"];
$parameters["secure"] = empty($parameters["secure"]) ? false : $parameters["secure"];
$parameters["secure"] = empty($parameters["secure"]) ? false : is_bool($parameters["secure"] === true) ? true : false;
$parameters["credentials_location"] = empty($parameters["credentials_location"]) ? __DIR__ . '/../../ini/credentials.ini' : $parameters["credentials_location"];

// Setup the database class variable
$this->db = new \Likel\DB($parameters["credentials_location"]);

// Attempt to get the secret_hash from the credentials file
try {
$session_credentials = parse_ini_file($parameters["credentials_location"], true);
$this->secret_hash = $this->loadSecretHash($session_credentials["likel_session"]);
} catch (\Exception $ex) {
throw $ex;
if($this->db->databaseInitialised()) {
// Attempt to get the secret_hash from the credentials file
try {
$this->secret_hash = $this->loadSecretHash($parameters["credentials_location"]);

// Start session
$this->start_session($parameters["session_name"], $parameters["secure"]);
} catch (\Exception $ex) {
echo $ex->getMessage();
}
}
}

// Start session
$this->start_session($parameters["session_name"], $parameters["secure"]);
/**
* Attempt to retrieve the secret_hash from the credentials file
*
* @param array $credentials likel_session from the credentials.ini file
* @return string
* @throws \Exception If credentials empty or not found
*/
private function loadSecretHash($credentials_location)
{
if(file_exists($credentials_location)) {
$session_credentials = parse_ini_file($credentials_location, true);
$credentials = $session_credentials["likel_session"];

if(!empty($credentials)){
if(!empty($credentials["secret_hash"])) {
return $credentials["secret_hash"];
} else {
throw new \Exception('The session_hash variable is empty.');
}
} else {
throw new \Exception('The likel_session parameter in the credentials file cannot be found.');
}
} else {
throw new \Exception('The credential file could not be located.');
}
}

/**
Expand Down Expand Up @@ -241,27 +273,6 @@ private function getKeyAndIv($id)
}
}

/**
* Attempt to retrieve the secret_hash from the credentials file
*
* @param array $credentials likel_session from the credentials.ini file
* @return string
* @throws \Exception If credentials empty or not found
*/
private function loadSecretHash($credentials)
{
if(!empty($credentials)){
if(!empty($credentials["secret_hash"])) {
return $credentials["secret_hash"];
} else {
throw new \Exception('The session_hash variable is empty.');
}

} else {
throw new \Exception('The credential file could not be located or is empty.');
}
}

/**
* Setup and start the session
*
Expand Down Expand Up @@ -294,6 +305,9 @@ private function start_session($session_name, $secure)
session_name($session_name);
session_start();

// Put it into the DB so we don't delay
$this->_write(session_id(), '');

// Regenerate ID is recommended to reset the session every reload
// Bug occurs if set to true that causes the current session to
// be removed if loading pages too quickly
Expand Down
Loading

0 comments on commit 73ecb8e

Please sign in to comment.