Skip to content

Commit

Permalink
PSR-12
Browse files Browse the repository at this point in the history
  • Loading branch information
tvdijen committed Nov 16, 2019
1 parent 48a65d8 commit d870c1d
Show file tree
Hide file tree
Showing 25 changed files with 164 additions and 138 deletions.
38 changes: 25 additions & 13 deletions config-templates/module_casserver.php
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
<?php
/*

/*
* Configuration for the module casserver.
*
*
*/

$config = [
'authsource' => 'casserver',

/* Scopes are named sets of entityIDs to be used for scoping. If a named scope is provided during login, then the
IdPs listed by the disco service will be restricted to entityIDs in the specified set. */
'scopes' =>[
'scopes' => [
'mobile' => [
'https://idp1.domain:1234/saml2/idp/metadata.php',
'https://idp2.domain:5678/saml2/idp/metadata.php'
],
'desktop' => [
'https://idp3.domain:1234/saml2/idp/metadata.php',
'https://idp3.domain:1234/saml2/idp/metadata.php',
'https://idp4.domain:5678/saml2/idp/metadata.php'
]
],
Expand Down Expand Up @@ -63,8 +64,11 @@
'attributes' => true, // enable transfer of attributes, defaults to true
'attributes_to_transfer' => ['eduPersonPrincipalName'], // set of attributes to transfer, defaults to all

/* Optional authproc filter. Only authproc filters that solely rely on attributes (such as core:AttributeMap and AttributeAlter)
may be used. If your authsource supports authproc filters you are better off doing it there. */
/**
* Optional authproc filter. Only authproc filters that solely rely on attributes
* (such as core:AttributeMap and AttributeAlter)
* may be used. If your authsource supports authproc filters you are better off doing it there.
*/
'authproc' => [
[
'class' => 'core:AttributeMap',
Expand All @@ -75,18 +79,26 @@
],

'base64attributes' => true, // base64 encode transferred attributes, defaults to false
'base64_attributes_indicator_attribute' => 'base64Attributes', /*add an attribute with the value of the base64attributes
configuration parameter to the set of transferred attributes.
Defaults to not adding an indicator attribute. */

/**
* add an attribute with the value of the base64attributes
* configuration parameter to the set of transferred attributes.
* Defaults to not adding an indicator attribute.
*/
'base64_attributes_indicator_attribute' => 'base64Attributes',

'enable_logout' => true, // enable CAS logout, defaults to false
'skip_logout_page' => true, /*perform a redirect instead of showing a logout page with a link to the location
given in the url parameter, defaults to false. Skipping the logout page makes the
url query parameter to CAS logout mandatory for obvious reasons.*/

'service_ticket_expire_time' => 5, //how many seconds service tickets are valid for, defaults to 5
'proxy_granting_ticket_expire_time' => 600, //how many seconds proxy granting tickets are valid for at most, defaults to 3600
'proxy_ticket_expire_time' => 5, //how many seconds proxy tickets are valid for, defaults to 5
// how many seconds service tickets are valid for, defaults to 5
'service_ticket_expire_time' => 5,
// how many seconds proxy granting tickets are valid for at most, defaults to 3600
'proxy_granting_ticket_expire_time' => 600,
//how many seconds proxy tickets are valid for, defaults to 5
'proxy_ticket_expire_time' => 5,

'debugMode' => true, // If query param debugMode=true is sent to the login endpoint then print cas ticket xml. Default false
// If query param debugMode=true is sent to the login endpoint then print cas ticket xml. Default false
'debugMode' => true,
];
3 changes: 2 additions & 1 deletion lib/Cas/CasException.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
*/
class CasException extends \Exception
{
// For list of cas codes see https://apereo.github.io/cas/5.2.x/protocol/CAS-Protocol-Specification.html#253-error-codes
// For list of cas codes see:
// https://apereo.github.io/cas/5.2.x/protocol/CAS-Protocol-Specification.html#253-error-codes
const INVALID_TICKET = 'INVALID_TICKET';
const INVALID_SERVICE = 'INVALID_SERVICE';

Expand Down
2 changes: 1 addition & 1 deletion lib/Cas/Protocol/Cas10.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public function __construct(Configuration $config)
*/
public function getValidateSuccessResponse($username)
{
return "yes\n".$username."\n";
return "yes\n" . $username . "\n";
}


Expand Down
4 changes: 2 additions & 2 deletions lib/Cas/Protocol/Cas20.php
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ public function getProxyFailureResponse($errorCode, $explanation)
private function workAroundForBuggyJasigXmlParser($xmlString)
{
// when will people stop hand coding xml handling....?
return str_replace('><', '>'.PHP_EOL.'<', str_replace(PHP_EOL, '', $xmlString));
return str_replace('><', '>' . PHP_EOL . '<', str_replace(PHP_EOL, '', $xmlString));
}


Expand All @@ -259,7 +259,7 @@ private function generateCas20Attribute($xmlDocument, $attributeName, $attribute
$attributeValueNode = $xmlDocument->createTextNode($this->base64EncodeAttributes ?
base64_encode($attributeValue) : $attributeValue);

$attributeElement = $xmlDocument->createElement('cas:'.$attributeName);
$attributeElement = $xmlDocument->createElement('cas:' . $attributeName);

$attributeElement->appendChild($attributeValueNode);

Expand Down
2 changes: 1 addition & 1 deletion lib/Cas/ServiceValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public function checkServiceURL($service)
$isValidService = true;
break;
} elseif ($result === false) {
Logger::warning("Invalid CAS legal service url '$legalUrl'. Error ".preg_last_error());
Logger::warning("Invalid CAS legal service url '$legalUrl'. Error " . preg_last_error());
}
} elseif (strpos($service, $legalUrl) === 0) {
$isValidService = true;
Expand Down
10 changes: 5 additions & 5 deletions lib/Cas/Ticket/FileSystemTicketStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ public function __construct(Configuration $config)
$path = $config->resolvePath($storeConfig['directory']);

if (is_null($path) || !is_dir($path)) {
throw new Exception('Directory for CAS Server ticket storage ['.strval($path).'] does not exists.');
throw new Exception('Directory for CAS Server ticket storage [' . strval($path) . '] does not exists.');
}

if (!is_writable($path)) {
throw new Exception('Directory for CAS Server ticket storage ['.$path.'] is not writable.');
throw new Exception('Directory for CAS Server ticket storage [' . $path . '] is not writable.');
}

$this->pathToTicketDirectory = preg_replace('/\/$/', '', $path);
Expand All @@ -65,7 +65,7 @@ public function __construct(Configuration $config)
*/
public function getTicket($ticketId)
{
$filename = $this->pathToTicketDirectory.'/'.$ticketId;
$filename = $this->pathToTicketDirectory . '/' . $ticketId;

if (file_exists($filename)) {
$content = file_get_contents($filename);
Expand All @@ -83,7 +83,7 @@ public function getTicket($ticketId)
*/
public function addTicket(array $ticket)
{
$filename = $this->pathToTicketDirectory.'/'.$ticket['id'];
$filename = $this->pathToTicketDirectory . '/' . $ticket['id'];
file_put_contents($filename, serialize($ticket));
}

Expand All @@ -94,7 +94,7 @@ public function addTicket(array $ticket)
*/
public function deleteTicket($ticketId)
{
$filename = $this->pathToTicketDirectory.'/'.$ticketId;
$filename = $this->pathToTicketDirectory . '/' . $ticketId;

if (file_exists($filename)) {
unlink($filename);
Expand Down
2 changes: 1 addition & 1 deletion lib/Cas/Ticket/MemCacheTicketStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,6 @@ public function deleteTicket($ticketId)
*/
private function scopeTicketId($ticketId)
{
return $this->prefix.'.'.$ticketId;
return $this->prefix . '.' . $ticketId;
}
}
36 changes: 18 additions & 18 deletions lib/Cas/Ticket/SQLTicketStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public function deleteTicket($ticketId)
*/
private function scopeTicketId($ticketId)
{
return $this->prefix.'.'.$ticketId;
return $this->prefix . '.' . $ticketId;
}


Expand All @@ -130,9 +130,9 @@ private function initTableVersionTable()
$this->tableVersions = [];

try {
$fetchTableVersion = $this->pdo->query('SELECT _name, _version FROM '.$this->prefix.'_tableVersion');
$fetchTableVersion = $this->pdo->query('SELECT _name, _version FROM ' . $this->prefix . '_tableVersion');
} catch (PDOException $e) {
$this->pdo->exec('CREATE TABLE '.$this->prefix.
$this->pdo->exec('CREATE TABLE ' . $this->prefix .
'_tableVersion (_name VARCHAR(30) NOT NULL UNIQUE, _version INTEGER NOT NULL)');
return;
}
Expand All @@ -153,11 +153,11 @@ private function initKVTable()
return;
}

$query = 'CREATE TABLE '.$this->prefix.
$query = 'CREATE TABLE ' . $this->prefix .
'_kvstore (_key VARCHAR(50) NOT NULL, _value TEXT NOT NULL, _expire TIMESTAMP, PRIMARY KEY (_key))';
$this->pdo->exec($query);

$query = 'CREATE INDEX '.$this->prefix.'_kvstore_expire ON '.$this->prefix.'_kvstore (_expire)';
$query = 'CREATE INDEX ' . $this->prefix . '_kvstore_expire ON ' . $this->prefix . '_kvstore (_expire)';
$this->pdo->exec($query);

$this->setTableVersion('kvstore', 1);
Expand Down Expand Up @@ -191,7 +191,7 @@ private function setTableVersion($name, $version)
Assert::integer($version);

$this->insertOrUpdate(
$this->prefix.'_tableVersion',
$this->prefix . '_tableVersion',
['_name'],
[
'_name' => $name,
Expand All @@ -212,24 +212,24 @@ private function insertOrUpdate($table, array $keys, array $data)
{
Assert::string($table);

$colNames = '('.implode(', ', array_keys($data)).')';
$values = 'VALUES(:'.implode(', :', array_keys($data)).')';
$colNames = '(' . implode(', ', array_keys($data)) . ')';
$values = 'VALUES(:' . implode(', :', array_keys($data)) . ')';

switch ($this->driver) {
case 'mysql':
$query = 'REPLACE INTO '.$table.' '.$colNames.' '.$values;
$query = 'REPLACE INTO ' . $table . ' ' . $colNames . ' ' . $values;
$query = $this->pdo->prepare($query);
$query->execute($data);
return;
case 'sqlite':
$query = 'INSERT OR REPLACE INTO '.$table.' '.$colNames.' '.$values;
$query = 'INSERT OR REPLACE INTO ' . $table . ' ' . $colNames . ' ' . $values;
$query = $this->pdo->prepare($query);
$query->execute($data);
return;
default:
/* Default implementation. Try INSERT, and UPDATE if that fails. */

$insertQuery = 'INSERT INTO '.$table.' '.$colNames.' '.$values;
$insertQuery = 'INSERT INTO ' . $table . ' ' . $colNames . ' ' . $values;
/** @var \PDOStatement|false $insertQuery */
$insertQuery = $this->pdo->prepare($insertQuery);

Expand Down Expand Up @@ -260,7 +260,7 @@ private function insertOrUpdateFallback($table, array $keys, array $data, PDOSta
case '23505': /* PostgreSQL */
break;
default:
Logger::error('casserver: Error while saving data: '.$e->getMessage());
Logger::error('casserver: Error while saving data: ' . $e->getMessage());
throw $e;
}
}
Expand All @@ -269,7 +269,7 @@ private function insertOrUpdateFallback($table, array $keys, array $data, PDOSta
$condCols = [];

foreach ($data as $col => $value) {
$tmp = $col.' = :'.$col;
$tmp = $col . ' = :' . $col;

if (in_array($col, $keys, true)) {
$condCols[] = $tmp;
Expand All @@ -278,7 +278,7 @@ private function insertOrUpdateFallback($table, array $keys, array $data, PDOSta
}
}

$updateQuery = 'UPDATE '.$table.' SET '.implode(',', $updateCols).' WHERE '.implode(' AND ', $condCols);
$updateQuery = 'UPDATE ' . $table . ' SET ' . implode(',', $updateCols) . ' WHERE ' . implode(' AND ', $condCols);
$updateQuery = $this->pdo->prepare($updateQuery);
$updateQuery->execute($data);
}
Expand All @@ -289,7 +289,7 @@ private function insertOrUpdateFallback($table, array $keys, array $data, PDOSta
*/
private function cleanKVStore()
{
$query = 'DELETE FROM '.$this->prefix.'_kvstore WHERE _expire < :now';
$query = 'DELETE FROM ' . $this->prefix . '_kvstore WHERE _expire < :now';
$params = ['now' => gmdate('Y-m-d H:i:s')];

$query = $this->pdo->prepare($query);
Expand All @@ -309,7 +309,7 @@ private function get($key)
$key = sha1($key);
}

$query = 'SELECT _value FROM '.$this->prefix.
$query = 'SELECT _value FROM ' . $this->prefix .
'_kvstore WHERE _key = :key AND (_expire IS NULL OR _expire > :now)';
$params = ['key' => $key, 'now' => gmdate('Y-m-d H:i:s')];

Expand Down Expand Up @@ -369,7 +369,7 @@ private function set($key, $value, $expire = null)
'_expire' => $expire,
];

$this->insertOrUpdate($this->prefix.'_kvstore', ['_key'], $data);
$this->insertOrUpdate($this->prefix . '_kvstore', ['_key'], $data);
}


Expand All @@ -390,7 +390,7 @@ private function delete($key)

];

$query = 'DELETE FROM '.$this->prefix.'_kvstore WHERE _key=:_key';
$query = 'DELETE FROM ' . $this->prefix . '_kvstore WHERE _key=:_key';
$query = $this->pdo->prepare($query);
$query->execute($data);
}
Expand Down
16 changes: 8 additions & 8 deletions lib/Cas/TicketValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,26 +63,26 @@ public function validateAndDeleteTicket($ticket, $service)

$serviceTicket = $this->ticketStore->getTicket($ticket);
if ($serviceTicket == null) {
$message = 'Ticket '.var_export($ticket, true).' not recognized';
Logger::debug('casserver:'.$message);
$message = 'Ticket ' . var_export($ticket, true) . ' not recognized';
Logger::debug('casserver:' . $message);
throw new CasException(CasException::INVALID_TICKET, $message);
}

// TODO: do proxy vs non proxy ticket check
$this->ticketStore->deleteTicket($ticket);

if ($this->ticketFactory->isExpired($serviceTicket)) {
$message = 'Ticket '.var_export($ticket, true).' has expired';
Logger::debug('casserver:'.$message);
$message = 'Ticket ' . var_export($ticket, true) . ' has expired';
Logger::debug('casserver:' . $message);
throw new CasException(CasException::INVALID_TICKET, $message);
}

if (self::sanitize($serviceTicket['service']) !== self::sanitize($service)) {
$message = 'Mismatching service parameters: expected '.
var_export($serviceTicket['service'], true).
' but was: '.var_export($service, true);
$message = 'Mismatching service parameters: expected ' .
var_export($serviceTicket['service'], true) .
' but was: ' . var_export($service, true);

Logger::debug('casserver:'.$message);
Logger::debug('casserver:' . $message);
throw new CasException(CasException::INVALID_SERVICE, $message);
}

Expand Down
2 changes: 1 addition & 1 deletion templates/loggedIn.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,5 @@
$this->includeAtTemplateBase('includes/footer.php');

if (isset($this->data['autofocus'])) {
echo '<script type="text/javascript">window.onload = function() {document.getElementById(\''.$this->data['autofocus'].'\').focus();}</script>';
echo '<script type="text/javascript">window.onload = function() {document.getElementById(\'' . $this->data['autofocus'] . '\').focus();}</script>';
}
4 changes: 2 additions & 2 deletions templates/loggedOut.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@

<?php
if (isset($this->data['url'])) {
echo('<p><a href="'.$this->data["url"].'">'.$this->t('{casserver:casserver:continue_heading}').'</a>');
echo('<p><a href="' . $this->data["url"] . '">' . $this->t('{casserver:casserver:continue_heading}') . '</a>');
}
?>

Expand All @@ -42,5 +42,5 @@
$this->includeAtTemplateBase('includes/footer.php');

if (isset($this->data['autofocus'])) {
echo '<script type="text/javascript">window.onload = function() {document.getElementById(\''.$this->data['autofocus'].'\').focus();}</script>';
echo '<script type="text/javascript">window.onload = function() {document.getElementById(\'' . $this->data['autofocus'] . '\').focus();}</script>';
}
12 changes: 6 additions & 6 deletions tests/bootstrap.php
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
<?php

$projectRootDirectory = dirname(__DIR__);
$projectConfigDirectory = $projectRootDirectory.'/tests/config';
$casserverModulePath = $projectRootDirectory.'/vendor/simplesamlphp/simplesamlphp/modules/casserver';
$simplesamlphpConfig = $projectRootDirectory.'/vendor/simplesamlphp/simplesamlphp/config';
$ticketCacheDir = $projectRootDirectory.'/tests/ticketcache';
$projectConfigDirectory = $projectRootDirectory . '/tests/config';
$casserverModulePath = $projectRootDirectory . '/vendor/simplesamlphp/simplesamlphp/modules/casserver';
$simplesamlphpConfig = $projectRootDirectory . '/vendor/simplesamlphp/simplesamlphp/config';
$ticketCacheDir = $projectRootDirectory . '/tests/ticketcache';
if (!file_exists($ticketCacheDir)) {
mkdir($ticketCacheDir);
}
/** @psalm-suppress UnresolvableInclude */
require_once($projectRootDirectory.'/vendor/autoload.php');
require_once($projectRootDirectory . '/vendor/autoload.php');

/**
* Sets a link in the simplesamlphp vendor directory
Expand All @@ -30,7 +30,7 @@ function symlinkModulePathInVendorDirectory($target, $link)
if (is_link($link) === false) {
// Looks like there is a directory here. Lets remove it and symlink in this one
print "Renaming pre-installed path and linking '$link' to '$target'\n";
rename($link, $link.'-preinstalled');
rename($link, $link . '-preinstalled');
symlink($target, $link);
}
}
Expand Down
Loading

0 comments on commit d870c1d

Please sign in to comment.