mirror of
https://github.com/delight-im/PHP-Auth.git
synced 2025-08-08 09:06:29 +02:00
Compare commits
76 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
47afa1c411 | ||
|
26cb41e992 | ||
|
ee485f99ab | ||
|
8fc0b98493 | ||
|
45553afaea | ||
|
7834455e16 | ||
|
e49adf0150 | ||
|
0fb653d6e0 | ||
|
dc233d9d46 | ||
|
7c842f903e | ||
|
0e2279ecda | ||
|
79db94f500 | ||
|
f38d7bd62c | ||
|
04a2e8ef4e | ||
|
59505479a5 | ||
|
fdcfd6f78c | ||
|
20606bc507 | ||
|
89a7af17fe | ||
|
4c084150c4 | ||
|
dd51d2c07d | ||
|
93477e4e7e | ||
|
d59ac83d13 | ||
|
9a0036b8a8 | ||
|
a05d277a2c | ||
|
0839beefcb | ||
|
bf5db38361 | ||
|
d9be7a4c22 | ||
|
e9bae4a346 | ||
|
2317423550 | ||
|
d9dccf8100 | ||
|
26ca48c3b9 | ||
|
9ec74b3b2d | ||
|
9c60acec0d | ||
|
94eeb9dbe0 | ||
|
4dca8439d1 | ||
|
81bdd79906 | ||
|
63144d4dc0 | ||
|
f06af42f87 | ||
|
6c6f34935c | ||
|
293c231003 | ||
|
05d72a849b | ||
|
cf41c9a105 | ||
|
da4bb583bf | ||
|
d99979f270 | ||
|
22872d55bd | ||
|
ff6d78942a | ||
|
d27005df10 | ||
|
ad2aa84e4a | ||
|
f7d50d53ea | ||
|
e916c3d07e | ||
|
fdeff8a792 | ||
|
43fa612d67 | ||
|
0b0258f29a | ||
|
9252bee030 | ||
|
6a15679238 | ||
|
8ab08f41e1 | ||
|
83464c0be7 | ||
|
b5c853388c | ||
|
5585623e08 | ||
|
a7d640154c | ||
|
8acd3a9779 | ||
|
374f27176b | ||
|
3cb2284870 | ||
|
690485ba6d | ||
|
495a87d499 | ||
|
784030139b | ||
|
fb6f3d31b8 | ||
|
370ecc4933 | ||
|
da2d282648 | ||
|
4aaf85e3cf | ||
|
f2561a1932 | ||
|
8cc54473e3 | ||
|
f26f2209cd | ||
|
188086f2e4 | ||
|
c6213a6081 | ||
|
c55250c572 |
@@ -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,
|
||||
|
56
Database/SQLite.sql
Normal file
56
Database/SQLite.sql
Normal file
@@ -0,0 +1,56 @@
|
||||
-- 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)
|
||||
|
||||
PRAGMA foreign_keys = OFF;
|
||||
|
||||
CREATE TABLE "users" (
|
||||
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0),
|
||||
"email" VARCHAR(249) NOT NULL,
|
||||
"password" VARCHAR(255) NOT NULL,
|
||||
"username" VARCHAR(100) DEFAULT NULL,
|
||||
"status" INTEGER NOT NULL CHECK ("status" >= 0) DEFAULT "0",
|
||||
"verified" INTEGER NOT NULL CHECK ("verified" >= 0) DEFAULT "0",
|
||||
"registered" INTEGER NOT NULL CHECK ("registered" >= 0),
|
||||
"last_login" INTEGER CHECK ("last_login" >= 0) DEFAULT NULL,
|
||||
CONSTRAINT "email" UNIQUE ("email")
|
||||
);
|
||||
|
||||
CREATE TABLE "users_confirmations" (
|
||||
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0),
|
||||
"email" VARCHAR(249) NOT NULL,
|
||||
"selector" VARCHAR(16) NOT NULL,
|
||||
"token" VARCHAR(255) NOT NULL,
|
||||
"expires" INTEGER NOT NULL CHECK ("expires" >= 0),
|
||||
CONSTRAINT "selector" UNIQUE ("selector")
|
||||
);
|
||||
CREATE INDEX "users_confirmations.email_expires" ON "users_confirmations" ("email", "expires");
|
||||
|
||||
CREATE TABLE "users_remembered" (
|
||||
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0),
|
||||
"user" INTEGER NOT NULL CHECK ("user" >= 0),
|
||||
"selector" VARCHAR(24) NOT NULL,
|
||||
"token" VARCHAR(255) NOT NULL,
|
||||
"expires" INTEGER NOT NULL CHECK ("expires" >= 0),
|
||||
CONSTRAINT "selector" UNIQUE ("selector")
|
||||
);
|
||||
CREATE INDEX "users_remembered.user" ON "users_remembered" ("user");
|
||||
|
||||
CREATE TABLE "users_resets" (
|
||||
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0),
|
||||
"user" INTEGER NOT NULL CHECK ("user" >= 0),
|
||||
"selector" VARCHAR(20) NOT NULL,
|
||||
"token" VARCHAR(255) NOT NULL,
|
||||
"expires" INTEGER NOT NULL CHECK ("expires" >= 0),
|
||||
CONSTRAINT "selector" UNIQUE ("selector")
|
||||
);
|
||||
CREATE INDEX "users_resets.user_expires" ON "users_resets" ("user", "expires");
|
||||
|
||||
CREATE TABLE "users_throttling" (
|
||||
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0),
|
||||
"action_type" TEXT NOT NULL CHECK ("action_type" IN ("login", "register", "confirm_email")),
|
||||
"selector" VARCHAR(44) DEFAULT NULL,
|
||||
"time_bucket" INTEGER NOT NULL CHECK ("time_bucket" >= 0),
|
||||
"attempts" INTEGER NOT NULL CHECK ("attempts" >= 0) DEFAULT "1",
|
||||
CONSTRAINT "action_type_selector_time_bucket" UNIQUE ("action_type", "selector", "time_bucket")
|
||||
);
|
31
Migration.md
31
Migration.md
@@ -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,11 +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).
|
||||
|
||||
## From `v3.x.x` to `v4.x.x`
|
||||
|
||||
* PHP 5.6.0 or higher is now required.
|
||||
|
187
README.md
187
README.md
@@ -17,8 +17,10 @@ Completely framework-agnostic and database-agnostic.
|
||||
## Requirements
|
||||
|
||||
* PHP 5.6.0+
|
||||
* PDO (PHP Data Objects) extension (`pdo`)
|
||||
* MySQL Native Driver (`mysqlnd`) **or** SQLite driver (`sqlite`)
|
||||
* OpenSSL extension (`openssl`)
|
||||
* MySQL 5.5.3+ **or** MariaDB 5.5.23+
|
||||
* MySQL 5.5.3+ **or** MariaDB 5.5.23+ **or** SQLite 3.14.1+ **or** other SQL databases that you create the [schema](Database) for
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -37,6 +39,11 @@ Completely framework-agnostic and database-agnostic.
|
||||
1. Set up a database and create the required tables:
|
||||
|
||||
* [MySQL](Database/MySQL.sql)
|
||||
* [SQLite](Database/SQLite.sql)
|
||||
|
||||
## Upgrading
|
||||
|
||||
Migrating from an earlier version of this project? See our [upgrade guide](Migration.md) for help.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -56,6 +63,9 @@ Completely framework-agnostic and database-agnostic.
|
||||
* [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)
|
||||
@@ -66,7 +76,13 @@ Completely framework-agnostic and database-agnostic.
|
||||
```php
|
||||
// $db = new PDO('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
|
||||
// or
|
||||
// $db = new PDO('sqlite:../Databases/my-database.sqlite');
|
||||
|
||||
// or
|
||||
|
||||
// $db = new \Delight\Db\PdoDsn('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
|
||||
// or
|
||||
// $db = new \Delight\Db\PdoDsn('sqlite:../Databases/my-database.sqlite');
|
||||
|
||||
$auth = new \Delight\Auth\Auth($db);
|
||||
```
|
||||
@@ -103,9 +119,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`, if necessary.
|
||||
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.:
|
||||
|
||||
@@ -137,6 +153,8 @@ catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
}
|
||||
```
|
||||
|
||||
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).
|
||||
|
||||
### Email verification
|
||||
|
||||
Extract the selector and token from the URL that the user clicked on in the verification email.
|
||||
@@ -314,6 +332,34 @@ 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`.
|
||||
|
||||
#### 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
|
||||
@@ -358,6 +404,73 @@ Here's how to use this library with your own tables for custom user information
|
||||
}
|
||||
```
|
||||
|
||||
### 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
|
||||
|
||||
#### Creating a random string
|
||||
@@ -377,41 +490,41 @@ $uuid = \Delight\Auth\Auth::createUuid();
|
||||
|
||||
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
|
||||
## Frequently asked questions
|
||||
|
||||
* registration
|
||||
* secure password storage using the bcrypt algorithm
|
||||
* email verification through message with confirmation link
|
||||
* assurance of unique email addresses
|
||||
* customizable password requirements and enforcement
|
||||
* optional usernames with customizable restrictions
|
||||
* login
|
||||
* keeping the user logged in for a long time (beyond expiration of browser session) via secure long-lived token ("remember me")
|
||||
* account management
|
||||
* change password
|
||||
* tracking the time of sign up and last login
|
||||
* check if user has been logged in via "remember me" cookie
|
||||
* logout
|
||||
* full and reliable destruction of session
|
||||
* session management
|
||||
* protection against session hijacking via cross-site scripting (XSS)
|
||||
* do *not* permit script-based access to cookies
|
||||
* restrict cookies to HTTPS to prevent session hijacking via non-secure HTTP
|
||||
* protection against session fixation attacks
|
||||
* protection against cross-site request forgery (CSRF)
|
||||
* works automatically (i.e. no need for CSRF tokens everywhere)
|
||||
* do *not* use HTTP `GET` requests for "dangerous" operations
|
||||
* throttling
|
||||
* per IP address
|
||||
* per account
|
||||
* enhanced HTTP security
|
||||
* prevents clickjacking
|
||||
* prevent content sniffing (MIME sniffing)
|
||||
* disables caching of potentially sensitive data
|
||||
* miscellaneous
|
||||
* ready for both IPv4 and IPv6
|
||||
* works behind proxy servers as well
|
||||
* privacy-friendly (e.g. does *not* save readable IP addresses)
|
||||
### What about password hashing?
|
||||
|
||||
Any password or authentication token is automatically hashed using the ["bcrypt"](https://en.wikipedia.org/wiki/Bcrypt) function, which is based on the ["Blowfish" cipher](https://en.wikipedia.org/wiki/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"](https://en.wikipedia.org/wiki/Salt_(cryptography)) 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](https://en.wikipedia.org/wiki/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:
|
||||
|
||||
```php
|
||||
function isPasswordAllowed($password) {
|
||||
if (strlen($password) < 8) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$blacklist = [ 'password1', '123456', 'qwerty' ];
|
||||
|
||||
if (in_array($password, $blacklist)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isPasswordAllowed($password)) {
|
||||
$auth->register($email, $password);
|
||||
}
|
||||
```
|
||||
|
||||
## Exceptions
|
||||
|
||||
|
@@ -5,7 +5,7 @@
|
||||
"php": ">=5.6.0",
|
||||
"ext-openssl": "*",
|
||||
"delight-im/cookie": "^2.1",
|
||||
"delight-im/db": "^1.0"
|
||||
"delight-im/db": "^1.2"
|
||||
},
|
||||
"type": "library",
|
||||
"keywords": [ "auth", "authentication", "login", "security" ],
|
||||
|
27
composer.lock
generated
27
composer.lock
generated
@@ -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": "bd80e3e52b8bd8a4a0c74c7cf9f5bf5e",
|
||||
"content-hash": "3f836c43e0ff2293051f2ccb739d23cf",
|
||||
"content-hash": "c075bec19490fc0e972be01cdd02d59b",
|
||||
"packages": [
|
||||
{
|
||||
"name": "delight-im/cookie",
|
||||
"version": "v2.1.0",
|
||||
"version": "v2.1.1",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/delight-im/PHP-Cookie.git",
|
||||
"reference": "3e41e0d44959b59de98722b5b1b1fb83f9f528f3"
|
||||
"reference": "22f2c19750a6ad3dbf69a8ef3ea0e454a8e064fa"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/delight-im/PHP-Cookie/zipball/3e41e0d44959b59de98722b5b1b1fb83f9f528f3",
|
||||
"reference": "3e41e0d44959b59de98722b5b1b1fb83f9f528f3",
|
||||
"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,20 +45,20 @@
|
||||
"samesite",
|
||||
"xss"
|
||||
],
|
||||
"time": "2016-11-23 20:09:42"
|
||||
"time": "2016-12-18T20:22:46+00:00"
|
||||
},
|
||||
{
|
||||
"name": "delight-im/db",
|
||||
"version": "v1.0.2",
|
||||
"version": "v1.2.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/delight-im/PHP-DB.git",
|
||||
"reference": "c8d1eba6583007471d55bf7d88eb3c9d87ea849d"
|
||||
"reference": "df99ef7c2e86c7ce206647ffe8ba74447c075b57"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/delight-im/PHP-DB/zipball/c8d1eba6583007471d55bf7d88eb3c9d87ea849d",
|
||||
"reference": "c8d1eba6583007471d55bf7d88eb3c9d87ea849d",
|
||||
"url": "https://api.github.com/repos/delight-im/PHP-DB/zipball/df99ef7c2e86c7ce206647ffe8ba74447c075b57",
|
||||
"reference": "df99ef7c2e86c7ce206647ffe8ba74447c075b57",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -87,7 +86,7 @@
|
||||
"sql",
|
||||
"sqlite"
|
||||
],
|
||||
"time": "2016-12-01 12:40:36"
|
||||
"time": "2017-03-18T20:51:59+00:00"
|
||||
},
|
||||
{
|
||||
"name": "delight-im/http",
|
||||
@@ -123,7 +122,7 @@
|
||||
"http",
|
||||
"https"
|
||||
],
|
||||
"time": "2016-07-21 15:05:01"
|
||||
"time": "2016-07-21T15:05:01+00:00"
|
||||
}
|
||||
],
|
||||
"packages-dev": [],
|
||||
|
144
src/Administration.php
Normal file
144
src/Administration.php
Normal 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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
499
src/Auth.php
499
src/Auth.php
@@ -15,27 +15,22 @@ use Delight\Db\PdoDsn;
|
||||
use Delight\Db\Throwable\Error;
|
||||
use Delight\Db\Throwable\IntegrityConstraintViolationException;
|
||||
|
||||
require __DIR__.'/Base64.php';
|
||||
require __DIR__.'/Exceptions.php';
|
||||
require_once __DIR__ . '/Exceptions.php';
|
||||
|
||||
/** Base class that provides all methods, properties and utilities for secure authentication */
|
||||
class Auth {
|
||||
/** Component that provides all features and utilities for secure authentication of individual users */
|
||||
final class Auth extends UserManager {
|
||||
|
||||
const SESSION_FIELD_LOGGED_IN = 'auth_logged_in';
|
||||
const SESSION_FIELD_USER_ID = 'auth_user_id';
|
||||
const SESSION_FIELD_EMAIL = 'auth_email';
|
||||
const SESSION_FIELD_USERNAME = 'auth_username';
|
||||
const SESSION_FIELD_STATUS = 'auth_status';
|
||||
const SESSION_FIELD_REMEMBERED = 'auth_remembered';
|
||||
const COOKIE_CONTENT_SEPARATOR = '~';
|
||||
const COOKIE_NAME_REMEMBER = 'auth_remember';
|
||||
const IP_ADDRESS_HASH_ALGORITHM = 'sha256';
|
||||
const THROTTLE_ACTION_LOGIN = 'login';
|
||||
const THROTTLE_ACTION_REGISTER = 'register';
|
||||
const THROTTLE_ACTION_CONSUME_TOKEN = 'confirm_email';
|
||||
const HTTP_STATUS_CODE_TOO_MANY_REQUESTS = 429;
|
||||
|
||||
/** @var PdoDatabase the database connection that will be used */
|
||||
private $db;
|
||||
/** @var boolean whether HTTPS (TLS/SSL) will be used (recommended) */
|
||||
private $useHttps;
|
||||
/** @var boolean whether cookies should be accessible via client-side scripts (*not* recommended) */
|
||||
@@ -48,24 +43,13 @@ class Auth {
|
||||
private $throttlingTimeBucketSize;
|
||||
|
||||
/**
|
||||
* @param PdoDatabase|PdoDsn|\PDO $databaseConnection the database connection that will be used
|
||||
* @param PdoDatabase|PdoDsn|\PDO $databaseConnection the database connection to operate on
|
||||
* @param bool $useHttps whether HTTPS (TLS/SSL) will be used (recommended)
|
||||
* @param bool $allowCookiesScriptAccess whether cookies should be accessible via client-side scripts (*not* recommended)
|
||||
* @param string $ipAddress the IP address that should be used instead of the default setting (if any), e.g. when behind a proxy
|
||||
*/
|
||||
public function __construct($databaseConnection, $useHttps = false, $allowCookiesScriptAccess = false, $ipAddress = null) {
|
||||
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 {
|
||||
throw new \InvalidArgumentException('The database connection must be an instance of either `PdoDatabase`, `PdoDsn` or `PDO`');
|
||||
}
|
||||
parent::__construct($databaseConnection);
|
||||
|
||||
$this->useHttps = $useHttps;
|
||||
$this->allowCookiesScriptAccess = $allowCookiesScriptAccess;
|
||||
@@ -128,7 +112,7 @@ class Auth {
|
||||
if (isset($parts[0]) && isset($parts[1])) {
|
||||
try {
|
||||
$rememberData = $this->db->selectRow(
|
||||
'SELECT a.user, a.token, a.expires, b.email, b.username FROM users_remembered AS a JOIN users AS b ON a.user = b.id WHERE a.selector = ?',
|
||||
'SELECT a.user, a.token, a.expires, b.email, b.username, b.status FROM users_remembered AS a JOIN users AS b ON a.user = b.id WHERE a.selector = ?',
|
||||
[ $parts[0] ]
|
||||
);
|
||||
}
|
||||
@@ -139,7 +123,7 @@ class Auth {
|
||||
if (!empty($rememberData)) {
|
||||
if ($rememberData['expires'] >= time()) {
|
||||
if (password_verify($parts[1], $rememberData['token'])) {
|
||||
$this->onLoginSuccessful($rememberData['user'], $rememberData['email'], $rememberData['username'], true);
|
||||
$this->onLoginSuccessful($rememberData['user'], $rememberData['email'], $rememberData['username'], $rememberData['status'], true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -208,160 +192,38 @@ class Auth {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to sign in a user
|
||||
* Attempts to sign in a user with their email address and password
|
||||
*
|
||||
* @param string $email the user's email address
|
||||
* @param string $password the user's password
|
||||
* @param int|bool|null $rememberDuration (optional) the duration in seconds to keep the user logged in ("remember me"), e.g. `60 * 60 * 24 * 365.25` for one year
|
||||
* @param int|null $rememberDuration (optional) the duration in seconds to keep the user logged in ("remember me"), e.g. `60 * 60 * 24 * 365.25` for one year
|
||||
* @throws InvalidEmailException if the email address was invalid or could not be found
|
||||
* @throws InvalidPasswordException if the password was invalid
|
||||
* @throws EmailNotVerifiedException if the email address has not been verified yet via confirmation email
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function login($email, $password, $rememberDuration = null) {
|
||||
$email = self::validateEmailAddress($email);
|
||||
$password = self::validatePassword($password);
|
||||
|
||||
try {
|
||||
$userData = $this->db->selectRow(
|
||||
'SELECT id, password, verified, username FROM users WHERE email = ?',
|
||||
[ $email ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
}
|
||||
|
||||
if (!empty($userData)) {
|
||||
if (password_verify($password, $userData['password'])) {
|
||||
// if the password needs to be re-hashed to keep up with improving password cracking techniques
|
||||
if (password_needs_rehash($userData['password'], PASSWORD_DEFAULT)) {
|
||||
// create a new hash from the password and update it in the database
|
||||
$this->updatePassword($userData['id'], $password);
|
||||
}
|
||||
|
||||
if ($userData['verified'] === 1) {
|
||||
$this->onLoginSuccessful($userData['id'], $email, $userData['username'], false);
|
||||
|
||||
// continue to support the old parameter format
|
||||
if ($rememberDuration === true) {
|
||||
$rememberDuration = 60 * 60 * 24 * 28;
|
||||
}
|
||||
elseif ($rememberDuration === false) {
|
||||
$rememberDuration = null;
|
||||
}
|
||||
|
||||
if ($rememberDuration !== null) {
|
||||
$this->createRememberDirective($userData['id'], $rememberDuration);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
else {
|
||||
throw new EmailNotVerifiedException();
|
||||
}
|
||||
}
|
||||
else {
|
||||
$this->throttle(self::THROTTLE_ACTION_LOGIN);
|
||||
$this->throttle(self::THROTTLE_ACTION_LOGIN, $email);
|
||||
|
||||
throw new InvalidPasswordException();
|
||||
}
|
||||
}
|
||||
else {
|
||||
$this->throttle(self::THROTTLE_ACTION_LOGIN);
|
||||
$this->throttle(self::THROTTLE_ACTION_LOGIN, $email);
|
||||
|
||||
throw new InvalidEmailException();
|
||||
}
|
||||
$this->authenticateUserInternal($password, $email, null, $rememberDuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates an email address
|
||||
* Attempts to sign in a user with their username and password
|
||||
*
|
||||
* @param string $email the email address to validate
|
||||
* @return string the email address if it's valid
|
||||
* @throws InvalidEmailException if the email address was invalid
|
||||
*/
|
||||
private 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
|
||||
* When using this method to authenticate users, you should ensure that usernames are unique
|
||||
*
|
||||
* @param string $password the password to validate
|
||||
* @return string the password if it's valid
|
||||
* Consistently using {@see registerWithUniqueUsername} instead of {@see register} can be helpful
|
||||
*
|
||||
* @param string $username the user's username
|
||||
* @param string $password the user's password
|
||||
* @param int|null $rememberDuration (optional) the duration in seconds to keep the user logged in ("remember me"), e.g. `60 * 60 * 24 * 365.25` for one year
|
||||
* @throws UnknownUsernameException if the specified username does not exist
|
||||
* @throws AmbiguousUsernameException if the specified username is ambiguous, i.e. there are multiple users with that name
|
||||
* @throws InvalidPasswordException if the password was invalid
|
||||
* @throws EmailNotVerifiedException if the email address has not been verified yet via confirmation email
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
private static function validatePassword($password) {
|
||||
if (empty($password)) {
|
||||
throw new InvalidPasswordException();
|
||||
}
|
||||
|
||||
$password = trim($password);
|
||||
|
||||
if (strlen($password) < 1) {
|
||||
throw new InvalidPasswordException();
|
||||
}
|
||||
|
||||
return $password;
|
||||
public function loginWithUsername($username, $password, $rememberDuration = null) {
|
||||
$this->authenticateUserInternal($password, null, $username, $rememberDuration);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -435,17 +297,23 @@ class Auth {
|
||||
}
|
||||
|
||||
// set the cookie with the selector and token
|
||||
|
||||
$cookie = new Cookie(self::COOKIE_NAME_REMEMBER);
|
||||
|
||||
$cookie->setValue($content);
|
||||
$cookie->setExpiryTime($expires);
|
||||
|
||||
if (!empty($params['path'])) {
|
||||
$cookie->setPath($params['path']);
|
||||
}
|
||||
|
||||
if (!empty($params['domain'])) {
|
||||
$cookie->setDomain($params['domain']);
|
||||
}
|
||||
|
||||
$cookie->setHttpOnly($params['httponly']);
|
||||
$cookie->setSecureOnly($params['secure']);
|
||||
|
||||
$result = $cookie->save();
|
||||
|
||||
if ($result === false) {
|
||||
@@ -459,10 +327,11 @@ class Auth {
|
||||
* @param int $userId the ID of the user who has just logged in
|
||||
* @param string $email the email address of the user who has just logged in
|
||||
* @param string $username the username (if any)
|
||||
* @param int $status the status as one of the constants from the {@see Status} class
|
||||
* @param bool $remembered whether the user was remembered ("remember me") or logged in actively
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
private function onLoginSuccessful($userId, $email, $username, $remembered) {
|
||||
private function onLoginSuccessful($userId, $email, $username, $status, $remembered) {
|
||||
try {
|
||||
$this->db->update(
|
||||
'users',
|
||||
@@ -482,6 +351,7 @@ class Auth {
|
||||
$this->setUserId($userId);
|
||||
$this->setEmail($email);
|
||||
$this->setUsername($username);
|
||||
$this->setStatus($status);
|
||||
$this->setRemembered($remembered);
|
||||
}
|
||||
|
||||
@@ -714,7 +584,7 @@ class Auth {
|
||||
);
|
||||
|
||||
// ensure that the account has been verified before initiating a password reset
|
||||
if ($userData['verified'] !== 1) {
|
||||
if ((int) $userData['verified'] !== 1) {
|
||||
throw new EmailNotVerifiedException();
|
||||
}
|
||||
|
||||
@@ -729,87 +599,120 @@ class Auth {
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new user
|
||||
* Authenticates an existing 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
|
||||
* @param string $password the user's password
|
||||
* @param string|null $email (optional) the user's email address
|
||||
* @param string|null $username (optional) the user's username
|
||||
* @param int|null $rememberDuration (optional) the duration in seconds to keep the user logged in ("remember me"), e.g. `60 * 60 * 24 * 365.25` for one year
|
||||
* @throws InvalidEmailException if the email address was invalid or could not be found
|
||||
* @throws UnknownUsernameException if an attempt has been made to authenticate with a non-existing username
|
||||
* @throws AmbiguousUsernameException if an attempt has been made to authenticate with an ambiguous username
|
||||
* @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 EmailNotVerifiedException if the email address has not been verified yet via confirmation email
|
||||
* @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);
|
||||
private function authenticateUserInternal($password, $email = null, $username = null, $rememberDuration = null) {
|
||||
$columnsToFetch = [ 'id', 'email', 'password', 'verified', 'username', 'status' ];
|
||||
|
||||
ignore_user_abort(true);
|
||||
if ($email !== null) {
|
||||
$email = self::validateEmailAddress($email);
|
||||
|
||||
$email = self::validateEmailAddress($email);
|
||||
$password = self::validatePassword($password);
|
||||
// attempt to look up the account information using the specified email address
|
||||
try {
|
||||
$userData = $this->getUserDataByEmailAddress(
|
||||
$email,
|
||||
$columnsToFetch
|
||||
);
|
||||
}
|
||||
// if there is no user with the specified email address
|
||||
catch (InvalidEmailException $e) {
|
||||
// throttle this operation
|
||||
$this->throttle(self::THROTTLE_ACTION_LOGIN);
|
||||
$this->throttle(self::THROTTLE_ACTION_LOGIN, $email);
|
||||
|
||||
$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();
|
||||
// and re-throw the exception
|
||||
throw new InvalidEmailException();
|
||||
}
|
||||
}
|
||||
elseif ($username !== null) {
|
||||
$username = trim($username);
|
||||
|
||||
$password = password_hash($password, PASSWORD_DEFAULT);
|
||||
$verified = isset($callback) && is_callable($callback) ? 0 : 1;
|
||||
// attempt to look up the account information using the specified username
|
||||
try {
|
||||
$userData = $this->getUserDataByUsername(
|
||||
$username,
|
||||
$columnsToFetch
|
||||
);
|
||||
}
|
||||
// if there is no user with the specified username
|
||||
catch (UnknownUsernameException $e) {
|
||||
// throttle this operation
|
||||
$this->throttle(self::THROTTLE_ACTION_LOGIN);
|
||||
$this->throttle(self::THROTTLE_ACTION_LOGIN, $username);
|
||||
|
||||
try {
|
||||
$this->db->insert(
|
||||
'users',
|
||||
[
|
||||
'email' => $email,
|
||||
'password' => $password,
|
||||
'username' => $username,
|
||||
'verified' => $verified,
|
||||
'registered' => time()
|
||||
]
|
||||
);
|
||||
// and re-throw the exception
|
||||
throw new UnknownUsernameException();
|
||||
}
|
||||
// if there are multiple users with the specified username
|
||||
catch (AmbiguousUsernameException $e) {
|
||||
// throttle this operation
|
||||
$this->throttle(self::THROTTLE_ACTION_LOGIN);
|
||||
$this->throttle(self::THROTTLE_ACTION_LOGIN, $username);
|
||||
|
||||
// and re-throw the exception
|
||||
throw new AmbiguousUsernameException();
|
||||
}
|
||||
}
|
||||
catch (IntegrityConstraintViolationException $e) {
|
||||
// if we have a duplicate entry
|
||||
throw new UserAlreadyExistsException();
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
// if neither an email address nor a username has been provided
|
||||
else {
|
||||
// we can't do anything here because the method call has been invalid
|
||||
throw new EmailOrUsernameRequiredError();
|
||||
}
|
||||
|
||||
$newUserId = (int) $this->db->getLastInsertId();
|
||||
$password = self::validatePassword($password);
|
||||
|
||||
if ($verified === 0) {
|
||||
$this->createConfirmationRequest($email, $callback);
|
||||
if (password_verify($password, $userData['password'])) {
|
||||
// if the password needs to be re-hashed to keep up with improving password cracking techniques
|
||||
if (password_needs_rehash($userData['password'], PASSWORD_DEFAULT)) {
|
||||
// create a new hash from the password and update it in the database
|
||||
$this->updatePassword($userData['id'], $password);
|
||||
}
|
||||
|
||||
if ((int) $userData['verified'] === 1) {
|
||||
$this->onLoginSuccessful($userData['id'], $userData['email'], $userData['username'], $userData['status'], false);
|
||||
|
||||
// continue to support the old parameter format
|
||||
if ($rememberDuration === true) {
|
||||
$rememberDuration = 60 * 60 * 24 * 28;
|
||||
}
|
||||
elseif ($rememberDuration === false) {
|
||||
$rememberDuration = null;
|
||||
}
|
||||
|
||||
if ($rememberDuration !== null) {
|
||||
$this->createRememberDirective($userData['id'], $rememberDuration);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
else {
|
||||
throw new EmailNotVerifiedException();
|
||||
}
|
||||
}
|
||||
else {
|
||||
// throttle this operation
|
||||
$this->throttle(self::THROTTLE_ACTION_LOGIN);
|
||||
if (isset($email)) {
|
||||
$this->throttle(self::THROTTLE_ACTION_LOGIN, $email);
|
||||
}
|
||||
elseif (isset($username)) {
|
||||
$this->throttle(self::THROTTLE_ACTION_LOGIN, $username);
|
||||
}
|
||||
|
||||
return $newUserId;
|
||||
// we cannot authenticate the user due to the password being wrong
|
||||
throw new InvalidPasswordException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -818,14 +721,14 @@ class Auth {
|
||||
* You must never pass untrusted input to the parameter that takes the column list
|
||||
*
|
||||
* @param string $email the email address to look for
|
||||
* @param array $requestColumns the columns to request from the user's record
|
||||
* @param array $requestedColumns 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 getUserDataByEmailAddress($email, array $requestColumns) {
|
||||
private function getUserDataByEmailAddress($email, array $requestedColumns) {
|
||||
try {
|
||||
$projection = implode(', ', $requestColumns);
|
||||
$projection = implode(', ', $requestedColumns);
|
||||
$userData = $this->db->selectRow(
|
||||
'SELECT ' . $projection . ' FROM users WHERE email = ?',
|
||||
[ $email ]
|
||||
@@ -1113,6 +1016,101 @@ class Auth {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the currently signed-in user's status and updates the session
|
||||
*
|
||||
* @param int $status the status as one of the constants from the {@see Status} class
|
||||
*/
|
||||
private function setStatus($status) {
|
||||
$_SESSION[self::SESSION_FIELD_STATUS] = (int) $status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the currently signed-in user's status by reading from the session
|
||||
*
|
||||
* @return int the status as one of the constants from the {@see Status} class
|
||||
*/
|
||||
public function getStatus() {
|
||||
if (isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_STATUS])) {
|
||||
return $_SESSION[self::SESSION_FIELD_STATUS];
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the currently signed-in user is in "normal" state
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @see Status
|
||||
* @see Auth::getStatus
|
||||
*/
|
||||
public function isNormal() {
|
||||
return $this->getStatus() === Status::NORMAL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the currently signed-in user is in "archived" state
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @see Status
|
||||
* @see Auth::getStatus
|
||||
*/
|
||||
public function isArchived() {
|
||||
return $this->getStatus() === Status::ARCHIVED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the currently signed-in user is in "banned" state
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @see Status
|
||||
* @see Auth::getStatus
|
||||
*/
|
||||
public function isBanned() {
|
||||
return $this->getStatus() === Status::BANNED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the currently signed-in user is in "locked" state
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @see Status
|
||||
* @see Auth::getStatus
|
||||
*/
|
||||
public function isLocked() {
|
||||
return $this->getStatus() === Status::LOCKED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the currently signed-in user is in "pending review" state
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @see Status
|
||||
* @see Auth::getStatus
|
||||
*/
|
||||
public function isPendingReview() {
|
||||
return $this->getStatus() === Status::PENDING_REVIEW;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the currently signed-in user is in "suspended" state
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @see Status
|
||||
* @see Auth::getStatus
|
||||
*/
|
||||
public function isSuspended() {
|
||||
return $this->getStatus() === Status::SUSPENDED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets whether the currently signed-in user has been remembered by a long-lived cookie
|
||||
*
|
||||
@@ -1166,15 +1164,7 @@ class Auth {
|
||||
return (int) (time() / $this->throttlingTimeBucketSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Throttles the specified action for the user to protect against too many requests
|
||||
*
|
||||
* @param string $actionType one of the `THROTTLE_ACTION_*` constants
|
||||
* @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)
|
||||
*/
|
||||
private function throttle($actionType, $customSelector = null) {
|
||||
protected function throttle($actionType, $customSelector = null) {
|
||||
// if a custom selector has been provided (e.g. username, user ID or confirmation token)
|
||||
if (isset($customSelector)) {
|
||||
// use the provided selector for throttling
|
||||
@@ -1277,6 +1267,17 @@ class Auth {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the component that can be used for administrative tasks
|
||||
*
|
||||
* You must offer access to this interface to authorized users only (restricted via your own access control)
|
||||
*
|
||||
* @return Administration
|
||||
*/
|
||||
public function admin() {
|
||||
return new Administration($this->db);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the cookie settings that will be used to create and update cookies on the client
|
||||
*
|
||||
@@ -1295,24 +1296,6 @@ class Auth {
|
||||
return $params;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a UUID v4 as per RFC 4122
|
||||
*
|
||||
|
@@ -8,7 +8,7 @@
|
||||
|
||||
namespace Delight\Auth;
|
||||
|
||||
class Base64 {
|
||||
final class Base64 {
|
||||
|
||||
const SPECIAL_CHARS_ORIGINAL = '+/=';
|
||||
const SPECIAL_CHARS_SAFE = '._-';
|
||||
|
@@ -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 {}
|
||||
@@ -28,10 +32,16 @@ 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 MissingCallbackError extends AuthError {}
|
||||
|
||||
class HeadersAlreadySentError extends AuthError {}
|
||||
|
||||
class EmailOrUsernameRequiredError extends AuthError {}
|
||||
|
20
src/Status.php
Normal file
20
src/Status.php
Normal 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;
|
||||
|
||||
}
|
300
src/UserManager.php
Normal file
300
src/UserManager.php
Normal file
@@ -0,0 +1,300 @@
|
||||
<?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`');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
181
tests/index.php
181
tests/index.php
@@ -20,6 +20,8 @@ header('Content-type: text/html; charset=utf-8');
|
||||
require __DIR__.'/../vendor/autoload.php';
|
||||
|
||||
$db = new PDO('mysql:dbname=php_auth;host=127.0.0.1;charset=utf8mb4', 'root', 'monkey');
|
||||
// or
|
||||
// $db = new PDO('sqlite:../Databases/php_auth.sqlite');
|
||||
|
||||
$auth = new \Delight\Auth\Auth($db);
|
||||
|
||||
@@ -48,13 +50,27 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
}
|
||||
|
||||
try {
|
||||
$auth->login($_POST['email'], $_POST['password'], $rememberDuration);
|
||||
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';
|
||||
}
|
||||
@@ -86,7 +102,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';
|
||||
@@ -95,7 +120,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';
|
||||
@@ -182,6 +210,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']);
|
||||
}
|
||||
@@ -216,6 +304,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";
|
||||
@@ -230,6 +324,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>';
|
||||
@@ -255,6 +379,8 @@ 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" /> ';
|
||||
@@ -263,7 +389,18 @@ function showGuestUserForm() {
|
||||
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">';
|
||||
@@ -275,6 +412,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>';
|
||||
|
||||
@@ -298,4 +439,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>';
|
||||
}
|
||||
|
Reference in New Issue
Block a user