Giter Club home page Giter Club logo

php-auth's Introduction

Auth

Authentication for PHP. Simple, lightweight and secure.

Written once, to be used everywhere.

Completely framework-agnostic and database-agnostic.

Why do I need this?

  • There are tons of websites with weak authentication systems. Don’t build such a site.
  • Re-implementing a new authentication system for every PHP project is not a good idea.
  • Building your own authentication classes piece by piece, and copying it to every project, is not recommended, either.
  • A secure authentication system with an easy-to-use API should be thoroughly designed and planned.
  • Peer-review for your critical infrastructure is a must.

Requirements

  • PHP 5.6.0+
    • PDO (PHP Data Objects) extension (pdo)
      • MySQL Native Driver (mysqlnd) or PostgreSQL driver (pgsql) or SQLite driver (sqlite)
    • OpenSSL extension (openssl)
  • MySQL 5.5.3+ or MariaDB 5.5.23+ or PostgreSQL 9.5.10+ or SQLite 3.14.1+ or other SQL databases

Installation

  1. Include the library via Composer [?]:

    $ composer require delight-im/auth
    
  2. Include the Composer autoloader:

    require __DIR__ . '/vendor/autoload.php';
  3. Set up a database and create the required tables:

Upgrading

Migrating from an earlier version of this project? See our upgrade guide for help.

Usage

Creating a new instance

// $db = new \PDO('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
// or
// $db = new \PDO('pgsql:dbname=my-database;host=localhost;port=5432', 'my-username', 'my-password');
// or
// $db = new \PDO('sqlite:../Databases/my-database.sqlite');

// or

// $db = \Delight\Db\PdoDatabase::fromDsn(new \Delight\Db\PdoDsn('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password'));
// or
// $db = \Delight\Db\PdoDatabase::fromDsn(new \Delight\Db\PdoDsn('pgsql:dbname=my-database;host=localhost;port=5432', 'my-username', 'my-password'));
// or
// $db = \Delight\Db\PdoDatabase::fromDsn(new \Delight\Db\PdoDsn('sqlite:../Databases/my-database.sqlite'));

$auth = new \Delight\Auth\Auth($db);

If you have an open PDO connection already, just re-use it. The database user (e.g. my-username) needs at least the privileges SELECT, INSERT, UPDATE and DELETE for the tables used by this library (or their parent database).

If your web server is behind a proxy server and $_SERVER['REMOTE_ADDR'] only contains the proxy’s IP address, you must pass the user’s real IP address to the constructor in the second argument, which is named $ipAddress. The default is the usual remote IP address received by PHP.

Should your database tables for this library need a common prefix, e.g. my_users instead of users (and likewise for the other tables), pass the prefix (e.g. my_) as the third parameter to the constructor, which is named $dbTablePrefix. This is optional and the prefix is empty by default.

During development, you may want to disable the request limiting or throttling performed by this library. To do so, pass false to the constructor as the fourth argument, which is named $throttling. The feature is enabled by default.

During the lifetime of a session, some user data may be changed remotely, either by a client in another session or by an administrator. That means this information must be regularly resynchronized with its authoritative source in the database, which this library does automatically. By default, this happens every five minutes. If you want to change this interval, pass a custom interval in seconds to the constructor as the fifth argument, which is named $sessionResyncInterval.

If all your database tables need a common database name, schema name, or other qualifier that must be specified explicitly, you can optionally pass that qualifier to the constructor as the sixth parameter, which is named $dbSchema.

If you want to use a PdoDatabase instance (e.g. $db) independently as well, please refer to the documentation of the database library.

Registration (sign up)

try {
    $userId = $auth->register($_POST['email'], $_POST['password'], $_POST['username'], function ($selector, $token) {
        echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)';
        echo '  For emails, consider using the mail(...) function, Symfony Mailer, Swiftmailer, PHPMailer, etc.';
        echo '  For SMS, consider using a third-party service and a compatible SDK';
    });

    echo 'We have signed up a new user with the ID ' . $userId;
}
catch (\Delight\Auth\InvalidEmailException $e) {
    die('Invalid email address');
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    die('Invalid password');
}
catch (\Delight\Auth\UserAlreadyExistsException $e) {
    die('User already exists');
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    die('Too many requests');
}

Note: The anonymous callback function is a closure. Thus, besides its own parameters, only superglobals like $_GET, $_POST, $_COOKIE and $_SERVER are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a use clause after the parameter list.

The username in the third parameter is optional. You can pass null there if you don’t want to manage usernames.

If you want to enforce unique usernames, on the other hand, simply call registerWithUniqueUsername instead of register, and be prepared to catch the DuplicateUsernameException.

Note: When accepting and managing usernames, you may want to exclude non-printing control characters and certain printable special characters, as in the character class [\x00-\x1f\x7f\/:\\]. In order to do so, you could wrap the call to Auth#register or Auth#registerWithUniqueUsername inside a conditional branch, for example by only accepting usernames when the following condition is satisfied:

if (\preg_match('/[\x00-\x1f\x7f\/:\\\\]/', $username) === 0) {
    // ...
}

For email verification, you should build an URL with the selector and token and send it to the user, e.g.:

$url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector) . '&token=' . \urlencode($token);

If you don’t want to perform email verification, just omit the last parameter to Auth#register, i.e. the anonymous function or closure. The new user will be active immediately, then.

Need to store additional user information? Read on here.

Note: When sending an email to the user, please note that the (optional) username, at this point, has not yet been confirmed as acceptable to the owner of the (new) email address. It could contain offensive or misleading language chosen by someone who is not actually the owner of the address.

Login (sign in)

try {
    $auth->login($_POST['email'], $_POST['password']);

    echo 'User is logged in';
}
catch (\Delight\Auth\InvalidEmailException $e) {
    die('Wrong email address');
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    die('Wrong password');
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
    die('Email not verified');
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    die('Too many requests');
}

If you want to sign in with usernames on the other hand, either in addition to the login via email address or as a replacement, that’s possible as well. Simply call the method loginWithUsername instead of method login. Then, instead of catching InvalidEmailException, make sure to catch both UnknownUsernameException and AmbiguousUsernameException. You may also want to read the notes about the uniqueness of usernames in the section that explains how to sign up new users.

Email verification

Extract the selector and token from the URL that the user clicked on in the verification email.

try {
    $auth->confirmEmail($_GET['selector'], $_GET['token']);

    echo 'Email address has been verified';
}
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
    die('Invalid token');
}
catch (\Delight\Auth\TokenExpiredException $e) {
    die('Token expired');
}
catch (\Delight\Auth\UserAlreadyExistsException $e) {
    die('Email address already exists');
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    die('Too many requests');
}

If you want the user to be automatically signed in after successful confirmation, just call confirmEmailAndSignIn instead of confirmEmail. That alternative method also supports persistent logins via its optional third parameter.

On success, the two methods confirmEmail and confirmEmailAndSignIn both return an array with the user’s new email address, which has just been verified, at index one. If the confirmation was for an address change instead of a simple address verification, the user’s old email address will be included in the array at index zero.

Keeping the user logged in

The third parameter to the Auth#login and Auth#confirmEmailAndSignIn methods controls whether the login is persistent with a long-lived cookie. With such a persistent login, users may stay authenticated for a long time, even when the browser session has already been closed and the session cookies have expired. Typically, you’ll want to keep the user logged in for weeks or months with this feature, which is known as “remember me” or “keep me logged in”. Many users will find this more convenient, but it may be less secure if they leave their devices unattended.

if ($_POST['remember'] == 1) {
    // keep logged in for one year
    $rememberDuration = (int) (60 * 60 * 24 * 365.25);
}
else {
    // do not keep logged in after session ends
    $rememberDuration = null;
}

// ...

$auth->login($_POST['email'], $_POST['password'], $rememberDuration);

// ...

Without the persistent login, which is the default behavior, a user will only stay logged in until they close their browser, or as long as configured via session.cookie_lifetime and session.gc_maxlifetime in PHP.

Omit the third parameter or set it to null to disable the feature. Otherwise, you may ask the user whether they want to enable “remember me”. This is usually done with a checkbox in your user interface. Use the input from that checkbox to decide between null and a pre-defined duration in seconds here, e.g. 60 * 60 * 24 * 365.25 for one year.

Password reset (“forgot password”)

Step 1 of 3: Initiating the request

try {
    $auth->forgotPassword($_POST['email'], function ($selector, $token) {
        echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)';
        echo '  For emails, consider using the mail(...) function, Symfony Mailer, Swiftmailer, PHPMailer, etc.';
        echo '  For SMS, consider using a third-party service and a compatible SDK';
    });

    echo 'Request has been generated';
}
catch (\Delight\Auth\InvalidEmailException $e) {
    die('Invalid email address');
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
    die('Email not verified');
}
catch (\Delight\Auth\ResetDisabledException $e) {
    die('Password reset is disabled');
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    die('Too many requests');
}

Note: The anonymous callback function is a closure. Thus, besides its own parameters, only superglobals like $_GET, $_POST, $_COOKIE and $_SERVER are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a use clause after the parameter list.

You should build an URL with the selector and token and send it to the user, e.g.:

$url = 'https://www.example.com/reset_password?selector=' . \urlencode($selector) . '&token=' . \urlencode($token);

If the default lifetime of the password reset requests does not work for you, you can use the third parameter of Auth#forgotPassword to specify a custom interval in seconds after which the requests should expire.

Step 2 of 3: Verifying an attempt

As the next step, users will click on the link that they received. Extract the selector and token from the URL.

If the selector/token pair is valid, let the user choose a new password:

try {
    $auth->canResetPasswordOrThrow($_GET['selector'], $_GET['token']);

    echo 'Put the selector into a "hidden" field (or keep it in the URL)';
    echo 'Put the token into a "hidden" field (or keep it in the URL)';

    echo 'Ask the user for their new password';
}
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
    die('Invalid token');
}
catch (\Delight\Auth\TokenExpiredException $e) {
    die('Token expired');
}
catch (\Delight\Auth\ResetDisabledException $e) {
    die('Password reset is disabled');
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    die('Too many requests');
}

Alternatively, if you don’t need any error messages but only want to check the validity, you can use the slightly simpler version:

if ($auth->canResetPassword($_GET['selector'], $_GET['token'])) {
    echo 'Put the selector into a "hidden" field (or keep it in the URL)';
    echo 'Put the token into a "hidden" field (or keep it in the URL)';

    echo 'Ask the user for their new password';
}

Step 3 of 3: Updating the password

Now when you have the new password for the user (and still have the other two pieces of information), you can reset the password:

try {
    $auth->resetPassword($_POST['selector'], $_POST['token'], $_POST['password']);

    echo 'Password has been reset';
}
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
    die('Invalid token');
}
catch (\Delight\Auth\TokenExpiredException $e) {
    die('Token expired');
}
catch (\Delight\Auth\ResetDisabledException $e) {
    die('Password reset is disabled');
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    die('Invalid password');
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    die('Too many requests');
}

Do you want to have the respective user signed in automatically when their password reset succeeds? Simply use Auth#resetPasswordAndSignIn instead of Auth#resetPassword to log in the user immediately.

If you need the user’s ID or email address, e.g. for sending them a notification that their password has successfully been reset, just use the return value of Auth#resetPassword, which is an array containing two entries named id and email.

Changing the current user’s password

If a user is currently logged in, they may change their password.

try {
    $auth->changePassword($_POST['oldPassword'], $_POST['newPassword']);

    echo 'Password has been changed';
}
catch (\Delight\Auth\NotLoggedInException $e) {
    die('Not logged in');
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    die('Invalid password(s)');
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    die('Too many requests');
}

Asking the user for their current (and soon old) password and requiring it for verification is the recommended way to handle password changes. This is shown above.

If you’re sure that you don’t need that confirmation, however, you may call changePasswordWithoutOldPassword instead of changePassword and drop the first parameter from that method call (which would otherwise contain the old password).

In any case, after the user’s password has been changed, you should send an email to their account’s primary email address as an out-of-band notification informing the account owner about this critical change.

Changing the current user’s email address

If a user is currently logged in, they may change their email address.

try {
    if ($auth->reconfirmPassword($_POST['password'])) {
        $auth->changeEmail($_POST['newEmail'], function ($selector, $token) {
            echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email to the *new* address)';
            echo '  For emails, consider using the mail(...) function, Symfony Mailer, Swiftmailer, PHPMailer, etc.';
            echo '  For SMS, consider using a third-party service and a compatible SDK';
        });

        echo 'The change will take effect as soon as the new email address has been confirmed';
    }
    else {
        echo 'We can\'t say if the user is who they claim to be';
    }
}
catch (\Delight\Auth\InvalidEmailException $e) {
    die('Invalid email address');
}
catch (\Delight\Auth\UserAlreadyExistsException $e) {
    die('Email address already exists');
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
    die('Account not verified');
}
catch (\Delight\Auth\NotLoggedInException $e) {
    die('Not logged in');
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    die('Too many requests');
}

Note: The anonymous callback function is a closure. Thus, besides its own parameters, only superglobals like $_GET, $_POST, $_COOKIE and $_SERVER are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a use clause after the parameter list.

For email verification, you should build an URL with the selector and token and send it to the user, e.g.:

$url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector) . '&token=' . \urlencode($token);

Note: When sending an email to the user, please note that the (optional) username, at this point, has not yet been confirmed as acceptable to the owner of the (new) email address. It could contain offensive or misleading language chosen by someone who is not actually the owner of the address.

After the request to change the email address has been made, or even better, after the change has been confirmed by the user, you should send an email to their account’s previous email address as an out-of-band notification informing the account owner about this critical change.

Note: Changes to a user’s email address take effect in the local session immediately, as expected. In other sessions (e.g. on other devices), the changes may need up to five minutes to take effect, though. This increases performance and usually poses no problem. If you want to change this behavior, nevertheless, simply decrease (or perhaps increase) the value that you pass to the Auth constructor as the argument named $sessionResyncInterval.

Re-sending confirmation requests

If an earlier confirmation request could not be delivered to the user, or if the user missed that request, or if they just don’t want to wait any longer, you may re-send an earlier request like this:

try {
    $auth->resendConfirmationForEmail($_POST['email'], function ($selector, $token) {
        echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)';
        echo '  For emails, consider using the mail(...) function, Symfony Mailer, Swiftmailer, PHPMailer, etc.';
        echo '  For SMS, consider using a third-party service and a compatible SDK';
    });

    echo 'The user may now respond to the confirmation request (usually by clicking a link)';
}
catch (\Delight\Auth\ConfirmationRequestNotFound $e) {
    die('No earlier request found that could be re-sent');
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    die('There have been too many requests -- try again later');
}

If you want to specify the user by their ID instead of by their email address, this is possible as well:

try {
    $auth->resendConfirmationForUserId($_POST['userId'], function ($selector, $token) {
        echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)';
        echo '  For emails, consider using the mail(...) function, Symfony Mailer, Swiftmailer, PHPMailer, etc.';
        echo '  For SMS, consider using a third-party service and a compatible SDK';
    });

    echo 'The user may now respond to the confirmation request (usually by clicking a link)';
}
catch (\Delight\Auth\ConfirmationRequestNotFound $e) {
    die('No earlier request found that could be re-sent');
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    die('There have been too many requests -- try again later');
}

Note: The anonymous callback function is a closure. Thus, besides its own parameters, only superglobals like $_GET, $_POST, $_COOKIE and $_SERVER are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a use clause after the parameter list.

Usually, you should build an URL with the selector and token and send it to the user, e.g. as follows:

$url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector) . '&token=' . \urlencode($token);

Note: When sending an email to the user, please note that the (optional) username, at this point, has not yet been confirmed as acceptable to the owner of the (new) email address. It could contain offensive or misleading language chosen by someone who is not actually the owner of the address.

Logout

$auth->logOut();

// or

try {
    $auth->logOutEverywhereElse();
}
catch (\Delight\Auth\NotLoggedInException $e) {
    die('Not logged in');
}

// or

try {
    $auth->logOutEverywhere();
}
catch (\Delight\Auth\NotLoggedInException $e) {
    die('Not logged in');
}

Additionally, if you store custom information in the session as well, and if you want that information to be deleted, you can destroy the entire session by calling a second method:

$auth->destroySession();

Note: Global logouts take effect in the local session immediately, as expected. In other sessions (e.g. on other devices), the changes may need up to five minutes to take effect, though. This increases performance and usually poses no problem. If you want to change this behavior, nevertheless, simply decrease (or perhaps increase) the value that you pass to the Auth constructor as the argument named $sessionResyncInterval.

Accessing user information

Login state

if ($auth->isLoggedIn()) {
    echo 'User is signed in';
}
else {
    echo 'User is not signed in yet';
}

A shorthand/alias for this method is $auth->check().

User ID

$id = $auth->getUserId();

If the user is not currently signed in, this returns null.

A shorthand/alias for this method is $auth->id().

Email address

$email = $auth->getEmail();

If the user is not currently signed in, this returns null.

Display name

$username = $auth->getUsername();

Remember that usernames are optional and there is only a username if you supplied it during registration.

If the user is not currently signed in, this returns null.

Status information

if ($auth->isNormal()) {
    echo 'User is in default state';
}

if ($auth->isArchived()) {
    echo 'User has been archived';
}

if ($auth->isBanned()) {
    echo 'User has been banned';
}

if ($auth->isLocked()) {
    echo 'User has been locked';
}

if ($auth->isPendingReview()) {
    echo 'User is pending review';
}

if ($auth->isSuspended()) {
    echo 'User has been suspended';
}

Checking whether the user was “remembered”

if ($auth->isRemembered()) {
    echo 'User did not sign in but was logged in through their long-lived cookie';
}
else {
    echo 'User signed in manually';
}

If the user is not currently signed in, this returns null.

IP address

$ip = $auth->getIpAddress();

Additional user information

In order to preserve this library’s suitability for all purposes as well as its full re-usability, it doesn’t come with additional bundled columns for user information. But you don’t have to do without additional user information, of course:

Here’s how to use this library with your own tables for custom user information in a maintainable and re-usable way:

  1. Add any number of custom database tables where you store custom user information, e.g. a table named profiles.

  2. Whenever you call the register method (which returns the new user’s ID), add your own logic afterwards that fills your custom database tables.

  3. If you need the custom user information only rarely, you may just retrieve it as needed. If you need it more frequently, however, you’d probably want to have it in your session data. The following method is how you can load and access your data in a reliable way:

    function getUserInfo(\Delight\Auth\Auth $auth) {
        if (!$auth->isLoggedIn()) {
            return null;
        }
    
        if (!isset($_SESSION['_internal_user_info'])) {
            // TODO: load your custom user information and assign it to the session variable below
            // $_SESSION['_internal_user_info'] = ...
        }
    
        return $_SESSION['_internal_user_info'];
    }

Reconfirming the user’s password

Whenever you want to confirm the user’s identity again, e.g. before the user is allowed to perform some “dangerous” action, you should verify their password again to confirm that they actually are who they claim to be.

For example, when a user has been remembered by a long-lived cookie and thus Auth#isRemembered returns true, this means that the user probably has not entered their password for quite some time anymore. You may want to reconfirm their password in that case.

try {
    if ($auth->reconfirmPassword($_POST['password'])) {
        echo 'The user really seems to be who they claim to be';
    }
    else {
        echo 'We can\'t say if the user is who they claim to be';
    }
}
catch (\Delight\Auth\NotLoggedInException $e) {
    die('The user is not signed in');
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    die('Too many requests');
}

Roles (or groups)

Every user can have any number of roles, which you can use to implement authorization and to refine your access controls.

Users may have no role at all (which they do by default), exactly one role, or any arbitrary combination of roles.

Checking roles

if ($auth->hasRole(\Delight\Auth\Role::SUPER_MODERATOR)) {
    echo 'The user is a super moderator';
}

// or

if ($auth->hasAnyRole(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER)) {
    echo 'The user is either a developer, or a manager, or both';
}

// or

if ($auth->hasAllRoles(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER)) {
    echo 'The user is both a developer and a manager';
}

While the method hasRole takes exactly one role as its argument, the two methods hasAnyRole and hasAllRoles can take any number of roles that you would like to check for.

Alternatively, you can get a list of all the roles that have been assigned to the user:

$auth->getRoles();

Available roles

\Delight\Auth\Role::ADMIN;
\Delight\Auth\Role::AUTHOR;
\Delight\Auth\Role::COLLABORATOR;
\Delight\Auth\Role::CONSULTANT;
\Delight\Auth\Role::CONSUMER;
\Delight\Auth\Role::CONTRIBUTOR;
\Delight\Auth\Role::COORDINATOR;
\Delight\Auth\Role::CREATOR;
\Delight\Auth\Role::DEVELOPER;
\Delight\Auth\Role::DIRECTOR;
\Delight\Auth\Role::EDITOR;
\Delight\Auth\Role::EMPLOYEE;
\Delight\Auth\Role::MAINTAINER;
\Delight\Auth\Role::MANAGER;
\Delight\Auth\Role::MODERATOR;
\Delight\Auth\Role::PUBLISHER;
\Delight\Auth\Role::REVIEWER;
\Delight\Auth\Role::SUBSCRIBER;
\Delight\Auth\Role::SUPER_ADMIN;
\Delight\Auth\Role::SUPER_EDITOR;
\Delight\Auth\Role::SUPER_MODERATOR;
\Delight\Auth\Role::TRANSLATOR;

You can use any of these roles and ignore those that you don’t need. The list above can also be retrieved programmatically, in one of three formats:

\Delight\Auth\Role::getMap();
// or
\Delight\Auth\Role::getNames();
// or
\Delight\Auth\Role::getValues();

Permissions (or access rights, privileges or capabilities)

The permissions of each user are encoded in the way that role requirements are specified throughout your code base. If those requirements are evaluated with a specific user’s set of roles, implicitly checked permissions are the result.

For larger projects, it is often recommended to maintain the definition of permissions in a single place. You then don’t check for roles in your business logic, but you check for individual permissions. You could implement that concept as follows:

function canEditArticle(\Delight\Auth\Auth $auth) {
    return $auth->hasAnyRole(
        \Delight\Auth\Role::MODERATOR,
        \Delight\Auth\Role::SUPER_MODERATOR,
        \Delight\Auth\Role::ADMIN,
        \Delight\Auth\Role::SUPER_ADMIN
    );
}

// ...

if (canEditArticle($auth)) {
    echo 'The user can edit articles here';
}

// ...

if (canEditArticle($auth)) {
    echo '... and here';
}

// ...

if (canEditArticle($auth)) {
    echo '... and here';
}

As you can see, the permission of whether a certain user can edit an article is stored at a central location. This implementation has two major advantages:

If you want to know which users can edit articles, you don’t have to check your business logic in various places, but you only have to look where the specific permission is defined. And if you want to change who can edit an article, you only have to do this in one single place as well, not throughout your whole code base.

But this also comes with slightly more overhead when implementing the access restrictions for the first time, which may or may not be worth it for your project.

Custom role names

If the names of the included roles don’t work for you, you can alias any number of roles using your own identifiers, e.g. like this:

namespace My\Namespace;

final class MyRole {

    const CUSTOMER_SERVICE_AGENT = \Delight\Auth\Role::REVIEWER;
    const FINANCIAL_DIRECTOR = \Delight\Auth\Role::COORDINATOR;

    private function __construct() {}

}

The example above would allow you to use

\My\Namespace\MyRole::CUSTOMER_SERVICE_AGENT;
// and
\My\Namespace\MyRole::FINANCIAL_DIRECTOR;

instead of

\Delight\Auth\Role::REVIEWER;
// and
\Delight\Auth\Role::COORDINATOR;

Just remember not to alias a single included role to multiple roles with custom names.

Enabling or disabling password resets

While password resets via email are a convenient feature that most users find helpful from time to time, the availability of this feature implies that accounts on your service are only ever as secure as the user’s associated email account.

You may provide security-conscious (and experienced) users with the possibility to disable password resets for their accounts (and to enable them again later) for enhanced security:

try {
    if ($auth->reconfirmPassword($_POST['password'])) {
        $auth->setPasswordResetEnabled($_POST['enabled'] == 1);

        echo 'The setting has been changed';
    }
    else {
        echo 'We can\'t say if the user is who they claim to be';
    }
}
catch (\Delight\Auth\NotLoggedInException $e) {
    die('The user is not signed in');
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    die('Too many requests');
}

In order to check the current value of this setting, use the return value from

$auth->isPasswordResetEnabled();

for the correct default option in your user interface. You don’t need to check this value for restrictions of the feature, which are enforced automatically.

Throttling or rate limiting

All methods provided by this library are automatically protected against excessive numbers of requests from clients. If the need arises, you can (temporarily) disable this protection using the $throttling parameter passed to the constructor.

If you would like to throttle or rate limit external features or methods as well, e.g. those in your own code, you can make use of the built-in helper method for throttling and rate limiting:

try {
    // throttle the specified resource or feature to *3* requests per *60* seconds
    $auth->throttle([ 'my-resource-name' ], 3, 60);

    echo 'Do something with the resource or feature';
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    // operation cancelled

    \http_response_code(429);
    exit;
}

If the protection of the resource or feature should additionally depend on another attribute, e.g. to track something separately per IP address, just add more data to the resource description, such as:

[ 'my-resource-name', $_SERVER['REMOTE_ADDR'] ]
// instead of
// [ 'my-resource-name' ]

Allowing short bursts of activity during peak demand is possible by specifying a burst factor as the fourth argument. A value of 5, for example, would permit temporary bursts of fivefold activity, compared to the generally accepted level.

In some cases, you may just want to simulate the throttling or rate limiting. This lets you check whether an action would be permitted without actually modifying the activity tracker. To do so, simply pass true as the fifth argument.

Note: When you disable throttling on the instance (using the $throttling parameter passed to the constructor), this turns off both the automatic internal protection and the effect of any calls to Auth#throttle in your own application code – unless you also set the optional $force parameter to true in specific Auth#throttle calls.

Administration (managing users)

The administrative interface is available via $auth->admin(). You can call various method on this interface, as documented below.

Do not forget to implement secure access control before exposing access to this interface. For example, you may provide access to this interface to logged in users with the administrator role only, or use the interface in private scripts only.

Creating new users

try {
    $userId = $auth->admin()->createUser($_POST['email'], $_POST['password'], $_POST['username']);

    echo 'We have signed up a new user with the ID ' . $userId;
}
catch (\Delight\Auth\InvalidEmailException $e) {
    die('Invalid email address');
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    die('Invalid password');
}
catch (\Delight\Auth\UserAlreadyExistsException $e) {
    die('User already exists');
}

The username in the third parameter is optional. You can pass null there if you don’t want to manage usernames.

If you want to enforce unique usernames, on the other hand, simply call createUserWithUniqueUsername instead of createUser, and be prepared to catch the DuplicateUsernameException.

Deleting users

Deleting users by their ID:

try {
    $auth->admin()->deleteUserById($_POST['id']);
}
catch (\Delight\Auth\UnknownIdException $e) {
    die('Unknown ID');
}

Deleting users by their email address:

try {
    $auth->admin()->deleteUserByEmail($_POST['email']);
}
catch (\Delight\Auth\InvalidEmailException $e) {
    die('Unknown email address');
}

Deleting users by their username:

try {
    $auth->admin()->deleteUserByUsername($_POST['username']);
}
catch (\Delight\Auth\UnknownUsernameException $e) {
    die('Unknown username');
}
catch (\Delight\Auth\AmbiguousUsernameException $e) {
    die('Ambiguous username');
}

Retrieving a list of registered users

When fetching a list of all users, the requirements vary greatly between projects and use cases, and customization is common. For example, you might want to fetch different columns, join related tables, filter by certain criteria, change how results are sorted (in varying direction), and limit the number of results (while providing an offset).

That’s why it’s easier to use a single custom SQL query. Start with the following:

SELECT id, email, username, status, verified, roles_mask, registered, last_login FROM users;

Assigning roles to users

try {
    $auth->admin()->addRoleForUserById($userId, \Delight\Auth\Role::ADMIN);
}
catch (\Delight\Auth\UnknownIdException $e) {
    die('Unknown user ID');
}

// or

try {
    $auth->admin()->addRoleForUserByEmail($userEmail, \Delight\Auth\Role::ADMIN);
}
catch (\Delight\Auth\InvalidEmailException $e) {
    die('Unknown email address');
}

// or

try {
    $auth->admin()->addRoleForUserByUsername($username, \Delight\Auth\Role::ADMIN);
}
catch (\Delight\Auth\UnknownUsernameException $e) {
    die('Unknown username');
}
catch (\Delight\Auth\AmbiguousUsernameException $e) {
    die('Ambiguous username');
}

Note: Changes to a user’s set of roles may need up to five minutes to take effect. This increases performance and usually poses no problem. If you want to change this behavior, nevertheless, simply decrease (or perhaps increase) the value that you pass to the Auth constructor as the argument named $sessionResyncInterval.

Taking roles away from users

try {
    $auth->admin()->removeRoleForUserById($userId, \Delight\Auth\Role::ADMIN);
}
catch (\Delight\Auth\UnknownIdException $e) {
    die('Unknown user ID');
}

// or

try {
    $auth->admin()->removeRoleForUserByEmail($userEmail, \Delight\Auth\Role::ADMIN);
}
catch (\Delight\Auth\InvalidEmailException $e) {
    die('Unknown email address');
}

// or

try {
    $auth->admin()->removeRoleForUserByUsername($username, \Delight\Auth\Role::ADMIN);
}
catch (\Delight\Auth\UnknownUsernameException $e) {
    die('Unknown username');
}
catch (\Delight\Auth\AmbiguousUsernameException $e) {
    die('Ambiguous username');
}

Note: Changes to a user’s set of roles may need up to five minutes to take effect. This increases performance and usually poses no problem. If you want to change this behavior, nevertheless, simply decrease (or perhaps increase) the value that you pass to the Auth constructor as the argument named $sessionResyncInterval.

Checking roles

try {
    if ($auth->admin()->doesUserHaveRole($userId, \Delight\Auth\Role::ADMIN)) {
        echo 'The specified user is an administrator';
    }
    else {
        echo 'The specified user is not an administrator';
    }
}
catch (\Delight\Auth\UnknownIdException $e) {
    die('Unknown user ID');
}

Alternatively, you can get a list of all the roles that have been assigned to the user:

$auth->admin()->getRolesForUserById($userId);

Impersonating users (logging in as user)

try {
    $auth->admin()->logInAsUserById($_POST['id']);
}
catch (\Delight\Auth\UnknownIdException $e) {
    die('Unknown ID');
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
    die('Email address not verified');
}

// or

try {
    $auth->admin()->logInAsUserByEmail($_POST['email']);
}
catch (\Delight\Auth\InvalidEmailException $e) {
    die('Unknown email address');
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
    die('Email address not verified');
}

// or

try {
    $auth->admin()->logInAsUserByUsername($_POST['username']);
}
catch (\Delight\Auth\UnknownUsernameException $e) {
    die('Unknown username');
}
catch (\Delight\Auth\AmbiguousUsernameException $e) {
    die('Ambiguous username');
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
    die('Email address not verified');
}

Changing a user’s password

try {
    $auth->admin()->changePasswordForUserById($_POST['id'], $_POST['newPassword']);
}
catch (\Delight\Auth\UnknownIdException $e) {
    die('Unknown ID');
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    die('Invalid password');
}

// or

try {
    $auth->admin()->changePasswordForUserByUsername($_POST['username'], $_POST['newPassword']);
}
catch (\Delight\Auth\UnknownUsernameException $e) {
    die('Unknown username');
}
catch (\Delight\Auth\AmbiguousUsernameException $e) {
    die('Ambiguous username');
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    die('Invalid password');
}

Cookies

This library uses two cookies to keep state on the client: The first, whose name you can retrieve using

\session_name();

is the general (mandatory) session cookie. The second (optional) cookie is only used for persistent logins and its name can be retrieved as follows:

\Delight\Auth\Auth::createRememberCookieName();

Renaming the library’s cookies

You can rename the session cookie used by this library through one of the following means, in order of recommendation:

  • In the PHP configuration (php.ini), find the line with the session.name directive and change its value to something like session_v1, as in:

    session.name = session_v1
    
  • As early as possible in your application, and before you create the Auth instance, call \ini_set to change session.name to something like session_v1, as in:

    \ini_set('session.name', 'session_v1');

    For this to work, session.auto_start must be set to 0 in the PHP configuration (php.ini).

  • As early as possible in your application, and before you create the Auth instance, call \session_name with an argument like session_v1, as in:

    \session_name('session_v1');

    For this to work, session.auto_start must be set to 0 in the PHP configuration (php.ini).

The name of the cookie for persistent logins will change as well – automatically – following your change of the session cookie’s name.

Defining the domain scope for cookies

A cookie’s domain attribute controls which domain (and which subdomains) the cookie will be valid for, and thus where the user’s session and authentication state will be available.

The recommended default is an empty string, which means that the cookie will only be valid for the exact current host, excluding any subdomains that may exist. You should only use a different value if you need to share cookies between different subdomains. Often, you’ll want to share cookies between the bare domain and the www subdomain, but you might also want to share them between any other set of subdomains.

Whatever set of subdomains you choose, you should set the cookie’s attribute to the most specific domain name that still includes all your required subdomains. For example, to share cookies between example.com and www.example.com, you would set the attribute to example.com. But if you wanted to share cookies between sub1.app.example.com and sub2.app.example.com, you should set the attribute to app.example.com. Any explicitly specified domain name will always include all subdomains that may exist.

You can change the attribute through one of the following means, in order of recommendation:

  • In the PHP configuration (php.ini), find the line with the session.cookie_domain directive and change its value as desired, e.g.:

    session.cookie_domain = example.com
    
  • As early as possible in your application, and before you create the Auth instance, call \ini_set to change the value of the session.cookie_domain directive as desired, e.g.:

    \ini_set('session.cookie_domain', 'example.com');

    For this to work, session.auto_start must be set to 0 in the PHP configuration (php.ini).

Restricting the path where cookies are available

A cookie’s path attribute controls which directories (and subdirectories) the cookie will be valid for, and thus where the user’s session and authentication state will be available.

In most cases, you’ll want to make cookies available for all paths, i.e. any directory and file, starting in the root directory. That is what a value of / for the attribute does, which is also the recommended default. You should only change this attribute to a different value, e.g. /path/to/subfolder, if you want to restrict which directories your cookies will be available in, e.g. to host multiple applications side-by-side, in different directories, under the same domain name.

You can change the attribute through one of the following means, in order of recommendation:

  • In the PHP configuration (php.ini), find the line with the session.cookie_path directive and change its value as desired, e.g.:

    session.cookie_path = /
    
  • As early as possible in your application, and before you create the Auth instance, call \ini_set to change the value of the session.cookie_path directive as desired, e.g.:

    \ini_set('session.cookie_path', '/');

    For this to work, session.auto_start must be set to 0 in the PHP configuration (php.ini).

Controlling client-side script access to cookies

Using the httponly attribute, you can control whether client-side scripts, i.e. JavaScript, should be able to access your cookies or not. For security reasons, it is best to deny script access to your cookies, which reduces the damage that successful XSS attacks against your application could do, for example.

Thus, you should always set httponly to 1, except for the rare cases where you really need access to your cookies from JavaScript and can’t find any better solution. In those cases, set the attribute to 0, but be aware of the consequences.

You can change the attribute through one of the following means, in order of recommendation:

  • In the PHP configuration (php.ini), find the line with the session.cookie_httponly directive and change its value as desired, e.g.:

    session.cookie_httponly = 1
    
  • As early as possible in your application, and before you create the Auth instance, call \ini_set to change the value of the session.cookie_httponly directive as desired, e.g.:

    \ini_set('session.cookie_httponly', 1);

    For this to work, session.auto_start must be set to 0 in the PHP configuration (php.ini).

Configuring transport security for cookies

Using the secure attribute, you can control whether cookies should be sent over any connection, including plain HTTP, or whether a secure connection, i.e. HTTPS (with SSL/TLS), should be required. The former (less secure) mode can be chosen by setting the attribute to 0, and the latter (more secure) mode can be chosen by setting the attribute to 1.

Obviously, this solely depends on whether you are able to serve all pages exclusively via HTTPS. If you can, you should set the attribute to 1 and possibly combine it with HTTP redirects to the secure protocol and HTTP Strict Transport Security (HSTS). Otherwise, you may have to keep the attribute set to 0.

You can change the attribute through one of the following means, in order of recommendation:

  • In the PHP configuration (php.ini), find the line with the session.cookie_secure directive and change its value as desired, e.g.:

    session.cookie_secure = 1
    
  • As early as possible in your application, and before you create the Auth instance, call \ini_set to change the value of the session.cookie_secure directive as desired, e.g.:

    \ini_set('session.cookie_secure', 1);

    For this to work, session.auto_start must be set to 0 in the PHP configuration (php.ini).

Utilities

Creating a random string

$length = 24;
$randomStr = \Delight\Auth\Auth::createRandomString($length);

Creating a UUID v4 as per RFC 4122

$uuid = \Delight\Auth\Auth::createUuid();

Reading and writing session data

For detailed information on how to read and write session data conveniently, please refer to the documentation of the session library, which is included by default.

Frequently asked questions

What about password hashing?

Any password or authentication token is automatically hashed using the “bcrypt” function, which is based on the “Blowfish” cipher and (still) considered one of the strongest password hash functions today. “bcrypt” is used with 1,024 iterations, i.e. a “cost” factor of 10. A random “salt” is applied automatically as well.

You can verify this configuration by looking at the hashes in your database table users. If the above is true with your setup, all password hashes in your users table should start with the prefix $2$10$, $2a$10$ or $2y$10$.

When new algorithms (such as Argon2) may be introduced in the future, this library will automatically take care of “upgrading” your existing password hashes whenever a user signs in or changes their password.

How can I implement custom password requirements?

Enforcing a minimum length for passwords is usually a good idea. Apart from that, you may want to look up whether a potential password is in some blacklist, which you could manage in a database or in a file, in order to prevent dictionary words or commonly used passwords from being used in your application.

To allow for maximum flexibility and ease of use, this library has been designed so that it does not contain any further checks for password requirements itself, but instead allows you to wrap your own checks around the relevant calls to library methods. Example:

function isPasswordAllowed($password) {
    if (\strlen($password) < 8) {
        return false;
    }

    $blacklist = [ 'password1', '123456', 'qwerty' ];

    if (\in_array($password, $blacklist)) {
        return false;
    }

    return true;
}

if (isPasswordAllowed($password)) {
    $auth->register($email, $password);
}

Why are there problems when using other libraries that work with sessions?

You might try loading this library first, and creating the Auth instance first, before loading the other libraries. Apart from that, there’s probably not much we can do here.

Why are other sites not able to frame or embed my site?

If you want to let others include your site in a <frame>, <iframe>, <object>, <embed> or <applet> element, you have to disable the default clickjacking prevention:

\header_remove('X-Frame-Options');

Exceptions

This library throws two types of exceptions to indicate problems:

  • AuthException and its subclasses are thrown whenever a method does not complete successfully. You should always catch these exceptions as they carry the normal error responses that you must react to.
  • AuthError and its subclasses are thrown whenever there is an internal problem or the library has not been installed correctly. You should not catch these exceptions.

General advice

  • Serve all pages over HTTPS only, i.e. using SSL/TLS for every single request.
  • You should enforce a minimum length for passwords, e.g. 10 characters, but never any maximum length, at least not anywhere below 100 characters. Moreover, you should not restrict the set of allowed characters.
  • Whenever a user was remembered through the “remember me” feature enabled or disabled during sign in, which means that they did not log in by typing their password, you should require re-authentication for critical features.
  • Encourage users to use passphrases, i.e. combinations of words or even full sentences, instead of single passwords.
  • Do not prevent users' password managers from working correctly. Thus, use the standard form fields only and do not prevent copy and paste.
  • Before executing sensitive account operations (e.g. changing a user’s email address, deleting a user’s account), you should always require re-authentication, i.e. require the user to verify their login credentials once more.
  • You should not offer an online password reset feature (“forgot password”) for high-security applications.
  • For high-security applications, you should not use email addresses as identifiers. Instead, choose identifiers that are specific to the application and secret, e.g. an internal customer number.

Contributing

All contributions are welcome! If you wish to contribute, please create an issue first so that your feature, problem or question can be discussed.

License

This project is licensed under the terms of the MIT License.

php-auth's People

Contributors

chibicitiberiu avatar cosmologist avatar eminmuhammadi avatar maxsenft avatar ocram avatar prometeusweb avatar sikanderiqbal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-auth's Issues

Compatibility note for stacks without mysqlnd

Hello

I don't know much about DevOps or how common mysqlnd is in LAMP stacks, but Bluehost currently doesn't provide it out-of-the-box. The other PDO MySQL connector doesn't typecast (instead treating everything as a string) which causes a bug on if ($userData['verified'] === 1) { and if ($userData['verified'] !== 1) { in Auth.php lines 587 and 682.

Obviously the preferred solution is for users to configure the server with mysqlnd, but I just thought I'd mention this...

customizable password requirements and enforcement?

I may have missed something in the documentation but where and how is this feature implemented?
I guess I could validate passwords myself before but I see there is a catch for InvalidPasswordException, however I didn't see where to customize password requirements or where the default requirements are defined.

Any help would be appreciated as I'm trying to use this authentication system for a website.
Thanks.

automatic login after email verification

Hello,

From a user experience point of view it may be a bit bothersome to have to login right after the "registration and verification of email address" process.

I thought about storing the email/password in sessions variables to automatically log the user in right after checking the token/selector for the email verification but this seems to create security issues (ie: storing a plain text password somewhere). Is there a better way to do this?

Is there a security reason for it not being already implemented?

Thanks.

Configurable database table prefix

We should introduce an optional database table prefix and make it configurable.

The default prefix will be the empty string, of course.

That option could be passed to the constructor of the Auth class as another parameter called $databaseTablePrefix.

before login function

Hello,
Can we add a public function to execute before login ( true => continue, false => stop ), I'll use that to add google 2 step verification.
but I think other people will find it useful for other things

Password challenge

Hello

Just a quick feature suggestion: the ability to challenge a user for a password without proceeding through a complete login process.

For example, imagine that a user is already authenticated because they are remembered. But now the user accesses a "dangerous" or "significant" feature (such as linking a bank account). It would be good to challenge the user for their password again to ensure that it is not an imposter using a shared computer, for instance.

Browsing the internals of Auth.php I see that this can be done by password_verify($password, $userData['password']). However, perhaps there is some more reusable logic that may be helpful. Or if the password hashing changes, it would be good to encapsulate it all in one place...

Thx

Re-send confirmation request

Very nice library! Been a breeze to integrate into my Slim3 app.

I wanted to discuss the possibility of re-sending an email confirmation request on demand after registration.
Case being where confirmation link is lost or expired before the user clicks it. In which case the user is stuck in limbo as far as I can tell.

It looks to me that this would mostly be a matter of making createConfirmationRequest public.
A DB DELETE query could also be issued on every call by default to invalidate any previous confirmation tokens for given email so that only the latest one is valid.

Are there any potential issues with this that I'm overlooking?

Best
Steini

issue when using "localhost"

I had a tiny issue when using localhost as domain.

It seemed like the parameters couldn't be pushed into a cookie. I just quickly debugged it in the "login" method. Maybe some further investigation will be necessary.

Just wanted to let u know.

I used it with a ordinary XAMPP stack with PHP 7 - just to make this information useful.

Great lib btw! 👍

[NFR] Getter & setter for \Delight\Db\PdoDatabase::$attributes.

Hi,

Thanks for a nice auth library.

I need an ability to modify PDO attributes - MySQL does not support PDO::ATTR_STRINGIFY_FETCHES.

Please implement:

In \Delight\Db\PdoDatabase:

/**
 * Set single PDO attribute.
 *
 * @param integer $key PDO attribute
 * @param integer $val PDO attribute value
 * @return $this
 */
public function setAttribute($key, $val)
{
    $this->attributes[$key] = $val;
    return $this;
}

/**
 * Set PDO attributes array.
 *
 * @param array $val PDO attributes in key/value format.
 * @return $this
 */
public function setAttributes(array $val = null)
{
    $this->attributes = $val;
    return $this;
}

/**
 * Get PDO attribute value.
 *
 * @param integer $key PDO attribute
 * @return mixed
 */
public function getAttribute($key)
{
    if (isset($this->attributes[$key])) {
        return $this->attributes[$key];
    }
}
/**
 * Get all PDO attributes.
 *
 * @return array|null
 */
public function getAttributes()
{
    return $this->attributes;
}

In Delight\Auth\Auth:

/**
 * @return PdoDatabase
 */
public function getDb()
{
    return $this->db;
}

Thanks!

What happens when Remember Me is `uncheck`?

This is more of a question than an issue. I wanted to understand the behaviour when I login using your library and Remember me is uncheck.

Will my session expire while browsing through the website? Imagine a use-case where I logged in and browser to about-us page from homepage. After landing on about-us page I should still be logged in.

Another example is of refresh. What happens when I refresh my page?

Only cases where I should be logged out is when I close my tab or browser or manually type another url in address bar. Post these user actions if I come back on the site and Remember me was uncheck I should be asked to login again.

Thanks in advance!

percent sign in cookie

Does auth use a non-standard way of writing the PHPSESSID cookie? I am sometimes getting a %25 (encoded %) in my cookie, which is causing an error to be displayed in unexpected places. Thanks!

need session after log out

After logging out, I have some ajax stuff that needs session variables in order to function.

Is it normal to force a page reload after using $auth->logout();? Or is there a preferred way to regenerate the session?

Let me know if you need more info. Thanks in advance!

User is not verified due to error.

/src/Auth.php on line 682
if ($userData['verified'] === 1) {
On one of my servers, this condition always returns false. On localhost it's ok, but on the live server, it throwed me an error. I suppose it's because MySQL alway returns strings as an output and 1 !== '1' while 1 == '1'. For some reason two my servers are dealing with this issue differently.
So I just switched from === to == and it worked.
I thought maybe it will be helpful to change.

Change request: role const values

Last post until I hear back from the project team, promise.

Requesting a breaking change to Roles class. Please can you reorder the CONST so that the values are in numerical order from lowest to highest privilege. Ie: super administrator should be 999, administrator should be 666, and basic user should be 333, and guest should be 1 or whatever.

Doing this will allow my extend to ensure that the admin interface will only grant or edit roles less than or equal to the currently logged in user. This is a standard security control against elevation of privilege - will also allow control of user granting themself additional roles.

Appreciate that users of this library can do this themselves by aliasing the const, but they won't realize the implication of NOT doing this unless it's a) down in the code, b) shown in the docs before the check is added to the admin role grant and remove methods.

Unfortunately this will be a breaking change for anyone who uses the library today, even though it's not actually a code change in itself, it just enables a feature to be implemented.

Might also be a good time to stop using const for roles, and use a database table instead, because the const approach is very limiting for features.

Thanks

The registration page keeps loading forever

register.php

<?php 
$pagetitle = 'register';
 require('database_connect.php');

$email = '[email protected]';
$password= 'somepassword';
$username='elie';

try {
    $userId = $auth->admin()->createUser($email, $password, $username);
    


    // we have signed up a new user with the ID `$userId`
}
catch (\Delight\Auth\InvalidEmailException $e) {
    // invalid email address
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    // invalid password
}
catch (\Delight\Auth\UserAlreadyExistsException $e) {
    // user already exists
}
 ?>

connect.php

<?php
require __DIR__ . '/vendor/autoload.php';
use SimpleCrud\SimpleCrud;


/* Connect to a MySQL database using driver invocation */
$dsn = 'mysql:dbname=db;host=127.0.0.1';
$user = 'root';
$password = '';

try {
    $pdo = new PDO($dsn, $user, $password);
    $db = new SimpleCrud($pdo);
    $auth = new \Delight\Auth\Auth($pdo);


} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}



?>

Also tried to edit it to match the one in readme file, same problem. nothing in database. I'm using mariadb, xampp for linux, latest version

Login remembered

Hallo und frohes neues Jahr für euch!
Ich versuchs mal auf deutsch, sorry.
Ich denke, dass es ein Fehlverhalten gibt, bei der Angabe des zweiten Parameters im Konstruktor.
Oder ich habs noch nicht verstanden...
Also wenn das ausgeführt wird:
$auth = new \Delight\Auth\Auth($db, true);
$auth->login($_POST['email'], $_POST['password'], null);

dann erzeugt später komischerweise $auth->check() den Wert false.
Obwohl man doch mindestens bis zum Schließen des Browsers angemeldet sein müsste.
Lediglich die Session-Variable "auth-remember" ist verfügbar!?
Wenn beim instanzieren "true" weggelassen wird, funktioniert es wie erwartet.
Das passiert sowohl lokal (XAMPP, PHP5.6) als auch bei STRATO-Hosting (SSL, PHP5.6)
Am Ende will ich eigentlich nur, dass ohne Zeitvorgabe die Session bei Beenden des Browsers zu Ende ist, also automatisch ausgeloggt wird. Ich bekomme es nicht hin ...
Can you help? ;-)

hashing mechanism

What sort of hashing mechanism is being used in php-auth?

Thanks for your time!

Additional columns

Hello,

Is there any way to set additional data in users table during registration? It would be perfect if after sucessful login we'll receive it in Session either. Any chances to do so?

Of course I can insert additional data just after registration and then make wrapper to login method with additional SELECT statement, but maybe there is a way to do so only using PHP-Auth?

Extending the class

Hi,

Wouldn't it be better for the methods to be protected in case you want to extend the Auth class? For example, if I want a login method with user name instead of e-mail.

header already sent problems

I have a strange fenomenon:
On one subdomain (user tests) I am using the nearly same redirects but get no errors...
On the other subdomain (integration tests) I made a fresh install with a slight change (full domain - not relative header location calls) but got weird behaviour: It's actually not redirecting...
because Auth is already sending out headers...
But I have no clue why the code works in one subdomain, but in slight variation ( header('Location http://subdomain/folder/file.php) ) it doesn't... Specially why my change would provoke a different behaviour in Auth

representative Code (produces empty page, no redirect):
PD: Fact is: after running the code I am still logged in...

$AUTH->logout();
$_SESSION['preguntas_educacion'] = NULL;
$_SESSION['preguntas_postulacion'] = NULL;
?>
<?php if ($AUTH->isLoggedIn()): ?>
    <?php 
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
header("Location: http://$host$uri/paso1.php"); ?>
<?php else: ?>
    <?php 
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
header("Location: http://$host$uri/login.php"); ?>
<?php endif; ?>

Error:

Warning: ini_set(): A session is active. You cannot change the session module's ini settings at this time in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php on line 73

Warning: Cannot modify header information - headers already sent by (output started at /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php:73) in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php on line 87

Warning: Cannot modify header information - headers already sent by (output started at /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php:73) in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php on line 92

Warning: Cannot modify header information - headers already sent by (output started at /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php:73) in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php on line 94

Warning: Cannot modify header information - headers already sent by (output started at /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php:73) in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php on line 97

Warning: Cannot modify header information - headers already sent by (output started at /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php:73) in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php on line 98

Warning: Cannot modify header information - headers already sent by (output started at /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php:73) in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php on line 99

Fatal error: Uncaught exception 'Delight\Auth\HeadersAlreadySentError' in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php:320 Stack trace: #0 /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php(277): Delight\Auth\Auth->setRememberCookie(NULL, NULL, 1495128213) #1 /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php(371): Delight\Auth\Auth->deleteRememberDirective(50) #2 /home/user/subdomain.whatever.com/logout.php(15): Delight\Auth\Auth->logout() #3 {main} thrown in /home/user/subdomain.whatever.com/vendor/delight-im/auth/src/Auth.php on line 320

Cookie expire problem

I have problem at remember me function. Can you please show me the exact place to set an non-expiring cookie for the login ?

Headers already sent on logout

I'm having an issue using your logout method.

I'm using an MVC pattern so there is a link on my view like http://mysite/Account/Logout from which i call logout from PHP-Auth lib.
This produce to me the error Delight\Auth\HeadersAlreadySentError, with this stack trace:

#0 C:\xampp\htdocs\auth-bcv\vendor\delight-im\auth\src\Auth.php(315): Delight\Auth\Auth->setRememberCookie(NULL, NULL, 1502959682)
#1 C:\xampp\htdocs\auth-bcv\vendor\delight-im\auth\src\Auth.php(414): Delight\Auth\Auth->deleteRememberDirective(7)
#2 C:\xampp\htdocs\auth-bcv\Controllers\AccountController.php(411): Delight\Auth\Auth->logout()
#3 C:\xampp\htdocs\auth-bcv\Routes.php(61): AuthBcv\Controllers\AccountController->LogOut(Array)
#4 C:\xampp\htdocs\auth-bcv\Routes.php(97): call('Account', 'LogOut', Array)
#5 C:\xampp\htdocs\auth-bcv\Views\Shared\_Layout.php(23): require_once('C:\\xampp\\htdocs...')
#6 C:\xampp\htdocs\auth-bcv\index.php(37): require_once('C:\\xampp\\htdocs...')
#7 {main}

that i can't understand how to solve.

How can i fix this problem? Is there something wrong in my use of logout?

Questions about db schema

Hello!
First, thanks for this nice library.
I just have a couple questions about the database schema you use:

  • Is there any reason you use MyISAM over InnoDB (with foreign keys)?
  • Some columns are defined with a latin charset, is there a reason for that also? (simple curiosity)

Thank you!

Using Content-Security-Policy instead of X-Frame-Options

In "enhanceHttpSecurity" X-Frame-Options is used do prevent clickjacking. Would it be possible to use Content-Security-Policy instead?

This would allow to add exceptions without having to change PHP-AUTH or removing the X-Frame-Options and readding it with changed parameters.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors

Thank you for this amazing piece of work, I really enjoyed integrating the authentication system in some of my projects :)

change user email address

There's a way to change the current user's password.

Is there a way to change the current user's email address?

Provide a way to revoke sessions and to perform remote logouts

Whenever a user signs in, we could add the session ID, together with the ID of the user who has just logged in, to the database (into some new table that will be created for that purpose).

It might even make sense to track the IP address and user-agent string there as well, if not disabled for privacy reasons.

CREATE TABLE users_sessions (
    user_id int(10) unsigned NOT NULL,
    session_id varchar(256) CHARACTER SET latin1 NOT NULL,
    user_agent varchar(192) DEFAULT NULL,
    ip_address varchar(45) DEFAULT NULL,
    expires_at int(10) unsigned NOT NULL,
    PRIMARY KEY (user_id, session_id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;

In the two methods UserManager#onLoginSuccessful and Auth#logOut, we would always update the database with the latest information about the current session. That may not be enough, though. The expires_at column in the database schema is the critical piece of information here.

That would allow us to show users a list of all sessions (or devices) where they're currently logged in.

In addition to that, any of these sessions could then be killed remotely, e.g. as in the following example, which has neither been tested thoroughly nor been executed at all, though:

function destroySessionById($id) {
	$pausedSessionId = '';

	// if a session is currently active
	if (\session_id() != '') {
		// if that session is not the one we're trying to destroy
		if (\session_id() !== $id) {
			// remember which session it was that we interrupted
			$pausedSessionId = \session_id();
			// save and close that active session
			\session_write_close();
		}
	}

	// if the session to be destroyed has not been opened yet
	if (\session_id() == '') {
		// impersonate the session to be destroyed
		\session_id($id);
		// and open the session
		\session_start();
	}

	// unset the session variables
	$_SESSION = array();
	// destroy the session
	\session_destroy();
	// save and close the destroyed session
	\session_write_close();

	// if we have previously interrupted another session
	if ($pausedSessionId != '') {
		// assume that session again
		\session_id($pausedSessionId);
		// and open the session
		\session_start();
	}
}

Using those new resources, some new logOutFromAllDevices method would be possible as well.

Two PHPSESSID cookies

We are having an issue with two PHPSESSID cookies being created or a previously existing PHPSESSID cookie not being cleared after we implement php-auth.

$auth->check() passes at login but subsequently fails if we do not clear one of the cookies.

This seems to be happening in two circumstances:

  1. If a user has not cleared an existing PHPSESSID cookie, created before we implemented php-auth. This may be the result of the user having the website open when we updated the code to include php-auth.
  2. If a user has a domain and subdomain open in the same browser. If we have something like abw.mywebsite.com and mywebsite.com open in the same browser then we see two PHPSESSID cookies .abw.mywebsite.com and .mywebsite.com.

$auth->check() passes at login but subsequently fails if we do not clear one of the cookies.

Any ideas on what the issue / solution may be?

Failing to check if email is verified

In Auth.php the authenticateUserInternal method is failing to check if user column 'verified' is set to 1 because it is strictly comparing a string with an integer:

if ($userData['verified'] === 1) {

should have been casted to an integer:

if ((int)$userData['verified'] === 1) {

is it correct?

Inactive Users

Hello

First I'd like to express my appreciation for these very simple and extremely elegant libraries.

My question or suggestion relates to making users inactive. Rather than deleting rows, it is often preferable to set a flag for "isDeleted" or "isInactive". Storing such a column in another Users_Data table (e.g. Users_Profiles) might cause poor performance because of the join (especially when also joined with a User_Posts or User_Votes table). Would an "activeStatus" column be a candidate to be added to the main Users table in a schema update? I see you're careful to avoid bloat, but I just thought I'd suggest this. Alternatively, would it be bad form to combine this functionality with the suggested Roles feature?

Perhaps a workaround in the meantime would be to append or prepend an invalid ASCII string to the email column. Something like [[@@]] that isn't allowed in email addresses. It should still be able to query active users simply and quickly.

DB for Doctrine entity

Ir is possible to get Mysql entity class's for Doctrine instead MySQL.sql?
Many thanks.

Ensure account is verified before initiating password reset

I have an app that requires admin-approval of user accounts. The email verification already built into PHP-Auth works great for this (verification links sent to admins instead of users).

This brings up the use case where a user may register, then attempt to reset their password prior to the account being verified (could also occur for user email verification as well, although perhaps less often). I modified Auth::forgotPassword as follows to check if the account is verified before initiating the password reset process:

public function forgotPassword($email, callable $callback, $requestExpiresAfter = null, $maxOpenRequests = null) {
		$email = self::validateEmailAddress($email);

		if ($requestExpiresAfter === null) {
			// use six hours as the default
			$requestExpiresAfter = 60 * 60 * 6;
		}
		else {
			$requestExpiresAfter = (int) $requestExpiresAfter;
		}

		if ($maxOpenRequests === null) {
			// use two requests per user as the default
			$maxOpenRequests = 2;
		}
		else {
			$maxOpenRequests = (int) $maxOpenRequests;
		}

		// Ensure account is verified before initiating password reset
		try {
			$userData = $this->db->selectRow(
				'SELECT id, verified FROM users WHERE email = ?',
				[ $email ]
			);
		}
		catch (Error $e) {
			throw new DatabaseError();
		}

		if ($userData['verified'] !== 1) {
			throw new EmailNotVerifiedException();
		}

		$userId =  $userData["id"];
		// $userId = $this->getUserIdByEmailAddress($email); // no longer needed
		$openRequests = (int) $this->getOpenPasswordResetRequests($userId);

		if ($openRequests < $maxOpenRequests) {
			$this->createPasswordResetRequest($userId, $requestExpiresAfter, $callback);
		}
		else {
			self::onTooManyRequests($requestExpiresAfter);
		}
	}

And made sure to catch the new error in the $auth->forgotPassword handler:

try {
	$auth->forgotPassword($_POST['email'], function ($selector, $token) {
			// send `$selector` and `$token` to the user (e.g. via email)
	});

	// request has been generated
}
catch (\Delight\Auth\InvalidEmailException $e) {
	// invalid email address
}
catch (\Delight\Auth\TooManyRequestsException $e) {
	// too many requests
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
	// email not verified
}

Would be happy to create a pull request if it'll help, or if there's a more optimal solution would be great to hear that too. Thank you very much for an excellent, lightweight, well-documented library!

Fixed issues, added features

There's some other security issues with this library, and it's missing a lot of admin features.

I've fixed all that, made the login system authoritative, and done some other stuff.

I also dislike how unfriendly github is, so I've done my best with the files. Good luck.

https://github.com/32Blahs/PHP-AuthExtra

Thinking behind logout process

Hi guys, please can you explain your thinking behind the session and cookie destruction in the logout method?

I'd suggest PHPAuth should only kill session data directly related to auth & login, not the entire session. Killing the entire session has impact on other code outside of PHPAuth. For example, if the session is used to also retain for example "last used" (e.g.: "last search terms", "id of last thing looked at"), this session data may need to be preserved.

Imagine a menu where "recent searches", "recent products viewed" is an option, and those recent searches are retained in the session (rather than a backend DB). The user may want to log out, then log in again a few mins later or even view the site from a "not logged in state", and from a user experience point of view they'd expect to still see their "recent searches".

Hard killing the session in the way you do it can also cause other problems, e.g.: with ajax requests etc. I get why you've probably done this, but you're making the assumption that only valid activities can happen following a PHPAuth login - which isn't the case in many real world applications.

Thank you

composer strange import

It's actually my first try with PHPAuth & Composer, so maybe I did something wrong.

I followed the install guideline as suggested and uploaded to my server.
To my astonishment when testing I was getting a
Fatal error: Call to undefined method Delight\Auth\Auth::getStatus() in /home/........./delightPHPAuth/tests/index.php on line 349

Now after some long debugging, I've found out that composer included a delight-im package, which seems not matching the one in the master tree.
the file structure is different, and the AuthClass obviously too, that's where the error came from.
So now instead of taking the AuthClass from root/src it takes it from root/vendor/delight-im/auth/src

Now the main questions is: Did I something wrong? is there even something I could do wrong?
And even better: How to do it right and correctly fix it?

DB agnostic? Requires mysql...

Hi there, I'm not sure what you mean by db agnostic, if there is a requirement for mysql. I see that you pass a pdo instance to the class; can i use a pdo instance of sqlserver?

Installation instruction not sufficient

Dear Delight-Im,

When following the instructions I keep getting an error.
I copied the files (Auth.php, Base64.php and Exceptions.php) to a subfolder.
When I run the following script however, I get the following errors, no matter what I tried.
I feel like there might be an error using the namespaces?

I run the following (I tried both instances of $db uncommented)

require 'subfolder/Auth.php';
// $db = new PDO('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
// or
// $db = new \Delight\Db\PdoDsn('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');

$auth = new \Delight\Auth\Auth($db);

But I get the following errors:
Uncaught Error: Class 'Delight\Db\PdoDatabase' not found in ... Stack trace: #0 ...: Delight\Auth\Auth->__construct(Object(PDO)) #1 {main}

OR

Fatal error: Uncaught Error: Class 'Delight\Auth\PdoDsn' not found in ...
Stack trace: #0 {main}

I tried to install everything using composer but I got the some errors......

I am really looking forward to start using this package!

Cheers

Adding support for roles

We should add support for user roles to this library soon. A list of available roles can be hard-coded and could look like this:

final class Role {

	const ADMIN = 1;
	const AUTHOR = 2;
	const COLLABORATOR = 4;
	const CONSULTANT = 8;
	const CONSUMER = 16;
	const CONTRIBUTOR = 32;
	const COORDINATOR = 64;
	const CREATOR = 128;
	const DEVELOPER = 256;
	const DIRECTOR = 512;
	const EDITOR = 1024;
	const EMPLOYEE = 2048;
	const MAINTAINER = 4096;
	const MANAGER = 8192;
	const MODERATOR = 16384;
	const PUBLISHER = 32768;
	const REVIEWER = 65536;
	const SUBSCRIBER = 131072;
	const SUPER_ADMIN = 262144;
	const SUPER_EDITOR = 524288;
	const SUPER_MODERATOR = 1048576;
	const TRANSLATOR = 2097152;

	private function __construct() {}

}

You can then use any of these roles and ignore those that you don't need, and you can even combine these roles as you like. Thus a user may have none of these rules, one role or any other arbitrary subset.

Although a fixed set of roles is hard-coded in this implementation, the set of roles should include identifiers for most use cases. And if you really can't work with these roles, you can alias them using your own role identifiers:

final class MyRole {

	const CUSTOMER_SERVICE_AGENT = Role::REVIEWER;
	const FINANCIAL_DIRECTOR = Role::COORDINATOR;

	private function __construct() {}

}

That, for example, would allow you to use MyRole::FINANCIAL_DIRECTOR instead of Role::COORDINATOR.

Checking for roles that the current user has might then be done like this:

/** @var Auth $auth */

if ($auth->hasRole(Role::ADMIN)) {
	// ...
}

// or

if ($auth->hasAnyRole(Role::MODERATOR, Role::SUPER_MODERATOR, Role::ADMIN)) {
	// ...
}

// or

if ($auth->hasAllRoles(Role::TRANSLATOR, Role::REVIEWER)) {
	// ...
}

This feature would not include support for permissions, capabilities, access rights or privileges. These could be added with custom solutions in user code or one could go entirely without them. As can be seen above, it's possible to implement access restrictions using roles only. The privileges are then encoded in the conditions that specify the required roles.

Since the roles require database changes (at least one new column in the users table) that must be applied manually, this is a breaking change that can only be in a new major release. The next one would currently be v5.0.0.

Feedback, requests for additions/changes and criticism is welcome!

Security issue (and why autoloaders are a bad idea)

For clarity, the issue is with the way examples in the docs are written, combined with the way the PHPAuth library uses your DB library. It's creating a false sense of security.

The simple version: all of the examples in the documentation directly use unchecked POST input for params. This is OK in terms of SQL injection, because the underlying DB lib uses PDO prepared statements which automagically escapes everything.

However it does NOT prevent app level security risks. For example, a user can write javascript into a param (e.g.: change my email address). The script will be escaped when written to the DB, but unescaped on read and output in original format if echo'd to a page.

Assuming you code an admin system that lists all the users with their email addresses in a table, so you can take admin actions, this is a flaw - a user can execute code in the admin view.

So anyone using this library must ensure that all user input from POST and GET etc are correctly sanitized, despite PHPAuth documentation not mentioning this and explicitly using it in the examples (and, on assumption, relying on PHPDB PDO automagic to secure input). The OWASP recommendations are a good starting point: https://www.owasp.org/index.php/OWASP_PHP_Filters

The autoloader compounds this problem. If you simply use the autoloader, you can be forgiven for not realizing that PHPAuth uses PHP DB library & what protection it actually does/does not offer. This is why autoloaders are a bad idea - you don't know what dependency code is being included in your project simply by using a library.

In summary, either the documentation needs to be changed to highlight that POST and GET must be sanitized and should absolutely not be passed to PHPAuth unchecked. Or PHP Auth must be changed so that data is properly escaped at all stages (I'd suggest this is a better option, because nobody should have a username or email address that includes < script > etc

The problem is that at the moment you have a half way solution - some issues are prevented due to PDO automagic, but other issues are not prevented. Less savvy users of this code may assume that the protection offered by PHPDB (from the docs: "Safe against SQL injections through the use of prepared statements") is sufficient, when it's absolutely not - that is, if they even realize the additional libs that are in use due to autoload.

Happy to be told I'm wrong here because I don't use PDO, I use mysqli, but looks like a gap to me.

manual installation readme for shared servers that don't allow composer?

For the many thousands of us working on shared servers across many hosting sites, composer isn't installed or allowed without upgrading to VPS or dedicated boxes. It would be most awesome if a detailed readme could be made explaining how to install PHP-Auth manually. Obviously, the DB is easy part, although I love your idea of a table prefix option.

Would this be possible? Many thanks for your awesome work!

No test/exception for DB failure on construct

Nice library (although wish you would also include a manual include/no autoload include.php, had to do that myself and it's painful because the dir structure sprawls a bit, I don't like autoloaders....).

When instantiating a PHP-Auth, there doesn't seem to be a way to immediately test or catch whether there was an issue with the database / setup.

Testing whether the setup was ok is pretty critical for an authentication/security mechanism. If there was an error connecting to the DB or reading any data, I want to die() immediately rather than risk some unexpected insecure code flow.

For example, the following doesn't throw any exception. I tried using isLoggedIn() to force a throw, but nothing happens:

$db = new \Delight\Db\PdoDsn('mysql:dbname=SOME;host='INVALID', 'DATABASE', 'CONFIG');
$auth = new \Delight\Auth\Auth($db, SITE_HTTPS_ENFORCED, FALSE, NULL, "php_auth_");
$auth->isLoggedIn(); // should fail, but doesn't throw?

However later if I call
$auth->login("deliberately", "junkdata");

I get a Delight\Auth\DatabaseError thrown.

This seems wrong workflow to me. I understand why it happens due to PHP-DB, but in my opinion this isn't right. Regardless of lazy load in PHP-DB (which I don't use anywhere else in my code), PHP-Auth should actively check for valid DB connection on instantiation. If PHP-Auth doesn't throw when I instantiate it with all the data necessary to set up, the logical assumption is everything is working.

Ability to immediately dump out on critical error of PHP-Auth failure to access DB is essential. It creates the following scenario, for example when allowing a password reset after form submission:

$db = new \Delight\Db\PdoDsn('mysql:dbname=SOME;host='INVALID', 'DATABASE', 'CONFIG');
$auth = new \Delight\Auth\Auth($db, SITE_HTTPS_ENFORCED, FALSE, NULL, "php_auth_");
$auth->forgotPassword("irrelevant - db config is bad", function ($selector, $token)
{
// blah
});

The exception thrown is InvalidEmailException, when actually it should be DatabaseError and handled completely differently.

I'd be happy with a ->Connect method, to force immediate DB connection. There's no penalty here as you're only ever instantiating PHP-Auth when you need it for something...

Database encoding

Hi,

is it a security issue to use utf8_unicode_ci (instead of utf8mb4) for the database encoding (MySQL)?
Thanks,

Flo

doesn't work with two installations on one domain.

If you try to use the library on two websites sharing one domain (ex.: domain.com and sub.domain.com), after authorisation on domain.com you go to sub.domain.com and login fails every time no matter what.
This happens when two sessions are active. If you go to the Developer Tools and remove both sessions from cookies, authorization starts working. But again until you get two sessions on both installations active again. Which happens to me quite often.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.