Download the PHP package delight-im/auth without Composer

On this page you can find all versions of the php package delight-im/auth. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?
delight-im/auth
Rate from 1 - 5
Rated 4.00 based on 5 reviews

Informations about the package auth

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?

Requirements

Installation

  1. Include the library via Composer [?]:

  2. Include the Composer autoloader:

  3. Set up a database and create the required tables:

    • MariaDB
    • MySQL
    • PostgreSQL
    • SQLite

Upgrading

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

Usage

Creating a new instance

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)

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:

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

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)

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.

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.

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

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.:

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:

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

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:

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.

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.

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.:

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:

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

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:

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

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:

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

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

User ID

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

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

Email address

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

Display name

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

Checking whether the user was “remembered”

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

IP address

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:

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.

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

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:

Available roles

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:

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:

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:

The example above would allow you to use

instead of

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:

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

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:

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:

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

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:

Deleting users by their email address:

Deleting users by their 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:

Assigning roles to users

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

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

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

Impersonating users (logging in as user)

Changing a user’s password

Cookies

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

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

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:

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:

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:

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:

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:

Utilities

Creating a random string

Creating a UUID v4 as per RFC 4122

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:

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:

Exceptions

This library throws two types of exceptions to indicate problems:

General advice

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.


All versions of auth with dependencies

PHP Build Version
Package Version
Requires php Version >=5.6.0
ext-openssl Version *
delight-im/base64 Version ^1.0
delight-im/cookie Version ^3.1
delight-im/db Version ^1.3
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package delight-im/auth contains the following files

Loading the files please wait ....