mirror of
https://github.com/delight-im/PHP-Auth.git
synced 2025-08-08 09:06:29 +02:00
Compare commits
17 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
dac2850aba | ||
|
4268e3fcd5 | ||
|
d579179494 | ||
|
bd02e08f83 | ||
|
d4fe11b844 | ||
|
09fabd4c91 | ||
|
4dcf491ad9 | ||
|
4f5ff151ef | ||
|
f5027c09e9 | ||
|
6db82d1f65 | ||
|
f944067aff | ||
|
a640e8a5ad | ||
|
2aee8a662e | ||
|
36ef710480 | ||
|
9187840767 | ||
|
6bfa298836 | ||
|
6be456a27a |
105
README.md
105
README.md
@@ -22,25 +22,46 @@ Completely framework-agnostic and database-agnostic.
|
||||
|
||||
## Installation
|
||||
|
||||
* Set up the PHP library
|
||||
* Install via [Composer](https://getcomposer.org/) (recommended)
|
||||
1. Include the library via [Composer](https://getcomposer.org/):
|
||||
|
||||
`$ composer require delight-im/auth`
|
||||
```
|
||||
$ composer require delight-im/auth
|
||||
```
|
||||
|
||||
Include the Composer autoloader:
|
||||
1. Include the Composer autoloader:
|
||||
|
||||
`require __DIR__.'/vendor/autoload.php';`
|
||||
```php
|
||||
require __DIR__ . '/vendor/autoload.php';
|
||||
```
|
||||
|
||||
1. Set up a database and create the required tables:
|
||||
|
||||
* or
|
||||
* Install manually
|
||||
* Copy the contents of the [`src`](src) directory to a subfolder of your project
|
||||
* Include the files in your code via `require` or `require_once`
|
||||
* Set up a database and create the required tables
|
||||
* [MySQL](Database/MySQL.sql)
|
||||
|
||||
## Usage
|
||||
|
||||
### Create a new instance
|
||||
* [Creating a new instance](#creating-a-new-instance)
|
||||
* [Registration (sign up)](#registration-sign-up)
|
||||
* [Login (sign in)](#login-sign-in)
|
||||
* [Email verification](#email-verification)
|
||||
* [Keeping the user logged in](#keeping-the-user-logged-in)
|
||||
* [Password reset ("forgot password")](#password-reset-forgot-password)
|
||||
* [Changing the current user's password](#changing-the-current-users-password)
|
||||
* [Logout](#logout)
|
||||
* [Accessing user information](#accessing-user-information)
|
||||
* [Login state](#login-state)
|
||||
* [User ID](#user-id)
|
||||
* [Email address](#email-address)
|
||||
* [Display name](#display-name)
|
||||
* [Checking whether the user was "remembered"](#checking-whether-the-user-was-remembered)
|
||||
* [IP address](#ip-address)
|
||||
* [Additional user information](#additional-user-information)
|
||||
* [Utilities](#utilities)
|
||||
* [Creating a random string](#creating-a-random-string)
|
||||
* [Creating a UUID v4 as per RFC 4122](#creating-a-uuid-v4-as-per-rfc-4122)
|
||||
* [Reading and writing session data](#reading-and-writing-session-data)
|
||||
|
||||
### Creating a new instance
|
||||
|
||||
```php
|
||||
// $db = new PDO('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
|
||||
@@ -58,7 +79,7 @@ Only in the very rare case that you need access to your cookies from JavaScript,
|
||||
|
||||
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 fourth argument. The default is `null`.
|
||||
|
||||
### Registration (sign up a new user)
|
||||
### Registration (sign up)
|
||||
|
||||
```php
|
||||
try {
|
||||
@@ -84,6 +105,8 @@ catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
|
||||
The username in the third parameter is optional. You can pass `null` here 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`, if necessary.
|
||||
|
||||
For email verification, you should build an URL with the selector and token and send it to the user, e.g.:
|
||||
|
||||
```php
|
||||
@@ -92,7 +115,7 @@ $url = 'https://www.example.com/verify_email?selector='.urlencode($selector).'&t
|
||||
|
||||
If you don't want to perform email verification, just omit the last parameter to `Auth#register`. The new user will be active immediately, then.
|
||||
|
||||
### Login (sign in an existing user)
|
||||
### Login (sign in)
|
||||
|
||||
```php
|
||||
try {
|
||||
@@ -173,6 +196,9 @@ try {
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// invalid email address
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email not verified
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
}
|
||||
@@ -245,7 +271,9 @@ $auth->logout();
|
||||
// user has been signed out
|
||||
```
|
||||
|
||||
### Checking if the user is signed in
|
||||
### Accessing user information
|
||||
|
||||
#### Login state
|
||||
|
||||
```php
|
||||
if ($auth->isLoggedIn()) {
|
||||
@@ -258,7 +286,7 @@ else {
|
||||
|
||||
A shorthand/alias for this method is `$auth->check()`.
|
||||
|
||||
### Getting the user's ID
|
||||
#### User ID
|
||||
|
||||
```php
|
||||
$id = $auth->getUserId();
|
||||
@@ -268,7 +296,7 @@ If the user is not currently signed in, this returns `null`.
|
||||
|
||||
A shorthand/alias for this method is `$auth->id()`.
|
||||
|
||||
### Getting the user's email address
|
||||
#### Email address
|
||||
|
||||
```php
|
||||
$email = $auth->getEmail();
|
||||
@@ -276,7 +304,7 @@ $email = $auth->getEmail();
|
||||
|
||||
If the user is not currently signed in, this returns `null`.
|
||||
|
||||
### Getting the user's display name
|
||||
#### Display name
|
||||
|
||||
```php
|
||||
$email = $auth->getUsername();
|
||||
@@ -286,7 +314,7 @@ Remember that usernames are optional and there is only a username if you supplie
|
||||
|
||||
If the user is not currently signed in, this returns `null`.
|
||||
|
||||
### Checking if the user was "remembered"
|
||||
#### Checking whether the user was "remembered"
|
||||
|
||||
```php
|
||||
if ($auth->isRemembered()) {
|
||||
@@ -299,15 +327,36 @@ else {
|
||||
|
||||
If the user is not currently signed in, this returns `null`.
|
||||
|
||||
### Getting the user's IP address
|
||||
#### IP address
|
||||
|
||||
```php
|
||||
$ip = $auth->getIpAddress();
|
||||
```
|
||||
|
||||
### Reading and writing session data
|
||||
#### Additional user information
|
||||
|
||||
For detailed information on how to read and write session data conveniently, please refer to [the documentation of the session library](https://github.com/delight-im/PHP-Cookie), which is included by default.
|
||||
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`.
|
||||
1. Whenever you call the `register` method (which returns the new user's ID), add your own logic afterwards that fills your custom database tables.
|
||||
1. 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:
|
||||
|
||||
```php
|
||||
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'];
|
||||
}
|
||||
```
|
||||
|
||||
### Utilities
|
||||
|
||||
@@ -324,6 +373,10 @@ $randomStr = \Delight\Auth\Auth::createRandomString($length);
|
||||
$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](https://github.com/delight-im/PHP-Cookie#reading-and-writing-session-data), which is included by default.
|
||||
|
||||
## Features
|
||||
|
||||
* registration
|
||||
@@ -369,12 +422,12 @@ This library throws two types of exceptions to indicate problems:
|
||||
|
||||
## General advice
|
||||
|
||||
* Both serving the authentication pages (e.g. login and registration) and submitting the data entered by the user should only be done over TLS (HTTPS).
|
||||
* You should enforce a minimum length for passwords, e.g. 10 characters, but *no* maximum length. Moreover, you should not restrict the set of allowed characters.
|
||||
* Whenever a user was remembered ("remember me") and did not log in by entering their password, you should require re-authentication for critical features.
|
||||
* 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 pass*phrases*, i.e. combinations of words or even full sentences, instead of single pass*words*.
|
||||
* Do not prevent users' password managers from working correctly. Thus please 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 sign in once more.
|
||||
* 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.
|
||||
|
||||
|
185
src/Auth.php
185
src/Auth.php
@@ -151,9 +151,9 @@ class Auth {
|
||||
/**
|
||||
* Attempts to sign up a user
|
||||
*
|
||||
* If you want accounts to be activated by default, pass `null` as the callback
|
||||
* If you want the user's account to be activated by default, pass `null` as the callback
|
||||
*
|
||||
* If you want to perform email verification, pass an anonymous function as the callback
|
||||
* If you want to make the user verify their email address first, pass an anonymous function as the callback
|
||||
*
|
||||
* The callback function must have the following signature:
|
||||
*
|
||||
@@ -174,42 +174,37 @@ class Auth {
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function register($email, $password, $username = null, callable $callback = null) {
|
||||
$this->throttle(self::THROTTLE_ACTION_REGISTER);
|
||||
|
||||
$email = self::validateEmailAddress($email);
|
||||
$password = self::validatePassword($password);
|
||||
|
||||
$username = isset($username) ? trim($username) : null;
|
||||
$password = password_hash($password, PASSWORD_DEFAULT);
|
||||
$verified = isset($callback) && is_callable($callback) ? 0 : 1;
|
||||
|
||||
try {
|
||||
$this->db->insert(
|
||||
'users',
|
||||
[
|
||||
'email' => $email,
|
||||
'password' => $password,
|
||||
'username' => $username,
|
||||
'verified' => $verified,
|
||||
'registered' => time()
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (IntegrityConstraintViolationException $e) {
|
||||
// if we have a duplicate entry
|
||||
throw new UserAlreadyExistsException();
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
return $this->createUserInternal(false, $email, $password, $username, $callback);
|
||||
}
|
||||
|
||||
$newUserId = (int) $this->db->getLastInsertId();
|
||||
|
||||
if ($verified === 0) {
|
||||
$this->createConfirmationRequest($email, $callback);
|
||||
}
|
||||
|
||||
return $newUserId;
|
||||
/**
|
||||
* Attempts to sign up a user while ensuring that the username is unique
|
||||
*
|
||||
* If you want the user's account to be activated by default, pass `null` as the callback
|
||||
*
|
||||
* If you want to make the user verify their email address first, pass an anonymous function as the callback
|
||||
*
|
||||
* The callback function must have the following signature:
|
||||
*
|
||||
* `function ($selector, $token)`
|
||||
*
|
||||
* Both pieces of information must be sent to the user, usually embedded in a link
|
||||
*
|
||||
* When the user wants to verify their email address as a next step, both pieces will be required again
|
||||
*
|
||||
* @param string $email the email address to register
|
||||
* @param string $password the password for the new account
|
||||
* @param string|null $username (optional) the username that will be displayed
|
||||
* @param callable|null $callback (optional) the function that sends the confirmation email to the user
|
||||
* @return int the ID of the user that has been created (if any)
|
||||
* @throws InvalidEmailException if the email address was invalid
|
||||
* @throws InvalidPasswordException if the password was invalid
|
||||
* @throws UserAlreadyExistsException if a user with the specified email address already exists
|
||||
* @throws DuplicateUsernameException if the specified username wasn't unique
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function registerWithUniqueUsername($email, $password, $username = null, callable $callback = null) {
|
||||
return $this->createUserInternal(true, $email, $password, $username, $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -690,6 +685,7 @@ class Auth {
|
||||
* @param int|null $requestExpiresAfter (optional) the interval in seconds after which the request should expire
|
||||
* @param int|null $maxOpenRequests (optional) the maximum number of unexpired and unused requests per user
|
||||
* @throws InvalidEmailException if the email address was invalid or could not be found
|
||||
* @throws EmailNotVerifiedException if the email address has not been verified yet via confirmation email
|
||||
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
@@ -712,11 +708,20 @@ class Auth {
|
||||
$maxOpenRequests = (int) $maxOpenRequests;
|
||||
}
|
||||
|
||||
$userId = $this->getUserIdByEmailAddress($email);
|
||||
$openRequests = (int) $this->getOpenPasswordResetRequests($userId);
|
||||
$userData = $this->getUserDataByEmailAddress(
|
||||
$email,
|
||||
[ 'id', 'verified' ]
|
||||
);
|
||||
|
||||
// ensure that the account has been verified before initiating a password reset
|
||||
if ($userData['verified'] !== 1) {
|
||||
throw new EmailNotVerifiedException();
|
||||
}
|
||||
|
||||
$openRequests = (int) $this->getOpenPasswordResetRequests($userData['id']);
|
||||
|
||||
if ($openRequests < $maxOpenRequests) {
|
||||
$this->createPasswordResetRequest($userId, $requestExpiresAfter, $callback);
|
||||
$this->createPasswordResetRequest($userData['id'], $requestExpiresAfter, $callback);
|
||||
}
|
||||
else {
|
||||
self::onTooManyRequests($requestExpiresAfter);
|
||||
@@ -724,17 +729,105 @@ class Auth {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the user ID for the account with the specified email address (if any)
|
||||
* Creates a new user
|
||||
*
|
||||
* If you want the user's account to be activated by default, pass `null` as the callback
|
||||
*
|
||||
* If you want to make the user verify their email address first, pass an anonymous function as the callback
|
||||
*
|
||||
* The callback function must have the following signature:
|
||||
*
|
||||
* `function ($selector, $token)`
|
||||
*
|
||||
* Both pieces of information must be sent to the user, usually embedded in a link
|
||||
*
|
||||
* When the user wants to verify their email address as a next step, both pieces will be required again
|
||||
*
|
||||
* @param bool $requireUniqueUsername whether it must be ensured that the username is unique
|
||||
* @param string $email the email address to register
|
||||
* @param string $password the password for the new account
|
||||
* @param string|null $username (optional) the username that will be displayed
|
||||
* @param callable|null $callback (optional) the function that sends the confirmation email to the user
|
||||
* @return int the ID of the user that has been created (if any)
|
||||
* @throws InvalidEmailException if the email address was invalid
|
||||
* @throws InvalidPasswordException if the password was invalid
|
||||
* @throws UserAlreadyExistsException if a user with the specified email address already exists
|
||||
* @throws DuplicateUsernameException if it was specified that the username must be unique while it was *not*
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
private function createUserInternal($requireUniqueUsername, $email, $password, $username = null, callable $callback = null) {
|
||||
$this->throttle(self::THROTTLE_ACTION_REGISTER);
|
||||
|
||||
ignore_user_abort(true);
|
||||
|
||||
$email = self::validateEmailAddress($email);
|
||||
$password = self::validatePassword($password);
|
||||
|
||||
$username = isset($username) ? trim($username) : null;
|
||||
|
||||
// if the uniqueness of the username is to be ensured
|
||||
if ($requireUniqueUsername) {
|
||||
// count the number of users who do already have that specified username
|
||||
$occurrencesOfUsername = $this->db->selectValue(
|
||||
'SELECT COUNT(*) FROM users WHERE username = ?',
|
||||
[ $username ]
|
||||
);
|
||||
|
||||
// if any user with that username does already exist
|
||||
if ($occurrencesOfUsername > 0) {
|
||||
// cancel the operation and report the violation of this requirement
|
||||
throw new DuplicateUsernameException();
|
||||
}
|
||||
}
|
||||
|
||||
$password = password_hash($password, PASSWORD_DEFAULT);
|
||||
$verified = isset($callback) && is_callable($callback) ? 0 : 1;
|
||||
|
||||
try {
|
||||
$this->db->insert(
|
||||
'users',
|
||||
[
|
||||
'email' => $email,
|
||||
'password' => $password,
|
||||
'username' => $username,
|
||||
'verified' => $verified,
|
||||
'registered' => time()
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (IntegrityConstraintViolationException $e) {
|
||||
// if we have a duplicate entry
|
||||
throw new UserAlreadyExistsException();
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
}
|
||||
|
||||
$newUserId = (int) $this->db->getLastInsertId();
|
||||
|
||||
if ($verified === 0) {
|
||||
$this->createConfirmationRequest($email, $callback);
|
||||
}
|
||||
|
||||
return $newUserId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the requested user data for the account with the specified email address (if any)
|
||||
*
|
||||
* You must never pass untrusted input to the parameter that takes the column list
|
||||
*
|
||||
* @param string $email the email address to look for
|
||||
* @return string the user ID (if an account was found)
|
||||
* @param array $requestColumns the columns to request from the user's record
|
||||
* @return array the user data (if an account was found)
|
||||
* @throws InvalidEmailException if the email address could not be found
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
private function getUserIdByEmailAddress($email) {
|
||||
private function getUserDataByEmailAddress($email, array $requestColumns) {
|
||||
try {
|
||||
$userId = $this->db->selectValue(
|
||||
'SELECT id FROM users WHERE email = ?',
|
||||
$projection = implode(', ', $requestColumns);
|
||||
$userData = $this->db->selectRow(
|
||||
'SELECT ' . $projection . ' FROM users WHERE email = ?',
|
||||
[ $email ]
|
||||
);
|
||||
}
|
||||
@@ -742,8 +835,8 @@ class Auth {
|
||||
throw new DatabaseError();
|
||||
}
|
||||
|
||||
if (!empty($userId)) {
|
||||
return $userId;
|
||||
if (!empty($userData)) {
|
||||
return $userData;
|
||||
}
|
||||
else {
|
||||
throw new InvalidEmailException();
|
||||
|
@@ -26,6 +26,8 @@ class TokenExpiredException extends AuthException {}
|
||||
|
||||
class TooManyRequestsException extends AuthException {}
|
||||
|
||||
class DuplicateUsernameException extends AuthException {}
|
||||
|
||||
class AuthError extends \Exception {}
|
||||
|
||||
class DatabaseError extends AuthError {}
|
||||
|
@@ -138,6 +138,9 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
return 'invalid email address';
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
return 'email not verified';
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
return 'too many requests';
|
||||
}
|
||||
|
Reference in New Issue
Block a user