1
0
mirror of https://github.com/delight-im/PHP-Auth.git synced 2025-08-02 22:27:30 +02:00

Improve code style

This commit is contained in:
Marco
2017-10-12 02:42:40 +02:00
parent 04c466b309
commit 8fecb86f15
4 changed files with 120 additions and 120 deletions

View File

@@ -107,7 +107,7 @@ final class Administration extends UserManager {
*/
public function deleteUserByUsername($username) {
$userData = $this->getUserDataByUsername(
trim($username),
\trim($username),
[ 'id' ]
);

View File

@@ -61,16 +61,16 @@ final class Auth extends UserManager {
/** Initializes the session and sets the correct configuration */
private function initSession() {
// use cookies to store session IDs
ini_set('session.use_cookies', 1);
\ini_set('session.use_cookies', 1);
// use cookies only (do not send session IDs in URLs)
ini_set('session.use_only_cookies', 1);
\ini_set('session.use_only_cookies', 1);
// do not send session IDs in URLs
ini_set('session.use_trans_sid', 0);
\ini_set('session.use_trans_sid', 0);
// get our cookie settings
$params = $this->createCookieSettings();
// define our new cookie settings
session_set_cookie_params($params['lifetime'], $params['path'], $params['domain'], $params['secure'], $params['httponly']);
\session_set_cookie_params($params['lifetime'], $params['path'], $params['domain'], $params['secure'], $params['httponly']);
// start the session
@Session::start();
@@ -79,19 +79,19 @@ final class Auth extends UserManager {
/** Improves the application's security over HTTP(S) by setting specific headers */
private function enhanceHttpSecurity() {
// remove exposure of PHP version (at least where possible)
header_remove('X-Powered-By');
\header_remove('X-Powered-By');
// if the user is signed in
if ($this->isLoggedIn()) {
// prevent clickjacking
header('X-Frame-Options: sameorigin');
\header('X-Frame-Options: sameorigin');
// prevent content sniffing (MIME sniffing)
header('X-Content-Type-Options: nosniff');
\header('X-Content-Type-Options: nosniff');
// disable caching of potentially sensitive data
header('Cache-Control: no-store, no-cache, must-revalidate', true);
header('Expires: Thu, 19 Nov 1981 00:00:00 GMT', true);
header('Pragma: no-cache', true);
\header('Cache-Control: no-store, no-cache, must-revalidate', true);
\header('Expires: Thu, 19 Nov 1981 00:00:00 GMT', true);
\header('Pragma: no-cache', true);
}
}
@@ -102,7 +102,7 @@ final class Auth extends UserManager {
// if a remember cookie is set
if (isset($_COOKIE[self::COOKIE_NAME_REMEMBER])) {
// split the cookie's content into selector and token
$parts = explode(self::COOKIE_CONTENT_SEPARATOR, $_COOKIE[self::COOKIE_NAME_REMEMBER], 2);
$parts = \explode(self::COOKIE_CONTENT_SEPARATOR, $_COOKIE[self::COOKIE_NAME_REMEMBER], 2);
// if both selector and token were found
if (isset($parts[0]) && isset($parts[1])) {
try {
@@ -116,8 +116,8 @@ final class Auth extends UserManager {
}
if (!empty($rememberData)) {
if ($rememberData['expires'] >= time()) {
if (password_verify($parts[1], $rememberData['token'])) {
if ($rememberData['expires'] >= \time()) {
if (\password_verify($parts[1], $rememberData['token'])) {
$this->onLoginSuccessful($rememberData['user'], $rememberData['email'], $rememberData['username'], $rememberData['status'], $rememberData['roles_mask'], true);
}
}
@@ -361,8 +361,8 @@ final class Auth extends UserManager {
private function createRememberDirective($userId, $duration) {
$selector = self::createRandomString(24);
$token = self::createRandomString(32);
$tokenHashed = password_hash($token, PASSWORD_DEFAULT);
$expires = time() + ((int) $duration);
$tokenHashed = \password_hash($token, \PASSWORD_DEFAULT);
$expires = \time() + ((int) $duration);
try {
$this->db->insert(
@@ -399,7 +399,7 @@ final class Auth extends UserManager {
throw new DatabaseError();
}
$this->setRememberCookie(null, null, time() - 3600);
$this->setRememberCookie(null, null, \time() - 3600);
}
/**
@@ -461,7 +461,7 @@ final class Auth extends UserManager {
try {
$this->db->update(
$this->dbTablePrefix . 'users',
[ 'last_login' => time() ],
[ 'last_login' => \time() ],
[ 'id' => $userId ]
);
}
@@ -548,8 +548,8 @@ final class Auth extends UserManager {
}
if (!empty($confirmationData)) {
if (password_verify($token, $confirmationData['token'])) {
if ($confirmationData['expires'] >= time()) {
if (\password_verify($token, $confirmationData['token'])) {
if ($confirmationData['expires'] >= \time()) {
// invalidate any potential outstanding password reset requests
try {
$this->db->delete(
@@ -700,7 +700,7 @@ final class Auth extends UserManager {
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
private function updatePassword($userId, $newPassword) {
$newPassword = password_hash($newPassword, PASSWORD_DEFAULT);
$newPassword = \password_hash($newPassword, \PASSWORD_DEFAULT);
try {
$this->db->update(
@@ -978,7 +978,7 @@ final class Auth extends UserManager {
);
}
elseif ($username !== null) {
$username = trim($username);
$username = \trim($username);
// attempt to look up the account information using the specified username
$userData = $this->getUserDataByUsername(
@@ -994,9 +994,9 @@ final class Auth extends UserManager {
$password = self::validatePassword($password);
if (password_verify($password, $userData['password'])) {
if (\password_verify($password, $userData['password'])) {
// if the password needs to be re-hashed to keep up with improving password cracking techniques
if (password_needs_rehash($userData['password'], PASSWORD_DEFAULT)) {
if (\password_needs_rehash($userData['password'], \PASSWORD_DEFAULT)) {
// create a new hash from the password and update it in the database
$this->updatePassword($userData['id'], $password);
}
@@ -1064,7 +1064,7 @@ final class Auth extends UserManager {
*/
private function getUserDataByEmailAddress($email, array $requestedColumns) {
try {
$projection = implode(', ', $requestedColumns);
$projection = \implode(', ', $requestedColumns);
$userData = $this->db->selectRow(
'SELECT ' . $projection . ' FROM ' . $this->dbTablePrefix . 'users WHERE email = ?',
[ $email ]
@@ -1095,7 +1095,7 @@ final class Auth extends UserManager {
'SELECT COUNT(*) FROM ' . $this->dbTablePrefix . 'users_resets WHERE user = ? AND expires > ?',
[
$userId,
time()
\time()
]
);
@@ -1130,8 +1130,8 @@ final class Auth extends UserManager {
private function createPasswordResetRequest($userId, $expiresAfter, callable $callback) {
$selector = self::createRandomString(20);
$token = self::createRandomString(20);
$tokenHashed = password_hash($token, PASSWORD_DEFAULT);
$expiresAt = time() + $expiresAfter;
$tokenHashed = \password_hash($token, \PASSWORD_DEFAULT);
$expiresAt = \time() + $expiresAfter;
try {
$this->db->insert(
@@ -1148,7 +1148,7 @@ final class Auth extends UserManager {
throw new DatabaseError();
}
if (isset($callback) && is_callable($callback)) {
if (\is_callable($callback)) {
$callback($selector, $token);
}
else {
@@ -1188,8 +1188,8 @@ final class Auth extends UserManager {
if (!empty($resetData)) {
if ((int) $resetData['resettable'] === 1) {
if (password_verify($token, $resetData['token'])) {
if ($resetData['expires'] >= time()) {
if (\password_verify($token, $resetData['token'])) {
if ($resetData['expires'] >= \time()) {
$newPassword = self::validatePassword($newPassword);
// update the password in the database
@@ -1344,7 +1344,7 @@ final class Auth extends UserManager {
* @param int $userId the user's ID
*/
private function setUserId($userId) {
$_SESSION[self::SESSION_FIELD_USER_ID] = intval($userId);
$_SESSION[self::SESSION_FIELD_USER_ID] = (int) $userId;
}
/**
@@ -1736,7 +1736,7 @@ final class Auth extends UserManager {
*/
private function createCookieSettings() {
// get the default cookie settings
$params = session_get_cookie_params();
$params = \session_get_cookie_params();
// check if we want to send cookies via SSL/TLS only
$params['secure'] = $params['secure'] || $this->useHttps;
@@ -1756,14 +1756,14 @@ final class Auth extends UserManager {
* @author Jack @ Stack Overflow
*/
public static function createUuid() {
$data = openssl_random_pseudo_bytes(16);
$data = \openssl_random_pseudo_bytes(16);
// set the version to 0100
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
$data[6] = \chr(\ord($data[6]) & 0x0f | 0x40);
// set bits 6-7 to 10
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
$data[8] = \chr(\ord($data[8]) & 0x3f | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
return \vsprintf('%s%s-%s-%s-%s-%s%s%s', \str_split(\bin2hex($data), 4));
}
}

View File

@@ -40,10 +40,10 @@ abstract class UserManager {
*/
public static function createRandomString($maxLength = 24) {
// calculate how many bytes of randomness we need for the specified string length
$bytes = floor(intval($maxLength) / 4) * 3;
$bytes = \floor((int) $maxLength / 4) * 3;
// get random data
$data = openssl_random_pseudo_bytes($bytes);
$data = \openssl_random_pseudo_bytes($bytes);
// return the Base64-encoded result
return Base64::encodeUrlSafe($data);
@@ -103,12 +103,12 @@ abstract class UserManager {
* @see confirmEmailAndSignIn
*/
protected function createUserInternal($requireUniqueUsername, $email, $password, $username = null, callable $callback = null) {
ignore_user_abort(true);
\ignore_user_abort(true);
$email = self::validateEmailAddress($email);
$password = self::validatePassword($password);
$username = isset($username) ? trim($username) : null;
$username = isset($username) ? \trim($username) : null;
// if the supplied username is the empty string or has consisted of whitespace only
if ($username === '') {
@@ -134,8 +134,8 @@ abstract class UserManager {
}
}
$password = password_hash($password, PASSWORD_DEFAULT);
$verified = is_callable($callback) ? 0 : 1;
$password = \password_hash($password, \PASSWORD_DEFAULT);
$verified = \is_callable($callback) ? 0 : 1;
try {
$this->db->insert(
@@ -145,7 +145,7 @@ abstract class UserManager {
'password' => $password,
'username' => $username,
'verified' => $verified,
'registered' => time()
'registered' => \time()
]
);
}
@@ -180,7 +180,7 @@ abstract class UserManager {
*/
protected function getUserDataByUsername($username, array $requestedColumns) {
try {
$projection = implode(', ', $requestedColumns);
$projection = \implode(', ', $requestedColumns);
$users = $this->db->select(
'SELECT ' . $projection . ' FROM ' . $this->dbTablePrefix . 'users WHERE username = ? LIMIT 2 OFFSET 0',
@@ -195,7 +195,7 @@ abstract class UserManager {
throw new UnknownUsernameException();
}
else {
if (count($users) === 1) {
if (\count($users) === 1) {
return $users[0];
}
else {
@@ -216,9 +216,9 @@ abstract class UserManager {
throw new InvalidEmailException();
}
$email = trim($email);
$email = \trim($email);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (!\filter_var($email, \FILTER_VALIDATE_EMAIL)) {
throw new InvalidEmailException();
}
@@ -237,9 +237,9 @@ abstract class UserManager {
throw new InvalidPasswordException();
}
$password = trim($password);
$password = \trim($password);
if (strlen($password) < 1) {
if (\strlen($password) < 1) {
throw new InvalidPasswordException();
}
@@ -265,10 +265,10 @@ abstract class UserManager {
protected function createConfirmationRequest($userId, $email, callable $callback) {
$selector = self::createRandomString(16);
$token = self::createRandomString(16);
$tokenHashed = password_hash($token, PASSWORD_DEFAULT);
$tokenHashed = \password_hash($token, \PASSWORD_DEFAULT);
// the request shall be valid for one day
$expires = time() + self::CONFIRMATION_REQUESTS_TTL_IN_SECONDS;
$expires = \time() + self::CONFIRMATION_REQUESTS_TTL_IN_SECONDS;
try {
$this->db->insert(
@@ -286,7 +286,7 @@ abstract class UserManager {
throw new DatabaseError();
}
if (isset($callback) && is_callable($callback)) {
if (\is_callable($callback)) {
$callback($selector, $token);
}
else {

View File

@@ -15,33 +15,33 @@
*/
// enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 'stdout');
\error_reporting(\E_ALL);
\ini_set('display_errors', 'stdout');
// enable assertions
ini_set('assert.active', 1);
@ini_set('zend.assertions', 1);
ini_set('assert.exception', 1);
\ini_set('assert.active', 1);
@\ini_set('zend.assertions', 1);
\ini_set('assert.exception', 1);
header('Content-type: text/html; charset=utf-8');
\header('Content-type: text/html; charset=utf-8');
require __DIR__.'/../vendor/autoload.php';
$db = new PDO('mysql:dbname=php_auth;host=127.0.0.1;charset=utf8mb4', 'root', 'monkey');
$db = new \PDO('mysql:dbname=php_auth;host=127.0.0.1;charset=utf8mb4', 'root', 'monkey');
// or
// $db = new PDO('sqlite:../Databases/php_auth.sqlite');
// $db = new \PDO('sqlite:../Databases/php_auth.sqlite');
$auth = new \Delight\Auth\Auth($db);
$result = processRequestData($auth);
$result = \processRequestData($auth);
showDebugData($auth, $result);
\showDebugData($auth, $result);
if ($auth->check()) {
showAuthenticatedUserForm($auth);
\showAuthenticatedUserForm($auth);
}
else {
showGuestUserForm();
\showGuestUserForm();
}
function processRequestData(\Delight\Auth\Auth $auth) {
@@ -98,11 +98,11 @@ function processRequestData(\Delight\Auth\Auth $auth) {
echo "\n";
echo ' > Selector';
echo "\t\t\t\t";
echo htmlspecialchars($selector);
echo \htmlspecialchars($selector);
echo "\n";
echo ' > Token';
echo "\t\t\t\t";
echo htmlspecialchars($token);
echo \htmlspecialchars($token);
echo '</pre>';
};
}
@@ -177,11 +177,11 @@ function processRequestData(\Delight\Auth\Auth $auth) {
echo "\n";
echo ' > Selector';
echo "\t\t\t\t";
echo htmlspecialchars($selector);
echo \htmlspecialchars($selector);
echo "\n";
echo ' > Token';
echo "\t\t\t\t";
echo htmlspecialchars($token);
echo \htmlspecialchars($token);
echo '</pre>';
});
@@ -202,11 +202,11 @@ function processRequestData(\Delight\Auth\Auth $auth) {
echo "\n";
echo ' > Selector';
echo "\t\t\t\t";
echo htmlspecialchars($selector);
echo \htmlspecialchars($selector);
echo "\n";
echo ' > Token';
echo "\t\t\t\t";
echo htmlspecialchars($token);
echo \htmlspecialchars($token);
echo '</pre>';
});
@@ -227,11 +227,11 @@ function processRequestData(\Delight\Auth\Auth $auth) {
echo "\n";
echo ' > Selector';
echo "\t\t\t\t";
echo htmlspecialchars($selector);
echo \htmlspecialchars($selector);
echo "\n";
echo ' > Token';
echo "\t\t\t\t";
echo htmlspecialchars($token);
echo \htmlspecialchars($token);
echo '</pre>';
});
@@ -320,11 +320,11 @@ function processRequestData(\Delight\Auth\Auth $auth) {
echo "\n";
echo ' > Selector';
echo "\t\t\t\t";
echo htmlspecialchars($selector);
echo \htmlspecialchars($selector);
echo "\n";
echo ' > Token';
echo "\t\t\t\t";
echo htmlspecialchars($token);
echo \htmlspecialchars($token);
echo '</pre>';
});
@@ -523,7 +523,7 @@ function processRequestData(\Delight\Auth\Auth $auth) {
}
}
else {
throw new Exception('Unexpected action: '.$_POST['action']);
throw new Exception('Unexpected action: ' . $_POST['action']);
}
}
}
@@ -534,57 +534,57 @@ function processRequestData(\Delight\Auth\Auth $auth) {
function showDebugData(\Delight\Auth\Auth $auth, $result) {
echo '<pre>';
echo 'Last operation'."\t\t\t\t";
var_dump($result);
echo 'Session ID'."\t\t\t\t";
var_dump(session_id());
echo 'Last operation' . "\t\t\t\t";
\var_dump($result);
echo 'Session ID' . "\t\t\t\t";
\var_dump(\session_id());
echo "\n";
echo '$auth->isLoggedIn()'."\t\t\t";
var_dump($auth->isLoggedIn());
echo '$auth->check()'."\t\t\t\t";
var_dump($auth->check());
echo '$auth->isLoggedIn()' . "\t\t\t";
\var_dump($auth->isLoggedIn());
echo '$auth->check()' . "\t\t\t\t";
\var_dump($auth->check());
echo "\n";
echo '$auth->getUserId()'."\t\t\t";
var_dump($auth->getUserId());
echo '$auth->id()'."\t\t\t\t";
var_dump($auth->id());
echo '$auth->getUserId()' . "\t\t\t";
\var_dump($auth->getUserId());
echo '$auth->id()' . "\t\t\t\t";
\var_dump($auth->id());
echo "\n";
echo '$auth->getEmail()'."\t\t\t";
var_dump($auth->getEmail());
echo '$auth->getUsername()'."\t\t\t";
var_dump($auth->getUsername());
echo '$auth->getEmail()' . "\t\t\t";
\var_dump($auth->getEmail());
echo '$auth->getUsername()' . "\t\t\t";
\var_dump($auth->getUsername());
echo '$auth->getStatus()'."\t\t\t";
echo convertStatusToText($auth);
echo '$auth->getStatus()' . "\t\t\t";
echo \convertStatusToText($auth);
echo ' / ';
var_dump($auth->getStatus());
\var_dump($auth->getStatus());
echo "\n";
echo 'Roles (super moderator)'."\t\t\t";
var_dump($auth->hasRole(\Delight\Auth\Role::SUPER_MODERATOR));
echo 'Roles (super moderator)' . "\t\t\t";
\var_dump($auth->hasRole(\Delight\Auth\Role::SUPER_MODERATOR));
echo 'Roles (developer *or* manager)'."\t\t";
var_dump($auth->hasAnyRole(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER));
echo 'Roles (developer *or* manager)' . "\t\t";
\var_dump($auth->hasAnyRole(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER));
echo 'Roles (developer *and* manager)'."\t\t";
var_dump($auth->hasAllRoles(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER));
echo 'Roles (developer *and* manager)' . "\t\t";
\var_dump($auth->hasAllRoles(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER));
echo "\n";
echo '$auth->isRemembered()'."\t\t\t";
var_dump($auth->isRemembered());
echo '$auth->getIpAddress()'."\t\t\t";
var_dump($auth->getIpAddress());
echo '$auth->isRemembered()' . "\t\t\t";
\var_dump($auth->isRemembered());
echo '$auth->getIpAddress()' . "\t\t\t";
\var_dump($auth->getIpAddress());
echo "\n";
echo 'Auth::createRandomString()'."\t\t";
var_dump(\Delight\Auth\Auth::createRandomString());
echo 'Auth::createUuid()'."\t\t\t";
var_dump(\Delight\Auth\Auth::createUuid());
echo 'Auth::createRandomString()' . "\t\t";
\var_dump(\Delight\Auth\Auth::createRandomString());
echo 'Auth::createUuid()' . "\t\t\t";
\var_dump(\Delight\Auth\Auth::createUuid());
echo '</pre>';
}
@@ -626,7 +626,7 @@ function showGeneralForm() {
}
function showAuthenticatedUserForm(\Delight\Auth\Auth $auth) {
showGeneralForm();
\showGeneralForm();
echo '<form action="" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="action" value="reconfirmPassword" />';
@@ -653,7 +653,7 @@ function showAuthenticatedUserForm(\Delight\Auth\Auth $auth) {
echo '<button type="submit">Change email address</button>';
echo '</form>';
showConfirmEmailForm();
\showConfirmEmailForm();
echo '<form action="" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="action" value="setPasswordResetEnabled" />';
@@ -676,7 +676,7 @@ function showAuthenticatedUserForm(\Delight\Auth\Auth $auth) {
}
function showGuestUserForm() {
showGeneralForm();
\showGeneralForm();
echo '<h1>Public</h1>';
@@ -718,7 +718,7 @@ function showGuestUserForm() {
echo '<button type="submit">Register</button>';
echo '</form>';
showConfirmEmailForm();
\showConfirmEmailForm();
echo '<form action="" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="action" value="forgotPassword" />';
@@ -769,49 +769,49 @@ function showGuestUserForm() {
echo '<form action="" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="action" value="admin.addRole" />';
echo '<input type="text" name="id" placeholder="ID" /> ';
echo '<select name="role">' . createRolesOptions() . '</select>';
echo '<select name="role">' . \createRolesOptions() . '</select>';
echo '<button type="submit">Add role for user by ID</button>';
echo '</form>';
echo '<form action="" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="action" value="admin.addRole" />';
echo '<input type="text" name="email" placeholder="Email" /> ';
echo '<select name="role">' . createRolesOptions() . '</select>';
echo '<select name="role">' . \createRolesOptions() . '</select>';
echo '<button type="submit">Add role for user by email</button>';
echo '</form>';
echo '<form action="" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="action" value="admin.addRole" />';
echo '<input type="text" name="username" placeholder="Username" /> ';
echo '<select name="role">' . createRolesOptions() . '</select>';
echo '<select name="role">' . \createRolesOptions() . '</select>';
echo '<button type="submit">Add role for user by username</button>';
echo '</form>';
echo '<form action="" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="action" value="admin.removeRole" />';
echo '<input type="text" name="id" placeholder="ID" /> ';
echo '<select name="role">' . createRolesOptions() . '</select>';
echo '<select name="role">' . \createRolesOptions() . '</select>';
echo '<button type="submit">Remove role for user by ID</button>';
echo '</form>';
echo '<form action="" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="action" value="admin.removeRole" />';
echo '<input type="text" name="email" placeholder="Email" /> ';
echo '<select name="role">' . createRolesOptions() . '</select>';
echo '<select name="role">' . \createRolesOptions() . '</select>';
echo '<button type="submit">Remove role for user by email</button>';
echo '</form>';
echo '<form action="" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="action" value="admin.removeRole" />';
echo '<input type="text" name="username" placeholder="Username" /> ';
echo '<select name="role">' . createRolesOptions() . '</select>';
echo '<select name="role">' . \createRolesOptions() . '</select>';
echo '<button type="submit">Remove role for user by username</button>';
echo '</form>';
echo '<form action="" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="action" value="admin.hasRole" />';
echo '<input type="text" name="id" placeholder="ID" /> ';
echo '<select name="role">' . createRolesOptions() . '</select>';
echo '<select name="role">' . \createRolesOptions() . '</select>';
echo '<button type="submit">Does user have role?</button>';
echo '</form>';
}