1
0
mirror of https://github.com/delight-im/PHP-Auth.git synced 2025-08-06 16:16:29 +02:00

105 Commits

Author SHA1 Message Date
Marco
7c842f903e Add 'MySQL Native Driver' as full name of 'mysqlnd' driver in README 2017-03-18 22:35:44 +01:00
Marco
0e2279ecda Document what is required to make library work with other databases 2017-03-18 22:31:30 +01:00
Marco
79db94f500 Add 'mysqlnd' driver for PDO as platform dependency in README 2017-03-18 22:30:19 +01:00
Marco
f38d7bd62c Add PDO as platform dependency in README 2017-03-18 22:25:23 +01:00
Marco
04a2e8ef4e Throw error if 'libmysqlclient' driver is used instead of 'mysqlnd' 2017-03-18 22:21:23 +01:00
Marco
59505479a5 Add class 'WrongMysqlDatabaseDriverError' 2017-03-18 22:13:28 +01:00
Marco
fdcfd6f78c Add class 'DatabaseDriverError' 2017-03-18 22:12:49 +01:00
Marco
20606bc507 Update dependencies 2017-03-18 22:11:05 +01:00
Marco
89a7af17fe Add documentation on how to retrieve status information 2017-02-26 14:15:26 +01:00
Marco
4c084150c4 Update migration guide 2017-02-26 13:49:20 +01:00
Marco
dd51d2c07d Add tests for 'getStatus' and related methods in 'Auth' class 2017-02-26 13:45:26 +01:00
Marco
93477e4e7e Add shorthands for 'getStatus' in 'Auth' class 2017-02-26 13:45:00 +01:00
Marco
d59ac83d13 Refactor array definition in 'authenticateUserInternal' 2017-02-26 13:13:37 +01:00
Marco
9a0036b8a8 Add 'Status' class with constants 2017-02-26 13:05:37 +01:00
Marco
a05d277a2c Read status from 'users' table and provide read access in session 2017-02-26 13:03:52 +01:00
Marco
0839beefcb Improve readability of README 2017-02-26 11:54:41 +01:00
Marco
bf5db38361 Link to 'Migration' from README 2017-02-25 19:13:56 +01:00
Marco
d9be7a4c22 Add table of contents to 'Migration' 2017-02-25 18:59:15 +01:00
Marco
e9bae4a346 Reverse chronological order in 'Migration.md' 2017-02-25 18:49:27 +01:00
Marco
2317423550 Explain that constructor of 'Administration' is for internal use only 2017-02-25 18:40:49 +01:00
Marco
d9dccf8100 Add 'status' column to 'users' table 2017-02-25 18:13:55 +01:00
Marco
26ca48c3b9 Improve language 2017-02-25 18:07:02 +01:00
Marco
9ec74b3b2d Deprecate boolean format for parameter 'rememberDuration' with login 2017-02-25 18:06:07 +01:00
Marco
9c60acec0d Improve code style 2017-02-25 17:58:29 +01:00
Marco
94eeb9dbe0 Fix anchors in README 2017-02-25 17:35:38 +01:00
Marco
4dca8439d1 Add tests for method 'deleteUserById' and related methods 2017-02-25 17:34:36 +01:00
Marco
81bdd79906 Add method 'deleteUserById' and similar methods for email and username 2017-02-25 17:32:35 +01:00
Marco
63144d4dc0 Add private method 'deleteUsersByColumnValue' to 'Administration' 2017-02-25 17:14:24 +01:00
Marco
f06af42f87 Move method 'getUserDataByUsername' from 'Auth' to 'UserManager' 2017-02-25 16:18:51 +01:00
Marco
6c6f34935c Add tests for method 'createUser' in class 'Administration' 2017-02-25 15:45:58 +01:00
Marco
293c231003 Do not offer email verification when creating users as admin 2017-02-25 15:44:37 +01:00
Marco
05d72a849b Improve language 2017-02-21 10:02:49 +01:00
Marco
cf41c9a105 Add methods 'createUser' and 'createUserWithUniqueUsername' 2017-02-21 10:02:03 +01:00
Marco
da4bb583bf Add component for administrative tasks as class 'Administration' 2017-02-21 09:43:30 +01:00
Marco
d99979f270 Move method 'createUserInternal' from class 'Auth' to 'UserManager' 2017-02-21 09:28:42 +01:00
Marco
22872d55bd Import class 'IntegrityConstraintViolationException' in 'UserManager' 2017-02-21 09:27:54 +01:00
Marco
ff6d78942a Move method 'createConfirmationRequest' from 'Auth' to 'UserManager' 2017-02-21 09:26:10 +01:00
Marco
d27005df10 Import class 'Error' in 'UserManager' 2017-02-21 09:22:40 +01:00
Marco
ad2aa84e4a Move method 'validatePassword' from class 'Auth' to 'UserManager' 2017-02-21 09:19:09 +01:00
Marco
f7d50d53ea Move method 'validateEmailAddress' from class 'Auth' to 'UserManager' 2017-02-21 09:17:08 +01:00
Marco
e916c3d07e Move method 'createRandomString' from class 'Auth' to 'UserManager' 2017-02-21 09:13:39 +01:00
Marco
fdeff8a792 Emphasize that class 'UserManager' is for internal use only 2017-02-21 09:03:55 +01:00
Marco
43fa612d67 Move method 'throttle' and its constants from 'Auth' to 'UserManager' 2017-02-21 08:55:10 +01:00
Marco
0b0258f29a Manually require file 'Exceptions.php' in parent class as well 2017-02-21 08:45:27 +01:00
Marco
9252bee030 Let parent class 'UserManager' manage database connection for 'Auth' 2017-02-21 08:40:30 +01:00
Marco
6a15679238 Make class 'Base64' final 2017-02-21 08:28:14 +01:00
Marco
8ab08f41e1 Let autoloader fetch class 'Base64' instead of including it manually 2017-02-21 08:27:19 +01:00
Marco
83464c0be7 Improve description of 'Auth' class 2017-02-21 08:07:38 +01:00
Marco
b5c853388c Make class 'Auth' final 2017-02-21 08:01:41 +01:00
Marco
5585623e08 Let class 'Auth' extend abstract class 'UserManager' 2017-02-21 08:00:26 +01:00
Marco
a7d640154c Add abstract class 'UserManager' 2017-02-21 07:59:49 +01:00
Marco
8acd3a9779 Add tests for method 'loginWithUsername' in class 'Auth' 2017-02-20 21:46:36 +01:00
Marco
374f27176b Add tests for method 'registerWithUniqueUsername' in class 'Auth' 2017-02-20 21:42:48 +01:00
Marco
3cb2284870 Add public method 'loginWithUsername' to class 'Auth' 2017-02-20 21:36:45 +01:00
Marco
690485ba6d Add support for sign in via username to 'authenticateUserInternal' 2017-02-20 21:32:45 +01:00
Marco
495a87d499 No need to check for uniqueness of username if none has been provided 2017-02-20 20:52:02 +01:00
Marco
784030139b Treat empty string or whitespace-only string as non-existent username 2017-02-20 20:48:03 +01:00
Marco
fb6f3d31b8 Add private method 'getUserDataByUsername' to class 'Auth' 2017-02-20 19:57:23 +01:00
Marco
370ecc4933 Add class 'AmbiguousUsernameException' 2017-02-16 09:48:55 +01:00
Marco
da2d282648 Add class 'UnknownUsernameException' 2017-02-16 09:48:04 +01:00
Marco
4aaf85e3cf Add class 'EmailOrUsernameRequiredError' 2017-02-16 09:47:26 +01:00
Marco
f2561a1932 Re-use 'getUserDataByEmailAddress' in 'authenticateUserInternal' 2017-02-16 08:56:44 +01:00
Marco
8cc54473e3 Improve language of parameter name 2017-02-16 08:30:24 +01:00
Marco
f26f2209cd Store email address in session data as found in the database 2017-02-16 08:25:14 +01:00
Marco
188086f2e4 Do not validate password earlier than necessary 2017-02-16 08:18:48 +01:00
Marco
c6213a6081 Change order of parameters in 'authenticateUserInternal' 2017-02-16 08:15:48 +01:00
Marco
c55250c572 Refactor body of 'login' method into new 'authenticateUserInternal' 2017-02-15 18:29:15 +01:00
Marco
dac2850aba Add method 'registerWithUniqueUsername' 2017-02-15 17:19:16 +01:00
Marco
4268e3fcd5 Add support for unique username constraint in 'createUserInternal' 2017-02-15 17:11:56 +01:00
Marco
d579179494 Add class 'DuplicateUsernameException' 2017-02-15 17:06:08 +01:00
Marco
bd02e08f83 Refactor body of 'register' method into new 'createUserInternal' 2017-02-15 16:41:38 +01:00
Marco
d4fe11b844 Improve language 2017-02-15 16:39:17 +01:00
Marco
09fabd4c91 Improve notes in 'General advice' section of README 2017-01-31 23:49:36 +01:00
Marco
4dcf491ad9 Fix language in README 2017-01-30 19:33:04 +01:00
Marco
4f5ff151ef Improve installation instructions by excluding steps for manual setup 2017-01-30 19:31:45 +01:00
Marco
f5027c09e9 Add table of contents to 'Usage' section in README 2017-01-30 19:10:28 +01:00
Marco
6db82d1f65 Add guide on how to store and access additional user information 2017-01-30 19:04:11 +01:00
Marco
f944067aff Set 'ignore_user_abort' to 'true' in method 'register' 2017-01-30 18:48:23 +01:00
Marco
a640e8a5ad Define link to external documentation more precisely 2017-01-30 18:39:21 +01:00
Marco
2aee8a662e Move 'Reading and writing session data' below 'Utilities' in README 2017-01-30 18:37:47 +01:00
Marco
36ef710480 Group several sections in README under 'Accessing user information' 2017-01-30 18:24:44 +01:00
Marco
9187840767 Improve language in README 2017-01-30 18:23:30 +01:00
Marco
6bfa298836 Prevent usage of password reset if email has not been verified yet 2016-12-12 20:58:37 +01:00
Marco
6be456a27a Change 'getUserIdByEmailAddress' to 'getUserDataByEmailAddress' 2016-12-12 20:38:49 +01:00
Marco
78a16d8f50 Improve language 2016-12-04 17:27:58 +01:00
Marco
e669f6f017 Move documentation on 'remember me' to its own section 2016-12-04 17:24:21 +01:00
Marco
5aafd0b009 Improve language 2016-12-04 17:23:09 +01:00
Marco
d53a484c2e Improve language 2016-12-04 17:13:33 +01:00
Marco
07732dcaa9 Change 'remember me' for login from binary choice to custom interval 2016-12-04 17:05:57 +01:00
Marco
f486ab6763 Forget remembered sessions when passwords are reset or changed 2016-12-04 16:54:34 +01:00
Marco
5e331924f6 Increase entropy in tokens for remember directives 2016-12-04 16:52:18 +01:00
Marco
ac95be3714 Use dummy password (instead of no password at all) in examples 2016-12-04 16:49:09 +01:00
Marco
e6c8ae056c Ignore warnings for 'zend.assertions' that cannot be set 2016-12-04 16:46:05 +01:00
Marco
5bac29065d Improve documentation 2016-12-04 16:44:50 +01:00
Marco
36b590eb81 Update dependencies 2016-12-01 13:48:48 +01:00
Marco
5c6a71d921 Update migration guide 2016-09-15 23:52:24 +02:00
Marco
d94243f19d Update examples of how to provide a database connection 2016-09-15 23:51:29 +02:00
Marco
2a2d93f534 Improve exemplary database credentials 2016-09-15 23:45:35 +02:00
Marco
989c7940e5 Rewrite all SQL operations to use 'delight-im/db' instead of raw PDO 2016-09-15 23:43:40 +02:00
Marco
51a5735295 Require 'delight-im/db' as dependency 2016-09-14 16:54:54 +02:00
Marco
e5e465782b Update dependencies 2016-09-14 16:52:01 +02:00
Marco
83caa3e785 Improve list of requirements in README 2016-09-14 16:50:42 +02:00
Marco
f2a1aedf7a Change minimum required PHP version from 5.5.0 to 5.6.0 2016-09-14 16:49:13 +02:00
Marco
5c87e877db Import class 'Delight\Cookie\Session' 2016-09-14 16:42:52 +02:00
Marco
70842b4320 Import class 'Delight\Cookie\Cookie' 2016-09-14 16:42:00 +02:00
12 changed files with 1507 additions and 442 deletions

View File

@@ -12,6 +12,7 @@ CREATE TABLE IF NOT EXISTS `users` (
`email` varchar(249) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
`username` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`status` tinyint(2) unsigned NOT NULL DEFAULT '0',
`verified` tinyint(1) unsigned NOT NULL DEFAULT '0',
`registered` int(10) unsigned NOT NULL,
`last_login` int(10) unsigned DEFAULT NULL,

View File

@@ -1,5 +1,28 @@
# Migration
* [From `v4.x.x` to `v5.x.x`](#from-v4xx-to-v5xx)
* [From `v3.x.x` to `v4.x.x`](#from-v3xx-to-v4xx)
* [From `v2.x.x` to `v3.x.x`](#from-v2xx-to-v3xx)
* [From `v1.x.x` to `v2.x.x`](#from-v1xx-to-v2xx)
## From `v4.x.x` to `v5.x.x`
* The MySQL database schema has changed. Use the statement below to update your database:
```sql
ALTER TABLE `users` ADD COLUMN `status` TINYINT(2) UNSIGNED NOT NULL DEFAULT 0 AFTER `username`;
```
* The two classes `Auth` and `Base64` are now `final`, i.e. they can't be extended anymore, which has never been a good idea, anyway. If you still need to wrap your own methods around these classes, consider [object composition instead of class inheritance](https://en.wikipedia.org/wiki/Composition_over_inheritance).
## From `v3.x.x` to `v4.x.x`
* PHP 5.6.0 or higher is now required.
## From `v2.x.x` to `v3.x.x`
* The license has been changed from the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) to the [MIT License](https://opensource.org/licenses/MIT).
## From `v1.x.x` to `v2.x.x`
* The MySQL schema has been changed from charset `utf8` to charset `utf8mb4` and from collation `utf8_general_ci` to collation `utf8mb4_unicode_ci`. Use the statements below to update the database schema:
@@ -34,7 +57,3 @@
REPAIR TABLE users_throttling;
OPTIMIZE TABLE users_throttling;
```
## From `v2.x.x` to `v3.x.x`
* The license has been changed from the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) to the [MIT License](https://opensource.org/licenses/MIT).

269
README.md
View File

@@ -16,35 +16,66 @@ Completely framework-agnostic and database-agnostic.
## Requirements
* PHP 5.5.0+
* OpenSSL extension
* MySQL 5.5.3+ **or** MariaDB 5.5.23+
* PHP 5.6.0+
* PDO (PHP Data Objects) extension (`pdo`)
* MySQL Native Driver (`mysqlnd`)
* OpenSSL extension (`openssl`)
* MySQL 5.5.3+ **or** MariaDB 5.5.23+ **or** other SQL databases that you create the [schema](Database) for
## 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';
```
* 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)
1. Set up a database and create the required tables:
* [MySQL](Database/MySQL.sql)
## Upgrading
Migrating from an earlier version of this project? See our [upgrade guide](Migration.md) for help.
## 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)
* [Administration (managing users)](#administration-managing-users)
* [Creating new users](#creating-new-users)
* [Deleting users](#deleting-users)
* [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=database;host=localhost;charset=utf8mb4', 'username', 'password');
// $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// $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);
```
@@ -57,7 +88,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`.
### Sign up a new user (register)
### Registration (sign up)
```php
try {
@@ -81,7 +112,9 @@ 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.
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`.
For email verification, you should build an URL with the selector and token and send it to the user, e.g.:
@@ -89,13 +122,13 @@ For email verification, you should build an URL with the selector and token and
$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 `register(...)`. The new user will be active immediately, then.
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.
### Sign in an existing user (login)
### Login (sign in)
```php
try {
$auth->login($_POST['email'], $_POST['password'], ($_POST['remember'] == 1));
$auth->login($_POST['email'], $_POST['password']);
// user is logged in
}
@@ -113,13 +146,9 @@ catch (\Delight\Auth\TooManyRequestsException $e) {
}
```
The third parameter 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 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](#registration-sign-up).
*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.
Set the third parameter to `false` to disable the feature. Otherwise, ask the user if 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 `false` and `true` here. This is optional and the default is `false`.
### Perform email verification
### Email verification
Extract the selector and token from the URL that the user clicked on in the verification email.
@@ -140,7 +169,32 @@ catch (\Delight\Auth\TooManyRequestsException $e) {
}
```
### Reset a password ("forgot password")
### Keeping the user logged in
The third parameter to the `Auth#login` method 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.
```php
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")
```php
try {
@@ -153,6 +207,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
}
@@ -199,7 +256,7 @@ catch (\Delight\Auth\TooManyRequestsException $e) {
}
```
### Change the current user's password
### Changing the current user's password
If a user is currently logged in, they may change their password.
@@ -225,7 +282,9 @@ $auth->logout();
// user has been signed out
```
### Check if the user is signed in
### Accessing user information
#### Login state
```php
if ($auth->isLoggedIn()) {
@@ -238,7 +297,7 @@ else {
A shorthand/alias for this method is `$auth->check()`.
### Get the user's ID
#### User ID
```php
$id = $auth->getUserId();
@@ -248,7 +307,7 @@ If the user is not currently signed in, this returns `null`.
A shorthand/alias for this method is `$auth->id()`.
### Get the user's email address
#### Email address
```php
$email = $auth->getEmail();
@@ -256,7 +315,7 @@ $email = $auth->getEmail();
If the user is not currently signed in, this returns `null`.
### Get the user's display name
#### Display name
```php
$email = $auth->getUsername();
@@ -266,7 +325,35 @@ 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`.
### Check if the user was "remembered"
#### Status information
```php
if ($auth->isNormal()) {
// user is in default state
}
if ($auth->isArchived()) {
// user has been archived
}
if ($auth->isBanned()) {
// user has been banned
}
if ($auth->isLocked()) {
// user has been locked
}
if ($auth->isPendingReview()) {
// user is pending review
}
if ($auth->isSuspended()) {
// user has been suspended
}
```
#### Checking whether the user was "remembered"
```php
if ($auth->isRemembered()) {
@@ -279,31 +366,123 @@ else {
If the user is not currently signed in, this returns `null`.
### Get the user's IP address
#### IP address
```php
$ip = $auth->getIpAddress();
```
### Read and write 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'];
}
```
### 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
```php
try {
$userId = $auth->admin()->createUser($_POST['email'], $_POST['password'], $_POST['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
}
```
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:
```php
try {
$auth->admin()->deleteUserById($_POST['id']);
}
catch (\Delight\Auth\UnknownIdException $e) {
// unknown ID
}
```
Deleting users by their email address:
```php
try {
$auth->admin()->deleteUserByEmail($_POST['email']);
}
catch (\Delight\Auth\InvalidEmailException $e) {
// unknown email address
}
```
Deleting users by their username:
```php
try {
$auth->admin()->deleteUserByUsername($_POST['username']);
}
catch (\Delight\Auth\UnknownUsernameException $e) {
// unknown username
}
catch (\Delight\Auth\AmbiguousUsernameException $e) {
// ambiguous username
}
```
### Utilities
#### Create a random string
#### Creating a random string
```php
$length = 24;
$randomStr = \Delight\Auth\Auth::createRandomString($length);
```
#### Create a UUID v4 as per RFC 4122
#### Creating a UUID v4 as per RFC 4122
```php
$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
@@ -349,12 +528,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.

View File

@@ -2,9 +2,10 @@
"name": "delight-im/auth",
"description": "Authentication for PHP. Simple, lightweight and secure.",
"require": {
"php": ">=5.5.0",
"php": ">=5.6.0",
"ext-openssl": "*",
"delight-im/cookie": "^2.0"
"delight-im/cookie": "^2.1",
"delight-im/db": "^1.2"
},
"type": "library",
"keywords": [ "auth", "authentication", "login", "security" ],

60
composer.lock generated
View File

@@ -4,26 +4,25 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"hash": "22e56875c7a1386807d5cf6ae01f50fa",
"content-hash": "b914ccd7ac15e1519d7a04b55dbe725e",
"content-hash": "c075bec19490fc0e972be01cdd02d59b",
"packages": [
{
"name": "delight-im/cookie",
"version": "v2.0.0",
"version": "v2.1.1",
"source": {
"type": "git",
"url": "https://github.com/delight-im/PHP-Cookie.git",
"reference": "a746f4096885b6715a640a2122b1c21324624f8f"
"reference": "22f2c19750a6ad3dbf69a8ef3ea0e454a8e064fa"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/delight-im/PHP-Cookie/zipball/a746f4096885b6715a640a2122b1c21324624f8f",
"reference": "a746f4096885b6715a640a2122b1c21324624f8f",
"url": "https://api.github.com/repos/delight-im/PHP-Cookie/zipball/22f2c19750a6ad3dbf69a8ef3ea0e454a8e064fa",
"reference": "22f2c19750a6ad3dbf69a8ef3ea0e454a8e064fa",
"shasum": ""
},
"require": {
"delight-im/http": "^2.0",
"php": ">=5.3.0"
"php": ">=5.6.0"
},
"type": "library",
"autoload": {
@@ -46,7 +45,48 @@
"samesite",
"xss"
],
"time": "2016-07-21 15:20:20"
"time": "2016-12-18T20:22:46+00:00"
},
{
"name": "delight-im/db",
"version": "v1.2.0",
"source": {
"type": "git",
"url": "https://github.com/delight-im/PHP-DB.git",
"reference": "df99ef7c2e86c7ce206647ffe8ba74447c075b57"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/delight-im/PHP-DB/zipball/df99ef7c2e86c7ce206647ffe8ba74447c075b57",
"reference": "df99ef7c2e86c7ce206647ffe8ba74447c075b57",
"shasum": ""
},
"require": {
"ext-pdo": "*",
"php": ">=5.6.0"
},
"type": "library",
"autoload": {
"psr-4": {
"Delight\\Db\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "Safe and convenient SQL database access in a driver-agnostic way",
"homepage": "https://github.com/delight-im/PHP-DB",
"keywords": [
"database",
"mysql",
"pdo",
"pgsql",
"postgresql",
"sql",
"sqlite"
],
"time": "2017-03-18T20:51:59+00:00"
},
{
"name": "delight-im/http",
@@ -82,7 +122,7 @@
"http",
"https"
],
"time": "2016-07-21 15:05:01"
"time": "2016-07-21T15:05:01+00:00"
}
],
"packages-dev": [],
@@ -92,7 +132,7 @@
"prefer-stable": false,
"prefer-lowest": false,
"platform": {
"php": ">=5.5.0",
"php": ">=5.6.0",
"ext-openssl": "*"
},
"platform-dev": []

144
src/Administration.php Normal file
View File

@@ -0,0 +1,144 @@
<?php
/*
* PHP-Auth (https://github.com/delight-im/PHP-Auth)
* Copyright (c) delight.im (https://www.delight.im/)
* Licensed under the MIT License (https://opensource.org/licenses/MIT)
*/
namespace Delight\Auth;
use Delight\Db\PdoDatabase;
use Delight\Db\Throwable\Error;
require_once __DIR__ . '/Exceptions.php';
/** Component that can be used for administrative tasks by privileged and authorized users */
final class Administration extends UserManager {
/**
* @internal
*
* @param PdoDatabase $databaseConnection the database connection to operate on
*/
public function __construct(PdoDatabase $databaseConnection) {
parent::__construct($databaseConnection);
}
/**
* Creates a new user
*
* @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
* @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 AuthError if an internal problem occurred (do *not* catch)
*/
public function createUser($email, $password, $username = null) {
return $this->createUserInternal(false, $email, $password, $username, null);
}
/**
* Creates a new user while ensuring 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
* @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 createUserWithUniqueUsername($email, $password, $username = null) {
return $this->createUserInternal(true, $email, $password, $username, null);
}
/**
* Deletes the user with the specified ID
*
* This action cannot be undone
*
* @param int $id the ID of the user to delete
* @throws UnknownIdException if no user with the specified ID has been found
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function deleteUserById($id) {
$numberOfDeletedUsers = $this->deleteUsersByColumnValue('id', (int) $id);
if ($numberOfDeletedUsers === 0) {
throw new UnknownIdException();
}
}
/**
* Deletes the user with the specified email address
*
* This action cannot be undone
*
* @param string $email the email address of the user to delete
* @throws InvalidEmailException if no user with the specified email address has been found
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function deleteUserByEmail($email) {
$email = self::validateEmailAddress($email);
$numberOfDeletedUsers = $this->deleteUsersByColumnValue('email', $email);
if ($numberOfDeletedUsers === 0) {
throw new InvalidEmailException();
}
}
/**
* Deletes the user with the specified username
*
* This action cannot be undone
*
* @param string $username the username of the user to delete
* @throws UnknownUsernameException if no user with the specified username has been found
* @throws AmbiguousUsernameException if multiple users with the specified username have been found
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function deleteUserByUsername($username) {
$userData = $this->getUserDataByUsername(
trim($username),
[ 'id' ]
);
$this->deleteUsersByColumnValue('id', (int) $userData['id']);
}
protected function throttle($actionType, $customSelector = null) {
// do nothing
}
/**
* Deletes all existing users where the column with the specified name has the given value
*
* You must never pass untrusted input to the parameter that takes the column name
*
* @param string $columnName the name of the column to filter by
* @param mixed $columnValue the value to look for in the selected column
* @return int the number of deleted users
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
private function deleteUsersByColumnValue($columnName, $columnValue) {
try {
return $this->db->delete(
'users',
[
$columnName => $columnValue
]
);
}
catch (Error $e) {
throw new DatabaseError();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -8,7 +8,7 @@
namespace Delight\Auth;
class Base64 {
final class Base64 {
const SPECIAL_CHARS_ORIGINAL = '+/=';
const SPECIAL_CHARS_SAFE = '._-';

View File

@@ -10,8 +10,12 @@ namespace Delight\Auth;
class AuthException extends \Exception {}
class UnknownIdException extends AuthException {}
class InvalidEmailException extends AuthException {}
class UnknownUsernameException extends AuthException {}
class InvalidPasswordException extends AuthException {}
class EmailNotVerifiedException extends AuthException {}
@@ -26,10 +30,20 @@ class TokenExpiredException extends AuthException {}
class TooManyRequestsException extends AuthException {}
class DuplicateUsernameException extends AuthException {}
class AmbiguousUsernameException extends AuthException {}
class AuthError extends \Exception {}
class DatabaseError extends AuthError {}
class DatabaseDriverError extends DatabaseError {}
class WrongMysqlDatabaseDriverError extends DatabaseDriverError {}
class MissingCallbackError extends AuthError {}
class HeadersAlreadySentError extends AuthError {}
class EmailOrUsernameRequiredError extends AuthError {}

20
src/Status.php Normal file
View File

@@ -0,0 +1,20 @@
<?php
/*
* PHP-Auth (https://github.com/delight-im/PHP-Auth)
* Copyright (c) delight.im (https://www.delight.im/)
* Licensed under the MIT License (https://opensource.org/licenses/MIT)
*/
namespace Delight\Auth;
final class Status {
const NORMAL = 0;
const ARCHIVED = 1;
const BANNED = 2;
const LOCKED = 3;
const PENDING_REVIEW = 4;
const SUSPENDED = 5;
}

310
src/UserManager.php Normal file
View File

@@ -0,0 +1,310 @@
<?php
/*
* PHP-Auth (https://github.com/delight-im/PHP-Auth)
* Copyright (c) delight.im (https://www.delight.im/)
* Licensed under the MIT License (https://opensource.org/licenses/MIT)
*/
namespace Delight\Auth;
use Delight\Db\PdoDatabase;
use Delight\Db\PdoDsn;
use Delight\Db\Throwable\Error;
use Delight\Db\Throwable\IntegrityConstraintViolationException;
require_once __DIR__ . '/Exceptions.php';
/**
* Abstract base class for components implementing user management
*
* @internal
*/
abstract class UserManager {
const THROTTLE_ACTION_LOGIN = 'login';
const THROTTLE_ACTION_REGISTER = 'register';
const THROTTLE_ACTION_CONSUME_TOKEN = 'confirm_email';
/** @var PdoDatabase the database connection to operate on */
protected $db;
/**
* Creates a random string with the given maximum length
*
* With the default parameter, the output should contain at least as much randomness as a UUID
*
* @param int $maxLength the maximum length of the output string (integer multiple of 4)
* @return string the new random string
*/
public static function createRandomString($maxLength = 24) {
// calculate how many bytes of randomness we need for the specified string length
$bytes = floor(intval($maxLength) / 4) * 3;
// get random data
$data = openssl_random_pseudo_bytes($bytes);
// return the Base64-encoded result
return Base64::encode($data, true);
}
/**
* @param PdoDatabase|PdoDsn|\PDO $databaseConnection the database connection to operate on
*/
protected function __construct($databaseConnection) {
if ($databaseConnection instanceof PdoDatabase) {
$this->db = $databaseConnection;
}
elseif ($databaseConnection instanceof PdoDsn) {
$this->db = PdoDatabase::fromDsn($databaseConnection);
}
elseif ($databaseConnection instanceof \PDO) {
$this->db = PdoDatabase::fromPdo($databaseConnection, true);
}
else {
$this->db = null;
throw new \InvalidArgumentException('The database connection must be an instance of either `PdoDatabase`, `PdoDsn` or `PDO`');
}
$this->db->addOnConnectListener(function (PdoDatabase $db) {
// if a MySQL database is used
if ($db->getDriverName() === 'MySQL') {
// if the required MySQL Native Driver (mysqlnd) is not used (but instead the older MySQL Client Library (libmysqlclient))
if (\extension_loaded('mysqlnd') === false && \stripos($db->getClientVersion(), 'mysqlnd') === false) {
throw new WrongMysqlDatabaseDriverError('You must use PDO with the newer \'mysqlnd\' driver instead of the older \'libmysqlclient\' driver');
}
}
});
}
/**
* 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 has been invalid
* @throws InvalidPasswordException if the password has been 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)
*/
protected 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 supplied username is the empty string or has consisted of whitespace only
if ($username === '') {
// this actually means that there is no username
$username = null;
}
// if the uniqueness of the username is to be ensured
if ($requireUniqueUsername) {
// if a username has actually been provided
if ($username !== null) {
// 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()
]
);
}
// if we have a duplicate entry
catch (IntegrityConstraintViolationException $e) {
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 username (if any)
*
* You must never pass untrusted input to the parameter that takes the column list
*
* @param string $username the username to look for
* @param array $requestedColumns the columns to request from the user's record
* @return array the user data (if an account was found unambiguously)
* @throws UnknownUsernameException if no user with the specified username has been found
* @throws AmbiguousUsernameException if multiple users with the specified username have been found
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
protected function getUserDataByUsername($username, array $requestedColumns) {
try {
$projection = implode(', ', $requestedColumns);
$users = $this->db->select(
'SELECT ' . $projection . ' FROM users WHERE username = ? LIMIT 0, 2',
[ $username ]
);
}
catch (Error $e) {
throw new DatabaseError();
}
if (empty($users)) {
throw new UnknownUsernameException();
}
else {
if (count($users) === 1) {
return $users[0];
}
else {
throw new AmbiguousUsernameException();
}
}
}
/**
* Validates an email address
*
* @param string $email the email address to validate
* @return string the sanitized email address
* @throws InvalidEmailException if the email address has been invalid
*/
protected static function validateEmailAddress($email) {
if (empty($email)) {
throw new InvalidEmailException();
}
$email = trim($email);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidEmailException();
}
return $email;
}
/**
* Validates a password
*
* @param string $password the password to validate
* @return string the sanitized password
* @throws InvalidPasswordException if the password has been invalid
*/
protected static function validatePassword($password) {
if (empty($password)) {
throw new InvalidPasswordException();
}
$password = trim($password);
if (strlen($password) < 1) {
throw new InvalidPasswordException();
}
return $password;
}
/**
* Throttles the specified action for the user to protect against too many requests
*
* @param string $actionType one of the constants from this class starting with `THROTTLE_ACTION_`
* @param mixed|null $customSelector a custom selector to use for throttling (if any), otherwise the IP address will be used
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
abstract protected function throttle($actionType, $customSelector = null);
/**
* Creates a request for email confirmation
*
* 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 verify
* @param callable $callback the function that sends the confirmation email to the user
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
private function createConfirmationRequest($email, callable $callback) {
$selector = self::createRandomString(16);
$token = self::createRandomString(16);
$tokenHashed = password_hash($token, PASSWORD_DEFAULT);
// the request shall be valid for one day
$expires = time() + 60 * 60 * 24;
try {
$this->db->insert(
'users_confirmations',
[
'email' => $email,
'selector' => $selector,
'token' => $tokenHashed,
'expires' => $expires
]
);
}
catch (Error $e) {
throw new DatabaseError();
}
if (isset($callback) && is_callable($callback)) {
$callback($selector, $token);
}
else {
throw new MissingCallbackError();
}
}
}

View File

@@ -12,15 +12,14 @@ ini_set('display_errors', 'stdout');
// enable assertions
ini_set('assert.active', 1);
ini_set('zend.assertions', 1);
@ini_set('zend.assertions', 1);
ini_set('assert.exception', 1);
header('Content-type: text/html; charset=utf-8');
require __DIR__.'/../vendor/autoload.php';
$db = new PDO('mysql:dbname=php_auth;host=127.0.0.1;charset=utf8mb4', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db = new PDO('mysql:dbname=php_auth;host=127.0.0.1;charset=utf8mb4', 'root', 'monkey');
$auth = new \Delight\Auth\Auth($db);
@@ -39,14 +38,37 @@ function processRequestData(\Delight\Auth\Auth $auth) {
if (isset($_POST)) {
if (isset($_POST['action'])) {
if ($_POST['action'] === 'login') {
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;
}
try {
$auth->login($_POST['email'], $_POST['password'], ($_POST['remember'] == 1));
if (isset($_POST['email'])) {
$auth->login($_POST['email'], $_POST['password'], $rememberDuration);
}
elseif (isset($_POST['username'])) {
$auth->loginWithUsername($_POST['username'], $_POST['password'], $rememberDuration);
}
else {
return 'either email address or username required';
}
return 'ok';
}
catch (\Delight\Auth\InvalidEmailException $e) {
return 'wrong email address';
}
catch (\Delight\Auth\UnknownUsernameException $e) {
return 'unknown username';
}
catch (\Delight\Auth\AmbiguousUsernameException $e) {
return 'ambiguous username';
}
catch (\Delight\Auth\InvalidPasswordException $e) {
return 'wrong password';
}
@@ -78,7 +100,16 @@ function processRequestData(\Delight\Auth\Auth $auth) {
$callback = null;
}
return $auth->register($_POST['email'], $_POST['password'], $_POST['username'], $callback);
if (!isset($_POST['require_unique_username'])) {
$_POST['require_unique_username'] = '0';
}
if ($_POST['require_unique_username'] == 0) {
return $auth->register($_POST['email'], $_POST['password'], $_POST['username'], $callback);
}
else {
return $auth->registerWithUniqueUsername($_POST['email'], $_POST['password'], $_POST['username'], $callback);
}
}
catch (\Delight\Auth\InvalidEmailException $e) {
return 'invalid email address';
@@ -87,7 +118,10 @@ function processRequestData(\Delight\Auth\Auth $auth) {
return 'invalid password';
}
catch (\Delight\Auth\UserAlreadyExistsException $e) {
return 'user already exists';
return 'email address already exists';
}
catch (\Delight\Auth\DuplicateUsernameException $e) {
return 'username already exists';
}
catch (\Delight\Auth\TooManyRequestsException $e) {
return 'too many requests';
@@ -130,6 +164,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';
}
@@ -171,6 +208,66 @@ function processRequestData(\Delight\Auth\Auth $auth) {
return 'ok';
}
else if ($_POST['action'] === 'admin.createUser') {
try {
if (!isset($_POST['require_unique_username'])) {
$_POST['require_unique_username'] = '0';
}
if ($_POST['require_unique_username'] == 0) {
return $auth->admin()->createUser($_POST['email'], $_POST['password'], $_POST['username']);
}
else {
return $auth->admin()->createUserWithUniqueUsername($_POST['email'], $_POST['password'], $_POST['username']);
}
}
catch (\Delight\Auth\InvalidEmailException $e) {
return 'invalid email address';
}
catch (\Delight\Auth\InvalidPasswordException $e) {
return 'invalid password';
}
catch (\Delight\Auth\UserAlreadyExistsException $e) {
return 'email address already exists';
}
catch (\Delight\Auth\DuplicateUsernameException $e) {
return 'username already exists';
}
}
else if ($_POST['action'] === 'admin.deleteUser') {
if (isset($_POST['id'])) {
try {
$auth->admin()->deleteUserById($_POST['id']);
}
catch (\Delight\Auth\UnknownIdException $e) {
return 'unknown ID';
}
}
elseif (isset($_POST['email'])) {
try {
$auth->admin()->deleteUserByEmail($_POST['email']);
}
catch (\Delight\Auth\InvalidEmailException $e) {
return 'unknown email address';
}
}
elseif (isset($_POST['username'])) {
try {
$auth->admin()->deleteUserByUsername($_POST['username']);
}
catch (\Delight\Auth\UnknownUsernameException $e) {
return 'unknown username';
}
catch (\Delight\Auth\AmbiguousUsernameException $e) {
return 'ambiguous username';
}
}
else {
return 'either ID, email or username required';
}
return 'ok';
}
else {
throw new Exception('Unexpected action: '.$_POST['action']);
}
@@ -205,6 +302,12 @@ function showDebugData(\Delight\Auth\Auth $auth, $result) {
var_dump($auth->getEmail());
echo '$auth->getUsername()'."\t\t\t";
var_dump($auth->getUsername());
echo '$auth->getStatus()'."\t\t\t";
echo convertStatusToText($auth);
echo ' / ';
var_dump($auth->getStatus());
echo '$auth->isRemembered()'."\t\t\t";
var_dump($auth->isRemembered());
echo '$auth->getIpAddress()'."\t\t\t";
@@ -219,6 +322,36 @@ function showDebugData(\Delight\Auth\Auth $auth, $result) {
echo '</pre>';
}
function convertStatusToText(\Delight\Auth\Auth $auth) {
if ($auth->isLoggedIn() === true) {
if ($auth->getStatus() === \Delight\Auth\Status::NORMAL && $auth->isNormal()) {
return 'normal';
}
elseif ($auth->getStatus() === \Delight\Auth\Status::ARCHIVED && $auth->isArchived()) {
return 'archived';
}
elseif ($auth->getStatus() === \Delight\Auth\Status::BANNED && $auth->isBanned()) {
return 'banned';
}
elseif ($auth->getStatus() === \Delight\Auth\Status::LOCKED && $auth->isLocked()) {
return 'locked';
}
elseif ($auth->getStatus() === \Delight\Auth\Status::PENDING_REVIEW && $auth->isPendingReview()) {
return 'pending review';
}
elseif ($auth->getStatus() === \Delight\Auth\Status::SUSPENDED && $auth->isSuspended()) {
return 'suspended';
}
}
elseif ($auth->isLoggedIn() === false) {
if ($auth->getStatus() === null) {
return 'none';
}
}
throw new Exception('Invalid status `' . $auth->getStatus() . '`');
}
function showGeneralForm() {
echo '<form action="" method="get" accept-charset="utf-8">';
echo '<button type="submit">Refresh</button>';
@@ -244,15 +377,28 @@ function showAuthenticatedUserForm() {
function showGuestUserForm() {
showGeneralForm();
echo '<h1>Public</h1>';
echo '<form action="" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="action" value="login" />';
echo '<input type="text" name="email" placeholder="Email" /> ';
echo '<input type="text" name="password" placeholder="Password" /> ';
echo '<select name="remember" size="1">';
echo '<option value="0">Remember (28 days)? — No</option>';
echo '<option value="1">Remember (28 days)? — Yes</option>';
echo '<option value="0">Remember (keep logged in)? — No</option>';
echo '<option value="1">Remember (keep logged in)? — Yes</option>';
echo '</select> ';
echo '<button type="submit">Login</button>';
echo '<button type="submit">Log in with email address</button>';
echo '</form>';
echo '<form action="" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="action" value="login" />';
echo '<input type="text" name="username" placeholder="Username" /> ';
echo '<input type="text" name="password" placeholder="Password" /> ';
echo '<select name="remember" size="1">';
echo '<option value="0">Remember (keep logged in)? — No</option>';
echo '<option value="1">Remember (keep logged in)? — Yes</option>';
echo '</select> ';
echo '<button type="submit">Log in with username</button>';
echo '</form>';
echo '<form action="" method="post" accept-charset="utf-8">';
@@ -264,6 +410,10 @@ function showGuestUserForm() {
echo '<option value="0">Require email confirmation? — No</option>';
echo '<option value="1">Require email confirmation? — Yes</option>';
echo '</select> ';
echo '<select name="require_unique_username" size="1">';
echo '<option value="0">Username — Any</option>';
echo '<option value="1">Username — Unique</option>';
echo '</select> ';
echo '<button type="submit">Register</button>';
echo '</form>';
@@ -287,4 +437,36 @@ function showGuestUserForm() {
echo '<input type="text" name="password" placeholder="New password" /> ';
echo '<button type="submit">Reset password</button>';
echo '</form>';
echo '<h1>Administration</h1>';
echo '<form action="" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="action" value="admin.createUser" />';
echo '<input type="text" name="email" placeholder="Email" /> ';
echo '<input type="text" name="password" placeholder="Password" /> ';
echo '<input type="text" name="username" placeholder="Username (optional)" /> ';
echo '<select name="require_unique_username" size="1">';
echo '<option value="0">Username — Any</option>';
echo '<option value="1">Username — Unique</option>';
echo '</select> ';
echo '<button type="submit">Create user</button>';
echo '</form>';
echo '<form action="" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="action" value="admin.deleteUser" />';
echo '<input type="text" name="id" placeholder="ID" /> ';
echo '<button type="submit">Delete user by ID</button>';
echo '</form>';
echo '<form action="" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="action" value="admin.deleteUser" />';
echo '<input type="text" name="email" placeholder="Email" /> ';
echo '<button type="submit">Delete user by email</button>';
echo '</form>';
echo '<form action="" method="post" accept-charset="utf-8">';
echo '<input type="hidden" name="action" value="admin.deleteUser" />';
echo '<input type="text" name="username" placeholder="Username" /> ';
echo '<button type="submit">Delete user by username</button>';
echo '</form>';
}