mirror of
https://github.com/delight-im/PHP-Auth.git
synced 2025-08-07 16:46:29 +02:00
Compare commits
172 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
9637dfa60d | ||
|
aec738a9db | ||
|
382ee5bf93 | ||
|
47d1e303aa | ||
|
67443c122a | ||
|
24056e89a4 | ||
|
c06bc7da1a | ||
|
aedd2125fc | ||
|
425cf9b6f6 | ||
|
739fa7d574 | ||
|
302feb5da2 | ||
|
2ded232d8e | ||
|
70a905afd7 | ||
|
84f3ad10a9 | ||
|
81091df66b | ||
|
8926e7e708 | ||
|
eec450677f | ||
|
f1360dceba | ||
|
2cf7b27ba3 | ||
|
ecd8015acf | ||
|
1eedfd0e02 | ||
|
757579523c | ||
|
d695328a5a | ||
|
71506eaa05 | ||
|
ce8dbbc436 | ||
|
d181219e40 | ||
|
891cef2511 | ||
|
f70613b2b8 | ||
|
59816d1a40 | ||
|
1284f64f04 | ||
|
8165e8917b | ||
|
a4b68167a1 | ||
|
fc2fb4bb44 | ||
|
b2a3fde696 | ||
|
36880b87c9 | ||
|
4a66965994 | ||
|
e7b590dc80 | ||
|
33d2384c93 | ||
|
1169856217 | ||
|
fa75811679 | ||
|
fa8fa4887e | ||
|
8fecb86f15 | ||
|
04c466b309 | ||
|
61041cc6fd | ||
|
2ca835ac75 | ||
|
1e23e6de13 | ||
|
50220d463b | ||
|
f0bdd7b63e | ||
|
0473d59c39 | ||
|
f8f44a0286 | ||
|
ea91d8c92e | ||
|
7983bebd83 | ||
|
ddc5b50459 | ||
|
0b67f3d1e2 | ||
|
16bcfa85ef | ||
|
404739634d | ||
|
82a24fbbca | ||
|
1a195adf39 | ||
|
5e4d4fd072 | ||
|
6162092618 | ||
|
f142dd91dc | ||
|
05567acc7c | ||
|
3d8c583823 | ||
|
546a57cbf9 | ||
|
52ba03248d | ||
|
c5ed53898e | ||
|
a66312bbcf | ||
|
c1bb10f58d | ||
|
4fd37f079b | ||
|
8ff3776e75 | ||
|
b24979ae26 | ||
|
30b2f30aec | ||
|
b3d37ada86 | ||
|
27adc9fa91 | ||
|
c9a4e28c7b | ||
|
f83ac969d4 | ||
|
0bbf9d32b1 | ||
|
381e05f102 | ||
|
2839743c46 | ||
|
d86d7ffd25 | ||
|
e3873f2d15 | ||
|
b7a47fc707 | ||
|
91f50a80bb | ||
|
7272fbb9a8 | ||
|
62c5fab1ad | ||
|
1800525b51 | ||
|
e4f8673eab | ||
|
59cd626bd0 | ||
|
3809b9d5d5 | ||
|
3329c6a985 | ||
|
7b98993bf8 | ||
|
d5ae78a418 | ||
|
e925a73ef8 | ||
|
39f9b00b45 | ||
|
ea67c66bd1 | ||
|
7b4c4bf0e1 | ||
|
f13302b014 | ||
|
af5ce5a0b4 | ||
|
15f73567b6 | ||
|
90c621aeb0 | ||
|
28979925d7 | ||
|
b2e6f68a22 | ||
|
d14d929bc3 | ||
|
f962008fc4 | ||
|
ec8e9eab4e | ||
|
65b4f812c0 | ||
|
b8e04e3c6a | ||
|
5c92d026c9 | ||
|
2247c2781c | ||
|
72b2468aa3 | ||
|
7cc27b814e | ||
|
dbc463c95e | ||
|
4b6afc7c48 | ||
|
a3a28af2aa | ||
|
c842fa9792 | ||
|
a599771bd5 | ||
|
e73f29eec0 | ||
|
c118116a52 | ||
|
0e969ccd8d | ||
|
aae0bfb5ab | ||
|
fb982cee6a | ||
|
838c6edf66 | ||
|
ad5784364d | ||
|
d8f21a35fc | ||
|
79ecb85bb6 | ||
|
f56e7e6871 | ||
|
83f2ab0a9c | ||
|
5274dd5f8e | ||
|
b93d9616d0 | ||
|
0af55ad77c | ||
|
7b6287a7dc | ||
|
cf7493d87e | ||
|
f68d29000e | ||
|
cd3469c137 | ||
|
bc44a08b1b | ||
|
8ff4242f8f | ||
|
1a4041ea60 | ||
|
b7e6ca6dee | ||
|
f2074e1537 | ||
|
9c63c30cd9 | ||
|
8a1140a485 | ||
|
23b172055b | ||
|
c25b74d405 | ||
|
2278b86fba | ||
|
4eca6bb151 | ||
|
db4c99e729 | ||
|
d6bc8c6492 | ||
|
b577322939 | ||
|
6cf955ed52 | ||
|
8c2c32f9dc | ||
|
2d7ad74c44 | ||
|
a91cde706d | ||
|
8feda0ae58 | ||
|
78b7fb4169 | ||
|
499fbb6542 | ||
|
50b9c48f8d | ||
|
fcbace0aec | ||
|
c2ab825354 | ||
|
b1ac859fd2 | ||
|
0d9be76f8b | ||
|
64d15263ae | ||
|
854bc2b62b | ||
|
01a52b76bc | ||
|
ad88c1c6ab | ||
|
449e1c69ee | ||
|
63734fc5ee | ||
|
6e3728a918 | ||
|
0909291cf1 | ||
|
6aa3f58059 | ||
|
6156b1c135 | ||
|
829d5614ed | ||
|
47afa1c411 |
@@ -14,6 +14,8 @@ CREATE TABLE IF NOT EXISTS `users` (
|
||||
`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',
|
||||
`resettable` tinyint(1) unsigned NOT NULL DEFAULT '1',
|
||||
`roles_mask` int(10) unsigned NOT NULL DEFAULT '0',
|
||||
`registered` int(10) unsigned NOT NULL,
|
||||
`last_login` int(10) unsigned DEFAULT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
@@ -22,13 +24,15 @@ CREATE TABLE IF NOT EXISTS `users` (
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `users_confirmations` (
|
||||
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
|
||||
`user_id` int(10) unsigned NOT NULL,
|
||||
`email` varchar(249) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`selector` varchar(16) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
|
||||
`token` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
|
||||
`expires` int(10) unsigned NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `selector` (`selector`),
|
||||
KEY `email_expires` (`email`,`expires`)
|
||||
KEY `email_expires` (`email`,`expires`),
|
||||
KEY `user_id` (`user_id`)
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `users_remembered` (
|
||||
@@ -54,13 +58,12 @@ CREATE TABLE IF NOT EXISTS `users_resets` (
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `users_throttling` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
|
||||
`action_type` enum('login','register','confirm_email') COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`selector` varchar(44) CHARACTER SET latin1 COLLATE latin1_general_cs DEFAULT NULL,
|
||||
`time_bucket` int(10) unsigned NOT NULL,
|
||||
`attempts` mediumint(8) unsigned NOT NULL DEFAULT '1',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `action_type_selector_time_bucket` (`action_type`,`selector`,`time_bucket`)
|
||||
`bucket` varchar(44) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
|
||||
`tokens` float unsigned NOT NULL,
|
||||
`replenished_at` int(10) unsigned NOT NULL,
|
||||
`expires_at` int(10) unsigned NOT NULL,
|
||||
PRIMARY KEY (`bucket`),
|
||||
KEY `expires_at` (`expires_at`)
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
|
||||
|
@@ -11,6 +11,8 @@ CREATE TABLE "users" (
|
||||
"username" VARCHAR(100) DEFAULT NULL,
|
||||
"status" INTEGER NOT NULL CHECK ("status" >= 0) DEFAULT "0",
|
||||
"verified" INTEGER NOT NULL CHECK ("verified" >= 0) DEFAULT "0",
|
||||
"resettable" INTEGER NOT NULL CHECK ("resettable" >= 0) DEFAULT "1",
|
||||
"roles_mask" INTEGER NOT NULL CHECK ("roles_mask" >= 0) DEFAULT "0",
|
||||
"registered" INTEGER NOT NULL CHECK ("registered" >= 0),
|
||||
"last_login" INTEGER CHECK ("last_login" >= 0) DEFAULT NULL,
|
||||
CONSTRAINT "email" UNIQUE ("email")
|
||||
@@ -18,6 +20,7 @@ CREATE TABLE "users" (
|
||||
|
||||
CREATE TABLE "users_confirmations" (
|
||||
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0),
|
||||
"user_id" INTEGER NOT NULL CHECK ("user_id" >= 0),
|
||||
"email" VARCHAR(249) NOT NULL,
|
||||
"selector" VARCHAR(16) NOT NULL,
|
||||
"token" VARCHAR(255) NOT NULL,
|
||||
@@ -25,6 +28,7 @@ CREATE TABLE "users_confirmations" (
|
||||
CONSTRAINT "selector" UNIQUE ("selector")
|
||||
);
|
||||
CREATE INDEX "users_confirmations.email_expires" ON "users_confirmations" ("email", "expires");
|
||||
CREATE INDEX "users_confirmations.user_id" ON "users_confirmations" ("user_id");
|
||||
|
||||
CREATE TABLE "users_remembered" (
|
||||
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0),
|
||||
@@ -47,10 +51,9 @@ CREATE TABLE "users_resets" (
|
||||
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")
|
||||
"bucket" VARCHAR(44) PRIMARY KEY NOT NULL,
|
||||
"tokens" REAL NOT NULL CHECK ("tokens" >= 0),
|
||||
"replenished_at" INTEGER NOT NULL CHECK ("replenished_at" >= 0),
|
||||
"expires_at" INTEGER NOT NULL CHECK ("expires_at" >= 0)
|
||||
);
|
||||
CREATE INDEX "users_throttling.expires_at" ON "users_throttling" ("expires_at");
|
||||
|
141
Migration.md
141
Migration.md
@@ -1,10 +1,151 @@
|
||||
# Migration
|
||||
|
||||
* [General](#general)
|
||||
* [From `v6.x.x` to `v7.x.x`](#from-v6xx-to-v7xx)
|
||||
* [From `v5.x.x` to `v6.x.x`](#from-v5xx-to-v6xx)
|
||||
* [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)
|
||||
|
||||
## General
|
||||
|
||||
Update your version of this library via Composer [[?]](https://github.com/delight-im/Knowledge/blob/master/Composer%20(PHP).md):
|
||||
|
||||
```
|
||||
$ composer update delight-im/auth
|
||||
```
|
||||
|
||||
If you want to perform a major version upgrade (e.g. from version `1.x.x` to version `2.x.x`), the version constraints defined in your `composer.json` [[?]](https://github.com/delight-im/Knowledge/blob/master/Composer%20(PHP).md) may not allow this. In that case, just add the dependency again to overwrite it with the latest version (or optionally with a specified version):
|
||||
|
||||
```
|
||||
$ composer require delight-im/auth
|
||||
```
|
||||
|
||||
## From `v6.x.x` to `v7.x.x`
|
||||
|
||||
* The method `logOutButKeepSession` from class `Auth` is now simply called `logOut`. Therefore, the former method `logout` is now called `logOutAndDestroySession`. With both methods, mind the capitalization of the letter “O”.
|
||||
|
||||
* The second argument of the `Auth` constructor, which was named `$useHttps`, has been removed. If you previously had it set to `true`, make sure to set the value of the `session.cookie_secure` directive to `1` now. You may do so either directly in your [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), via the `\ini_set` method or via the `\session_set_cookie_params` method. Otherwise, make sure that directive is set to `0`.
|
||||
|
||||
* The third argument of the `Auth` constructor, which was named `$allowCookiesScriptAccess`, has been removed. If you previously had it set to `true`, make sure to set the value of the `session.cookie_httponly` directive to `0` now. You may do so either directly in your [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), via the `\ini_set` method or via the `\session_set_cookie_params` method. Otherwise, make sure that directive is set to `1`.
|
||||
|
||||
* Only if *both* of the following two conditions are met:
|
||||
|
||||
* The directive `session.cookie_domain` is set to an empty value. It may have been set directly in your [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), via the `\ini_set` method or via the `\session_set_cookie_params` method. You can check the value of that directive by executing the following statement somewhere in your application:
|
||||
|
||||
```php
|
||||
\var_dump(\ini_get('session.cookie_domain'));
|
||||
```
|
||||
|
||||
* Your application is accessed via a registered or registrable *domain name*, either by yourself during development and testing or by your visitors and users in production. That means your application is *not*, or *not only*, accessed via `localhost` or via an IP address.
|
||||
|
||||
Then the domain scope for the [two cookies](README.md#cookies) used by this library has changed. You can handle this change in one of two different ways:
|
||||
|
||||
* Restore the old behavior by placing the following statement as early as possible in your application, and before you create the `Auth` instance:
|
||||
|
||||
```php
|
||||
\ini_set('session.cookie_domain', \preg_replace('/^www\./', '', $_SERVER['HTTP_HOST']));
|
||||
```
|
||||
|
||||
You may also evaluate the complete second parameter and put its value directly into your [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`).
|
||||
|
||||
* Use the new domain scope for your application. To do so, you only need to [rename the cookies](README.md#renaming-the-librarys-cookies) used by this library in order to prevent conflicts with old cookies that have been created previously. Renaming the cookies is critically important here. We recommend a versioned name such as `session_v1` for the session cookie.
|
||||
|
||||
* Only if *both* of the following two conditions are met:
|
||||
|
||||
* The directive `session.cookie_domain` is set to a value that starts with the `www` subdomain. It may have been set directly in your [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), via the `\ini_set` method or via the `\session_set_cookie_params` method. You can check the value of that directive by executing the following statement somewhere in your application:
|
||||
|
||||
```php
|
||||
\var_dump(\ini_get('session.cookie_domain'));
|
||||
```
|
||||
|
||||
* Your application is accessed via a registered or registrable *domain name*, either by yourself during development and testing or by your visitors and users in production. That means your application is *not*, or *not only*, accessed via `localhost` or via an IP address.
|
||||
|
||||
Then the domain scope for [one of the cookies](README.md#cookies) used by this library has changed. To make your application work correctly with the new scope, [rename the cookies](README.md#renaming-the-librarys-cookies) used by this library in order to prevent conflicts with old cookies that have been created previously. Renaming the cookies is critically important here. We recommend a versioned name such as `session_v1` for the session cookie.
|
||||
|
||||
* If the directive `session.cookie_path` is set to an empty value, then the path scope for [one of the cookies](README.md#cookies) used by this library has changed. To make your application work correctly with the new scope, [rename the cookies](README.md#renaming-the-librarys-cookies) used by this library in order to prevent conflicts with old cookies that have been created previously. Renaming the cookies is critically important here. We recommend a versioned name such as `session_v1` for the session cookie.
|
||||
|
||||
The directive may have been set directly in your [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), via the `\ini_set` method or via the `\session_set_cookie_params` method. You can check the value of that directive by executing the following statement somewhere in your application:
|
||||
|
||||
```php
|
||||
\var_dump(\ini_get('session.cookie_path'));
|
||||
```
|
||||
|
||||
## From `v5.x.x` to `v6.x.x`
|
||||
|
||||
* The database schema has changed.
|
||||
|
||||
* The MySQL database schema has changed. Use the statements below to update your database:
|
||||
|
||||
```sql
|
||||
ALTER TABLE users
|
||||
ADD COLUMN roles_mask INT(10) UNSIGNED NOT NULL DEFAULT 0 AFTER verified,
|
||||
ADD COLUMN resettable TINYINT(1) UNSIGNED NOT NULL DEFAULT 1 AFTER verified;
|
||||
|
||||
ALTER TABLE users_confirmations
|
||||
ADD COLUMN user_id INT(10) UNSIGNED NULL DEFAULT NULL AFTER id;
|
||||
|
||||
UPDATE users_confirmations SET user_id = (
|
||||
SELECT id FROM users WHERE email = users_confirmations.email
|
||||
) WHERE user_id IS NULL;
|
||||
|
||||
ALTER TABLE users_confirmations
|
||||
CHANGE COLUMN user_id user_id INT(10) UNSIGNED NOT NULL;
|
||||
|
||||
ALTER TABLE users_confirmations
|
||||
ADD INDEX user_id (user_id ASC);
|
||||
|
||||
DROP TABLE users_throttling;
|
||||
|
||||
CREATE TABLE users_throttling (
|
||||
bucket varchar(44) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
|
||||
tokens float unsigned NOT NULL,
|
||||
replenished_at int(10) unsigned NOT NULL,
|
||||
expires_at int(10) unsigned NOT NULL,
|
||||
PRIMARY KEY (bucket),
|
||||
KEY expires_at (expires_at)
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
```
|
||||
|
||||
* The SQLite database schema has changed. Use the statements below to update your database:
|
||||
|
||||
```sql
|
||||
ALTER TABLE users
|
||||
ADD COLUMN "roles_mask" INTEGER NOT NULL CHECK ("roles_mask" >= 0) DEFAULT "0",
|
||||
ADD COLUMN "resettable" INTEGER NOT NULL CHECK ("resettable" >= 0) DEFAULT "1";
|
||||
|
||||
ALTER TABLE users_confirmations
|
||||
ADD COLUMN "user_id" INTEGER CHECK ("user_id" >= 0);
|
||||
|
||||
UPDATE users_confirmations SET user_id = (
|
||||
SELECT id FROM users WHERE email = users_confirmations.email
|
||||
) WHERE user_id IS NULL;
|
||||
|
||||
CREATE INDEX "users_confirmations.user_id" ON "users_confirmations" ("user_id");
|
||||
|
||||
DROP TABLE users_throttling;
|
||||
|
||||
CREATE TABLE "users_throttling" (
|
||||
"bucket" VARCHAR(44) PRIMARY KEY NOT NULL,
|
||||
"tokens" REAL NOT NULL CHECK ("tokens" >= 0),
|
||||
"replenished_at" INTEGER NOT NULL CHECK ("replenished_at" >= 0),
|
||||
"expires_at" INTEGER NOT NULL CHECK ("expires_at" >= 0)
|
||||
);
|
||||
|
||||
CREATE INDEX "users_throttling.expires_at" ON "users_throttling" ("expires_at");
|
||||
```
|
||||
|
||||
* The method `setThrottlingOptions` has been removed.
|
||||
|
||||
* The method `changePassword` may now throw an additional `\Delight\Auth\TooManyRequestsException` if too many attempts have been made without the correct old password.
|
||||
|
||||
* The two methods `confirmEmail` and `confirmEmailAndSignIn` may now throw an additional `\Delight\Auth\UserAlreadyExistsException` if an attempt has been made to change the email address to an address that has become occupied in the meantime.
|
||||
|
||||
* The two methods `forgotPassword` and `resetPassword` may now throw an additional `\Delight\Auth\ResetDisabledException` if the user has disabled password resets for their account.
|
||||
|
||||
* The `Base64` class is now an external module and has been moved from the namespace `Delight\Auth` to the namespace `Delight\Base64`. The interface and the return values are not compatible with those from previous versions anymore.
|
||||
|
||||
## From `v4.x.x` to `v5.x.x`
|
||||
|
||||
* The MySQL database schema has changed. Use the statement below to update your database:
|
||||
|
683
README.md
683
README.md
@@ -1,6 +1,6 @@
|
||||
# Auth
|
||||
|
||||
Authentication for PHP. Simple, lightweight and secure.
|
||||
**Authentication for PHP. Simple, lightweight and secure.**
|
||||
|
||||
Written once, to be used everywhere.
|
||||
|
||||
@@ -8,7 +8,7 @@ Completely framework-agnostic and database-agnostic.
|
||||
|
||||
## Why do I need this?
|
||||
|
||||
* There are [tons](http://www.troyhunt.com/2011/01/whos-who-of-bad-password-practices.html) [of](http://www.jeremytunnell.com/posts/swab-password-policies-and-two-factor-authentication-a-comedy-of-errors) [websites](http://badpasswordpolicies.tumblr.com/) with weak authentication systems. Don't build such a site.
|
||||
* There are [tons](http://www.troyhunt.com/2011/01/whos-who-of-bad-password-practices.html) [of](http://www.jeremytunnell.com/posts/swab-password-policies-and-two-factor-authentication-a-comedy-of-errors) [websites](http://badpasswordpolicies.tumblr.com/) with weak authentication systems. Don’t build such a site.
|
||||
* Re-implementing a new authentication system for every PHP project is *not* a good idea.
|
||||
* Building your own authentication classes piece by piece, and copying it to every project, is *not* recommended, either.
|
||||
* A secure authentication system with an easy-to-use API should be thoroughly designed and planned.
|
||||
@@ -24,7 +24,7 @@ Completely framework-agnostic and database-agnostic.
|
||||
|
||||
## Installation
|
||||
|
||||
1. Include the library via [Composer](https://getcomposer.org/):
|
||||
1. Include the library via Composer [[?]](https://github.com/delight-im/Knowledge/blob/master/Composer%20(PHP).md):
|
||||
|
||||
```
|
||||
$ composer require delight-im/auth
|
||||
@@ -52,20 +52,40 @@ Migrating from an earlier version of this project? See our [upgrade guide](Migra
|
||||
* [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)
|
||||
* [Password reset (“forgot password”)](#password-reset-forgot-password)
|
||||
* [Changing the current user’s password](#changing-the-current-users-password)
|
||||
* [Changing the current user’s email address](#changing-the-current-users-email-address)
|
||||
* [Re-sending confirmation requests](#re-sending-confirmation-requests)
|
||||
* [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)
|
||||
* [Checking whether the user was “remembered”](#checking-whether-the-user-was-remembered)
|
||||
* [IP address](#ip-address)
|
||||
* [Additional user information](#additional-user-information)
|
||||
* [Reconfirming the user’s password](#reconfirming-the-users-password)
|
||||
* [Roles (or groups)](#roles-or-groups)
|
||||
* [Checking roles](#checking-roles)
|
||||
* [Available roles](#available-roles)
|
||||
* [Permissions (or access rights, privileges or capabilities)](#permissions-or-access-rights-privileges-or-capabilities)
|
||||
* [Custom role names](#custom-role-names)
|
||||
* [Enabling or disabling password resets](#enabling-or-disabling-password-resets)
|
||||
* [Throttling or rate limiting](#throttling-or-rate-limiting)
|
||||
* [Administration (managing users)](#administration-managing-users)
|
||||
* [Creating new users](#creating-new-users)
|
||||
* [Deleting users](#deleting-users)
|
||||
* [Assigning roles to users](#assigning-roles-to-users)
|
||||
* [Taking roles away from users](#taking-roles-away-from-users)
|
||||
* [Checking roles](#checking-roles-1)
|
||||
* [Impersonating users (logging in as user)](#impersonating-users-logging-in-as-user)
|
||||
* [Cookies](#cookies)
|
||||
* [Renaming the library’s cookies](#renaming-the-librarys-cookies)
|
||||
* [Defining the domain scope for cookies](#defining-the-domain-scope-for-cookies)
|
||||
* [Restricting the path where cookies are available](#restricting-the-path-where-cookies-are-available)
|
||||
* [Controlling client-side script access to cookies](#controlling-client-side-script-access-to-cookies)
|
||||
* [Configuring transport security for cookies](#configuring-transport-security-for-cookies)
|
||||
* [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)
|
||||
@@ -74,9 +94,9 @@ Migrating from an earlier version of this project? See our [upgrade guide](Migra
|
||||
### Creating a new instance
|
||||
|
||||
```php
|
||||
// $db = new PDO('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
|
||||
// $db = new \PDO('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
|
||||
// or
|
||||
// $db = new PDO('sqlite:../Databases/my-database.sqlite');
|
||||
// $db = new \PDO('sqlite:../Databases/my-database.sqlite');
|
||||
|
||||
// or
|
||||
|
||||
@@ -89,11 +109,9 @@ $auth = new \Delight\Auth\Auth($db);
|
||||
|
||||
If you have an open `PDO` connection already, just re-use it.
|
||||
|
||||
If you do enforce HTTPS on your site, pass `true` as the second parameter to the constructor. This is optional and the default is `false`.
|
||||
If your web server is behind a proxy server and `$_SERVER['REMOTE_ADDR']` only contains the proxy’s IP address, you must pass the user’s real IP address to the constructor in the second argument, which is named `$ipAddress`. The default is `null`.
|
||||
|
||||
Only in the very rare case that you need access to your cookies from JavaScript, pass `true` as the third argument to the constructor. This is optional and the default is `false`. There is almost always a *better* solution than enabling this, however.
|
||||
|
||||
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`.
|
||||
Should your database tables for this library need a common prefix, e.g. `my_users` instead of `users` (and likewise for the other tables), pass the prefix (e.g. `my_`) as the third parameter to the constructor, which is named `$dbTablePrefix`. This is optional and the prefix is empty by default.
|
||||
|
||||
### Registration (sign up)
|
||||
|
||||
@@ -119,17 +137,17 @@ catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
}
|
||||
```
|
||||
|
||||
The username in the third parameter is optional. You can pass `null` there 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.:
|
||||
|
||||
```php
|
||||
$url = 'https://www.example.com/verify_email?selector='.urlencode($selector).'&token='.urlencode($token);
|
||||
$url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector) . '&token=' . \urlencode($token);
|
||||
```
|
||||
|
||||
If you don't want to perform email verification, just omit the last parameter to `Auth#register`. 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.
|
||||
|
||||
### Login (sign in)
|
||||
|
||||
@@ -153,7 +171,7 @@ 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).
|
||||
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
|
||||
|
||||
@@ -171,14 +189,19 @@ catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
|
||||
catch (\Delight\Auth\TokenExpiredException $e) {
|
||||
// token expired
|
||||
}
|
||||
catch (\Delight\Auth\UserAlreadyExistsException $e) {
|
||||
// email address already exists
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
}
|
||||
```
|
||||
|
||||
If you want the user to be automatically signed in after successful confirmation, just call `confirmEmailAndSignIn` instead of `confirmEmail`. That alternative method also supports [persistent logins](#keeping-the-user-logged-in) via its optional third parameter.
|
||||
|
||||
### 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.
|
||||
The third parameter to the `Auth#login` and `Auth#confirmEmailAndSignIn` methods controls whether the login is persistent with a long-lived cookie. With such a persistent login, users may stay authenticated for a long time, even when the browser session has already been closed and the session cookies have expired. Typically, you’ll want to keep the user logged in for weeks or months with this feature, which is known as “remember me” or “keep me logged in”. Many users will find this more convenient, but it may be less secure if they leave their devices unattended.
|
||||
|
||||
```php
|
||||
if ($_POST['remember'] == 1) {
|
||||
@@ -199,9 +222,9 @@ $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.
|
||||
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")
|
||||
### Password reset (“forgot password”)
|
||||
|
||||
```php
|
||||
try {
|
||||
@@ -217,6 +240,9 @@ catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email not verified
|
||||
}
|
||||
catch (\Delight\Auth\ResetDisabledException $e) {
|
||||
// password reset is disabled
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
}
|
||||
@@ -225,7 +251,7 @@ catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
You should build an URL with the selector and token and send it to the user, e.g.:
|
||||
|
||||
```php
|
||||
$url = 'https://www.example.com/reset_password?selector='.urlencode($selector).'&token='.urlencode($token);
|
||||
$url = 'https://www.example.com/reset_password?selector=' . \urlencode($selector) . '&token=' . \urlencode($token);
|
||||
```
|
||||
|
||||
As the next step, users will click on the link that they received. Extract the selector and token from the URL.
|
||||
@@ -255,6 +281,9 @@ catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
|
||||
catch (\Delight\Auth\TokenExpiredException $e) {
|
||||
// token expired
|
||||
}
|
||||
catch (\Delight\Auth\ResetDisabledException $e) {
|
||||
// password reset is disabled
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
// invalid password
|
||||
}
|
||||
@@ -263,7 +292,7 @@ catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
}
|
||||
```
|
||||
|
||||
### Changing the current user's password
|
||||
### Changing the current user’s password
|
||||
|
||||
If a user is currently logged in, they may change their password.
|
||||
|
||||
@@ -279,12 +308,109 @@ catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
// invalid password(s)
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
}
|
||||
```
|
||||
|
||||
Asking the user for their current (and soon *old*) password and requiring it for verification is the recommended way to handle password changes. This is shown above.
|
||||
|
||||
If you’re sure that you don’t need that confirmation, however, you may call `changePasswordWithoutOldPassword` instead of `changePassword` and drop the first parameter from that method call (which would otherwise contain the old password).
|
||||
|
||||
In any case, after the user’s password has been changed, you should send an email to their account’s primary email address as an out-of-band notification informing the account owner about this critical change.
|
||||
|
||||
### Changing the current user’s email address
|
||||
|
||||
If a user is currently logged in, they may change their email address.
|
||||
|
||||
```php
|
||||
try {
|
||||
if ($auth->reconfirmPassword($_POST['password'])) {
|
||||
$auth->changeEmail($_POST['newEmail'], function ($selector, $token) {
|
||||
// send `$selector` and `$token` to the user (e.g. via email to the *new* address)
|
||||
});
|
||||
|
||||
// the change will take effect as soon as the new email address has been confirmed
|
||||
}
|
||||
else {
|
||||
// we can't say if the user is who they claim to be
|
||||
}
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// invalid email address
|
||||
}
|
||||
catch (\Delight\Auth\UserAlreadyExistsException $e) {
|
||||
// email address already exists
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// account not verified
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
// not logged in
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
}
|
||||
```
|
||||
|
||||
For email verification, you should build an URL with the selector and token and send it to the user, e.g.:
|
||||
|
||||
```php
|
||||
$url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector) . '&token=' . \urlencode($token);
|
||||
```
|
||||
|
||||
After the request to change the email address has been made, or even better, after the change has been confirmed by the user, you should send an email to their account’s *previous* email address as an out-of-band notification informing the account owner about this critical change.
|
||||
|
||||
### Re-sending confirmation requests
|
||||
|
||||
If an earlier confirmation request could not be delivered to the user, or if the user missed that request, or if they just don’t want to wait any longer, you may re-send an earlier request like this:
|
||||
|
||||
```php
|
||||
try {
|
||||
$auth->resendConfirmationForEmail($_POST['email'], function ($selector, $token) {
|
||||
// send `$selector` and `$token` to the user (e.g. via email)
|
||||
});
|
||||
|
||||
// the user may now respond to the confirmation request (usually by clicking a link)
|
||||
}
|
||||
catch (\Delight\Auth\ConfirmationRequestNotFound $e) {
|
||||
// no earlier request found that could be re-sent
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// there have been too many requests -- try again later
|
||||
}
|
||||
```
|
||||
|
||||
If you want to specify the user by their ID instead of by their email address, this is possible as well:
|
||||
|
||||
```php
|
||||
try {
|
||||
$auth->resendConfirmationForUserId($_POST['userId'], function ($selector, $token) {
|
||||
// send `$selector` and `$token` to the user (e.g. via email)
|
||||
});
|
||||
|
||||
// the user may now respond to the confirmation request (usually by clicking a link)
|
||||
}
|
||||
catch (\Delight\Auth\ConfirmationRequestNotFound $e) {
|
||||
// no earlier request found that could be re-sent
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// there have been too many requests -- try again later
|
||||
}
|
||||
```
|
||||
|
||||
Usually, you should build an URL with the selector and token and send it to the user, e.g. as follows:
|
||||
|
||||
```php
|
||||
$url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector) . '&token=' . \urlencode($token);
|
||||
```
|
||||
|
||||
### Logout
|
||||
|
||||
```php
|
||||
$auth->logout();
|
||||
$auth->logOut();
|
||||
// or
|
||||
$auth->logOutAndDestroySession();
|
||||
|
||||
// user has been signed out
|
||||
```
|
||||
@@ -360,7 +486,7 @@ if ($auth->isSuspended()) {
|
||||
}
|
||||
```
|
||||
|
||||
#### Checking whether the user was "remembered"
|
||||
#### Checking whether the user was “remembered”
|
||||
|
||||
```php
|
||||
if ($auth->isRemembered()) {
|
||||
@@ -381,13 +507,13 @@ $ip = $auth->getIpAddress();
|
||||
|
||||
#### Additional user information
|
||||
|
||||
In order to preserve this library's suitability for all purposes as well as its full re-usability, it doesn't come with additional bundled columns for user information. But you don't have to do without additional user information, of course:
|
||||
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:
|
||||
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:
|
||||
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) {
|
||||
@@ -404,6 +530,228 @@ Here's how to use this library with your own tables for custom user information
|
||||
}
|
||||
```
|
||||
|
||||
### Reconfirming the user’s password
|
||||
|
||||
Whenever you want to confirm the user’s identity again, e.g. before the user is allowed to perform some “dangerous” action, you should verify their password again to confirm that they actually are who they claim to be.
|
||||
|
||||
For example, when a user has been remembered by a long-lived cookie and thus `Auth#isRemembered` returns `true`, this means that the user probably has not entered their password for quite some time anymore. You may want to reconfirm their password in that case.
|
||||
|
||||
```php
|
||||
try {
|
||||
if ($auth->reconfirmPassword($_POST['password'])) {
|
||||
// the user really seems to be who they claim to be
|
||||
}
|
||||
else {
|
||||
// we can't say if the user is who they claim to be
|
||||
}
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
// the user is not signed in
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
}
|
||||
```
|
||||
|
||||
### Roles (or groups)
|
||||
|
||||
Every user can have any number of roles, which you can use to implement authorization and to refine your access controls.
|
||||
|
||||
Users may have no role at all (which they do by default), exactly one role, or any arbitrary combination of roles.
|
||||
|
||||
#### Checking roles
|
||||
|
||||
```php
|
||||
if ($auth->hasRole(\Delight\Auth\Role::SUPER_MODERATOR)) {
|
||||
// the user is a super moderator
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
if ($auth->hasAnyRole(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER)) {
|
||||
// the user is either a developer, or a manager, or both
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
if ($auth->hasAllRoles(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER)) {
|
||||
// the user is both a developer and a manager
|
||||
}
|
||||
```
|
||||
|
||||
While the method `hasRole` takes exactly one role as its argument, the two methods `hasAnyRole` and `hasAllRoles` can take any number of roles that you would like to check for.
|
||||
|
||||
#### Available roles
|
||||
|
||||
```php
|
||||
\Delight\Auth\Role::ADMIN;
|
||||
\Delight\Auth\Role::AUTHOR;
|
||||
\Delight\Auth\Role::COLLABORATOR;
|
||||
\Delight\Auth\Role::CONSULTANT;
|
||||
\Delight\Auth\Role::CONSUMER;
|
||||
\Delight\Auth\Role::CONTRIBUTOR;
|
||||
\Delight\Auth\Role::COORDINATOR;
|
||||
\Delight\Auth\Role::CREATOR;
|
||||
\Delight\Auth\Role::DEVELOPER;
|
||||
\Delight\Auth\Role::DIRECTOR;
|
||||
\Delight\Auth\Role::EDITOR;
|
||||
\Delight\Auth\Role::EMPLOYEE;
|
||||
\Delight\Auth\Role::MAINTAINER;
|
||||
\Delight\Auth\Role::MANAGER;
|
||||
\Delight\Auth\Role::MODERATOR;
|
||||
\Delight\Auth\Role::PUBLISHER;
|
||||
\Delight\Auth\Role::REVIEWER;
|
||||
\Delight\Auth\Role::SUBSCRIBER;
|
||||
\Delight\Auth\Role::SUPER_ADMIN;
|
||||
\Delight\Auth\Role::SUPER_EDITOR;
|
||||
\Delight\Auth\Role::SUPER_MODERATOR;
|
||||
\Delight\Auth\Role::TRANSLATOR;
|
||||
```
|
||||
|
||||
You can use any of these roles and ignore those that you don’t need.
|
||||
|
||||
#### Permissions (or access rights, privileges or capabilities)
|
||||
|
||||
The permissions of each user are encoded in the way that role requirements are specified throughout your code base. If those requirements are evaluated with a specific user’s set of roles, implicitly checked permissions are the result.
|
||||
|
||||
For larger projects, it is often recommended to maintain the definition of permissions in a single place. You then don’t check for *roles* in your business logic, but you check for *individual permissions*. You could implement that concept as follows:
|
||||
|
||||
```php
|
||||
function canEditArticle(\Delight\Auth\Auth $auth) {
|
||||
return $auth->hasAnyRole(
|
||||
\Delight\Auth\Role::MODERATOR,
|
||||
\Delight\Auth\Role::SUPER_MODERATOR,
|
||||
\Delight\Auth\Role::ADMIN,
|
||||
\Delight\Auth\Role::SUPER_ADMIN
|
||||
);
|
||||
}
|
||||
|
||||
// ...
|
||||
|
||||
if (canEditArticle($app->auth())) {
|
||||
// the user can edit articles here
|
||||
}
|
||||
|
||||
// ...
|
||||
|
||||
if (canEditArticle($app->auth())) {
|
||||
// ... and here
|
||||
}
|
||||
|
||||
// ...
|
||||
|
||||
if (canEditArticle($app->auth())) {
|
||||
// ... and here
|
||||
}
|
||||
```
|
||||
|
||||
As you can see, the permission of whether a certain user can edit an article is stored at a central location. This implementation has two major advantages:
|
||||
|
||||
If you *want to know* which users can edit articles, you don’t have to check your business logic in various places, but you only have to look where the specific permission is defined. And if you want to *change* who can edit an article, you only have to do this in one single place as well, not throughout your whole code base.
|
||||
|
||||
But this also comes with slightly more overhead when implementing the access restrictions for the first time, which may or may not be worth it for your project.
|
||||
|
||||
#### Custom role names
|
||||
|
||||
If the names of the included roles don’t work for you, you can alias any number of roles using your own identifiers, e.g. like this:
|
||||
|
||||
```php
|
||||
namespace My\Namespace;
|
||||
|
||||
final class MyRole {
|
||||
|
||||
const CUSTOMER_SERVICE_AGENT = \Delight\Auth\Role::REVIEWER;
|
||||
const FINANCIAL_DIRECTOR = \Delight\Auth\Role::COORDINATOR;
|
||||
|
||||
private function __construct() {}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
The example above would allow you to use
|
||||
|
||||
```php
|
||||
\My\Namespace\MyRole::CUSTOMER_SERVICE_AGENT;
|
||||
// and
|
||||
\My\Namespace\MyRole::FINANCIAL_DIRECTOR;
|
||||
```
|
||||
|
||||
instead of
|
||||
|
||||
```php
|
||||
\Delight\Auth\Role::REVIEWER;
|
||||
// and
|
||||
\Delight\Auth\Role::COORDINATOR;
|
||||
```
|
||||
|
||||
Just remember *not* to alias a *single* included role to *multiple* roles with custom names.
|
||||
|
||||
### Enabling or disabling password resets
|
||||
|
||||
While password resets via email are a convenient feature that most users find helpful from time to time, the availability of this feature implies that accounts on your service are only ever as secure as the user’s associated email account.
|
||||
|
||||
You may provide security-conscious (and experienced) users with the possibility to disable password resets for their accounts (and to enable them again later) for enhanced security:
|
||||
|
||||
```php
|
||||
try {
|
||||
if ($auth->reconfirmPassword($_POST['password'])) {
|
||||
$auth->setPasswordResetEnabled($_POST['enabled'] == 1);
|
||||
|
||||
// the setting has been changed
|
||||
}
|
||||
else {
|
||||
// we can't say if the user is who they claim to be
|
||||
}
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
// the user is not signed in
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
}
|
||||
```
|
||||
|
||||
In order to check the current value of this setting, use the return value from
|
||||
|
||||
```php
|
||||
$auth->isPasswordResetEnabled();
|
||||
```
|
||||
|
||||
for the correct default option in your user interface. You don’t need to check this value for restrictions of the feature, which are enforced automatically.
|
||||
|
||||
### Throttling or rate limiting
|
||||
|
||||
All methods provided by this library are *automatically* protected against excessive numbers of requests from clients.
|
||||
|
||||
If you would like to throttle or rate limit *external* features or methods as well, e.g. those in your own code, you can make use of the built-in helper method for throttling and rate limiting:
|
||||
|
||||
```php
|
||||
try {
|
||||
// throttle the specified resource or feature to *3* requests per *60* seconds
|
||||
$auth->throttle([ 'my-resource-name' ], 3, 60);
|
||||
|
||||
// do something with the resource or feature
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// operation cancelled
|
||||
|
||||
\http_response_code(429);
|
||||
exit;
|
||||
}
|
||||
```
|
||||
|
||||
If the protection of the resource or feature should additionally depend on another attribute, e.g. to track something separately per IP address, just add more data to the resource description, such as:
|
||||
|
||||
```php
|
||||
[ 'my-resource-name', $_SERVER['REMOTE_ADDR'] ]
|
||||
// instead of
|
||||
// [ 'my-resource-name' ]
|
||||
```
|
||||
|
||||
Allowing short bursts of activity during peak demand is possible by specifying a burst factor as the fourth argument. A value of `5`, for example, would permit temporary bursts of fivefold activity, compared to the generally accepted level.
|
||||
|
||||
In some cases, you may just want to *simulate* the throttling or rate limiting. This lets you check whether an action would be permitted without actually modifying the activity tracker. To do so, simply pass `true` as the fifth argument.
|
||||
|
||||
### Administration (managing users)
|
||||
|
||||
The administrative interface is available via `$auth->admin()`. You can call various method on this interface, as documented below.
|
||||
@@ -429,7 +777,7 @@ catch (\Delight\Auth\UserAlreadyExistsException $e) {
|
||||
}
|
||||
```
|
||||
|
||||
The username in the third parameter is optional. You can pass `null` there 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 `createUserWithUniqueUsername` instead of `createUser`, and be prepared to catch the `DuplicateUsernameException`.
|
||||
|
||||
@@ -471,6 +819,259 @@ catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
}
|
||||
```
|
||||
|
||||
#### Assigning roles to users
|
||||
|
||||
```php
|
||||
try {
|
||||
$auth->admin()->addRoleForUserById($userId, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown user ID
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
try {
|
||||
$auth->admin()->addRoleForUserByEmail($userEmail, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// unknown email address
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
try {
|
||||
$auth->admin()->addRoleForUserByUsername($username, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
// unknown username
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
// ambiguous username
|
||||
}
|
||||
```
|
||||
|
||||
#### Taking roles away from users
|
||||
|
||||
```php
|
||||
try {
|
||||
$auth->admin()->removeRoleForUserById($userId, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown user ID
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
try {
|
||||
$auth->admin()->removeRoleForUserByEmail($userEmail, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// unknown email address
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
try {
|
||||
$auth->admin()->removeRoleForUserByUsername($username, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
// unknown username
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
// ambiguous username
|
||||
}
|
||||
```
|
||||
|
||||
#### Checking roles
|
||||
|
||||
```php
|
||||
try {
|
||||
if ($auth->admin()->doesUserHaveRole($userId, \Delight\Auth\Role::ADMIN)) {
|
||||
// the specified user is an administrator
|
||||
}
|
||||
else {
|
||||
// the specified user is *not* an administrator
|
||||
}
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown user ID
|
||||
}
|
||||
```
|
||||
|
||||
#### Impersonating users (logging in as user)
|
||||
|
||||
```php
|
||||
try {
|
||||
$auth->admin()->logInAsUserById($_POST['id']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown ID
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email address not verified
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
try {
|
||||
$auth->admin()->logInAsUserByEmail($_POST['email']);
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// unknown email address
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email address not verified
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
try {
|
||||
$auth->admin()->logInAsUserByUsername($_POST['username']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
// unknown username
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
// ambiguous username
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email address not verified
|
||||
}
|
||||
```
|
||||
|
||||
### Cookies
|
||||
|
||||
This library uses two cookies to keep state on the client: The first, whose name you can retrieve using
|
||||
|
||||
```php
|
||||
\session_name();
|
||||
```
|
||||
|
||||
is the general (mandatory) session cookie. The second (optional) cookie is only used for [persistent logins](#keeping-the-user-logged-in) and its name can be retrieved as follows:
|
||||
|
||||
```php
|
||||
\Delight\Auth\Auth::createRememberCookieName();
|
||||
```
|
||||
|
||||
#### Renaming the library’s cookies
|
||||
|
||||
You can rename the session cookie used by this library through one of the following means, in order of recommendation:
|
||||
|
||||
* In the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), find the line with the `session.name` directive and change its value to something like `session_v1`, as in:
|
||||
|
||||
```
|
||||
session.name = session_v1
|
||||
```
|
||||
|
||||
* As early as possible in your application, and before you create the `Auth` instance, call `\ini_set` to change `session.name` to something like `session_v1`, as in:
|
||||
|
||||
```php
|
||||
\ini_set('session.name', 'session_v1');
|
||||
```
|
||||
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`).
|
||||
|
||||
* As early as possible in your application, and before you create the `Auth` instance, call `\session_name` with an argument like `session_v1`, as in:
|
||||
|
||||
```php
|
||||
\session_name('session_v1');
|
||||
```
|
||||
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`).
|
||||
|
||||
The name of the cookie for [persistent logins](#keeping-the-user-logged-in) will change as well – automatically – following your change of the session cookie’s name.
|
||||
|
||||
#### Defining the domain scope for cookies
|
||||
|
||||
A cookie’s `domain` attribute controls which domain (and which subdomains) the cookie will be valid for, and thus where the user’s session and authentication state will be available.
|
||||
|
||||
The recommended default is an empty string, which means that the cookie will only be valid for the *exact* current host, *excluding* any subdomains that may exist. You should only use a different value if you need to share cookies between different subdomains. Often, you’ll want to share cookies between the bare domain and the `www` subdomain, but you might also want to share them between any other set of subdomains.
|
||||
|
||||
Whatever set of subdomains you choose, you should set the cookie’s attribute to the *most specific* domain name that still includes all your required subdomains. For example, to share cookies between `example.com` and `www.example.com`, you would set the attribute to `example.com`. But if you wanted to share cookies between `sub1.app.example.com` and `sub2.app.example.com`, you should set the attribute to `app.example.com`. Any explicitly specified domain name will always *include* all subdomains that may exist.
|
||||
|
||||
You can change the attribute through one of the following means, in order of recommendation:
|
||||
|
||||
* In the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), find the line with the `session.cookie_domain` directive and change its value as desired, e.g.:
|
||||
|
||||
```
|
||||
session.cookie_domain = example.com
|
||||
```
|
||||
|
||||
* As early as possible in your application, and before you create the `Auth` instance, call `\ini_set` to change the value of the `session.cookie_domain` directive as desired, e.g.:
|
||||
|
||||
```php
|
||||
\ini_set('session.cookie_domain', 'example.com');
|
||||
```
|
||||
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`).
|
||||
|
||||
#### Restricting the path where cookies are available
|
||||
|
||||
A cookie’s `path` attribute controls which directories (and subdirectories) the cookie will be valid for, and thus where the user’s session and authentication state will be available.
|
||||
|
||||
In most cases, you’ll want to make cookies available for all paths, i.e. any directory and file, starting in the root directory. That is what a value of `/` for the attribute does, which is also the recommended default. You should only change this attribute to a different value, e.g. `/path/to/subfolder`, if you want to restrict which directories your cookies will be available in, e.g. to host multiple applications side-by-side, in different directories, under the same domain name.
|
||||
|
||||
You can change the attribute through one of the following means, in order of recommendation:
|
||||
|
||||
* In the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), find the line with the `session.cookie_path` directive and change its value as desired, e.g.:
|
||||
|
||||
```
|
||||
session.cookie_path = /
|
||||
```
|
||||
|
||||
* As early as possible in your application, and before you create the `Auth` instance, call `\ini_set` to change the value of the `session.cookie_path` directive as desired, e.g.:
|
||||
|
||||
```php
|
||||
\ini_set('session.cookie_path', '/');
|
||||
```
|
||||
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`).
|
||||
|
||||
#### Controlling client-side script access to cookies
|
||||
|
||||
Using the `httponly` attribute, you can control whether client-side scripts, i.e. JavaScript, should be able to access your cookies or not. For security reasons, it is best to *deny* script access to your cookies, which reduces the damage that successful XSS attacks against your application could do, for example.
|
||||
|
||||
Thus, you should always set `httponly` to `1`, except for the rare cases where you really need access to your cookies from JavaScript and can’t find any better solution. In those cases, set the attribute to `0`, but be aware of the consequences.
|
||||
|
||||
You can change the attribute through one of the following means, in order of recommendation:
|
||||
|
||||
* In the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), find the line with the `session.cookie_httponly` directive and change its value as desired, e.g.:
|
||||
|
||||
```
|
||||
session.cookie_httponly = 1
|
||||
```
|
||||
|
||||
* As early as possible in your application, and before you create the `Auth` instance, call `\ini_set` to change the value of the `session.cookie_httponly` directive as desired, e.g.:
|
||||
|
||||
```php
|
||||
\ini_set('session.cookie_httponly', 1);
|
||||
```
|
||||
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`).
|
||||
|
||||
#### Configuring transport security for cookies
|
||||
|
||||
Using the `secure` attribute, you can control whether cookies should be sent over *any* connection, including plain HTTP, or whether a secure connection, i.e. HTTPS (with SSL/TLS), should be required. The former (less secure) mode can be chosen by setting the attribute to `0`, and the latter (more secure) mode can be chosen by setting the attribute to `1`.
|
||||
|
||||
Obviously, this solely depends on whether you are able to serve *all* pages exclusively via HTTPS. If you can, you should set the attribute to `1` and possibly combine it with HTTP redirects to the secure protocol and HTTP Strict Transport Security (HSTS). Otherwise, you may have to keep the attribute set to `0`.
|
||||
|
||||
You can change the attribute through one of the following means, in order of recommendation:
|
||||
|
||||
* In the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), find the line with the `session.cookie_secure` directive and change its value as desired, e.g.:
|
||||
|
||||
```
|
||||
session.cookie_secure = 1
|
||||
```
|
||||
|
||||
* As early as possible in your application, and before you create the `Auth` instance, call `\ini_set` to change the value of the `session.cookie_secure` directive as desired, e.g.:
|
||||
|
||||
```php
|
||||
\ini_set('session.cookie_secure', 1);
|
||||
```
|
||||
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`).
|
||||
|
||||
### Utilities
|
||||
|
||||
#### Creating a random string
|
||||
@@ -494,11 +1095,11 @@ For detailed information on how to read and write session data conveniently, ple
|
||||
|
||||
### 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.
|
||||
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.
|
||||
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?
|
||||
|
||||
@@ -508,13 +1109,13 @@ To allow for maximum flexibility and ease of use, this library has been designed
|
||||
|
||||
```php
|
||||
function isPasswordAllowed($password) {
|
||||
if (strlen($password) < 8) {
|
||||
if (\strlen($password) < 8) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$blacklist = [ 'password1', '123456', 'qwerty' ];
|
||||
|
||||
if (in_array($password, $blacklist)) {
|
||||
if (\in_array($password, $blacklist)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -526,6 +1127,18 @@ if (isPasswordAllowed($password)) {
|
||||
}
|
||||
```
|
||||
|
||||
### Why are there problems when using other libraries that work with sessions?
|
||||
|
||||
You might try loading this library first, and creating the `Auth` instance first, *before* loading the other libraries. Apart from that, there’s probably not much we can do here.
|
||||
|
||||
### Why are other sites not able to frame or embed my site?
|
||||
|
||||
If you want to let others include your site in a `<frame>`, `<iframe>`, `<object>`, `<embed>` or `<applet>` element, you have to disable the default clickjacking prevention:
|
||||
|
||||
```php
|
||||
\header_remove('X-Frame-Options');
|
||||
```
|
||||
|
||||
## Exceptions
|
||||
|
||||
This library throws two types of exceptions to indicate problems:
|
||||
@@ -537,11 +1150,11 @@ This library throws two types of exceptions to indicate problems:
|
||||
|
||||
* 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.
|
||||
* 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, 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.
|
||||
* Before executing sensitive account operations (e.g. changing a user’s email address, deleting a user’s account), you should always require re-authentication, i.e. require the user to verify their login credentials once more.
|
||||
* You should not offer an online password reset feature (“forgot password”) for high-security applications.
|
||||
* For high-security applications, you should not use email addresses as identifiers. Instead, choose identifiers that are specific to the application and secret, e.g. an internal customer number.
|
||||
|
||||
## Contributing
|
||||
|
@@ -4,7 +4,8 @@
|
||||
"require": {
|
||||
"php": ">=5.6.0",
|
||||
"ext-openssl": "*",
|
||||
"delight-im/cookie": "^2.1",
|
||||
"delight-im/base64": "^1.0",
|
||||
"delight-im/cookie": "^3.1",
|
||||
"delight-im/db": "^1.2"
|
||||
},
|
||||
"type": "library",
|
||||
|
59
composer.lock
generated
59
composer.lock
generated
@@ -4,25 +4,66 @@
|
||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"content-hash": "c075bec19490fc0e972be01cdd02d59b",
|
||||
"content-hash": "54d541ae3c5ba25b0cc06688d2b65467",
|
||||
"packages": [
|
||||
{
|
||||
"name": "delight-im/cookie",
|
||||
"version": "v2.1.1",
|
||||
"name": "delight-im/base64",
|
||||
"version": "v1.0.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/delight-im/PHP-Cookie.git",
|
||||
"reference": "22f2c19750a6ad3dbf69a8ef3ea0e454a8e064fa"
|
||||
"url": "https://github.com/delight-im/PHP-Base64.git",
|
||||
"reference": "687b2a49f663e162030a8d27b32838bbe7f91c78"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/delight-im/PHP-Cookie/zipball/22f2c19750a6ad3dbf69a8ef3ea0e454a8e064fa",
|
||||
"reference": "22f2c19750a6ad3dbf69a8ef3ea0e454a8e064fa",
|
||||
"url": "https://api.github.com/repos/delight-im/PHP-Base64/zipball/687b2a49f663e162030a8d27b32838bbe7f91c78",
|
||||
"reference": "687b2a49f663e162030a8d27b32838bbe7f91c78",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=5.3.0"
|
||||
},
|
||||
"type": "library",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Delight\\Base64\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"description": "Simple and convenient Base64 encoding and decoding for PHP",
|
||||
"homepage": "https://github.com/delight-im/PHP-Base64",
|
||||
"keywords": [
|
||||
"URL-safe",
|
||||
"base-64",
|
||||
"base64",
|
||||
"decode",
|
||||
"decoding",
|
||||
"encode",
|
||||
"encoding",
|
||||
"url"
|
||||
],
|
||||
"time": "2017-07-24T18:59:51+00:00"
|
||||
},
|
||||
{
|
||||
"name": "delight-im/cookie",
|
||||
"version": "v3.1.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/delight-im/PHP-Cookie.git",
|
||||
"reference": "76ef2a21817cf7a034f85fc3f4d4bfc60f873947"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/delight-im/PHP-Cookie/zipball/76ef2a21817cf7a034f85fc3f4d4bfc60f873947",
|
||||
"reference": "76ef2a21817cf7a034f85fc3f4d4bfc60f873947",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"delight-im/http": "^2.0",
|
||||
"php": ">=5.6.0"
|
||||
"php": ">=5.4.0"
|
||||
},
|
||||
"type": "library",
|
||||
"autoload": {
|
||||
@@ -45,7 +86,7 @@
|
||||
"samesite",
|
||||
"xss"
|
||||
],
|
||||
"time": "2016-12-18T20:22:46+00:00"
|
||||
"time": "2017-10-18T19:48:59+00:00"
|
||||
},
|
||||
{
|
||||
"name": "delight-im/db",
|
||||
|
@@ -20,9 +20,10 @@ final class Administration extends UserManager {
|
||||
* @internal
|
||||
*
|
||||
* @param PdoDatabase $databaseConnection the database connection to operate on
|
||||
* @param string|null $dbTablePrefix (optional) the prefix for the names of all database tables used by this component
|
||||
*/
|
||||
public function __construct(PdoDatabase $databaseConnection) {
|
||||
parent::__construct($databaseConnection);
|
||||
public function __construct(PdoDatabase $databaseConnection, $dbTablePrefix = null) {
|
||||
parent::__construct($databaseConnection, $dbTablePrefix);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -106,15 +107,237 @@ final class Administration extends UserManager {
|
||||
*/
|
||||
public function deleteUserByUsername($username) {
|
||||
$userData = $this->getUserDataByUsername(
|
||||
trim($username),
|
||||
\trim($username),
|
||||
[ 'id' ]
|
||||
);
|
||||
|
||||
$this->deleteUsersByColumnValue('id', (int) $userData['id']);
|
||||
}
|
||||
|
||||
protected function throttle($actionType, $customSelector = null) {
|
||||
// do nothing
|
||||
/**
|
||||
* Assigns the specified role to the user with the given ID
|
||||
*
|
||||
* A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles)
|
||||
*
|
||||
* @param int $userId the ID of the user to assign the role to
|
||||
* @param int $role the role as one of the constants from the {@see Role} class
|
||||
* @throws UnknownIdException if no user with the specified ID has been found
|
||||
*
|
||||
* @see Role
|
||||
*/
|
||||
public function addRoleForUserById($userId, $role) {
|
||||
$userFound = $this->addRoleForUserByColumnValue(
|
||||
'id',
|
||||
(int) $userId,
|
||||
$role
|
||||
);
|
||||
|
||||
if ($userFound === false) {
|
||||
throw new UnknownIdException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns the specified role to the user with the given email address
|
||||
*
|
||||
* A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles)
|
||||
*
|
||||
* @param string $userEmail the email address of the user to assign the role to
|
||||
* @param int $role the role as one of the constants from the {@see Role} class
|
||||
* @throws InvalidEmailException if no user with the specified email address has been found
|
||||
*
|
||||
* @see Role
|
||||
*/
|
||||
public function addRoleForUserByEmail($userEmail, $role) {
|
||||
$userEmail = self::validateEmailAddress($userEmail);
|
||||
|
||||
$userFound = $this->addRoleForUserByColumnValue(
|
||||
'email',
|
||||
$userEmail,
|
||||
$role
|
||||
);
|
||||
|
||||
if ($userFound === false) {
|
||||
throw new InvalidEmailException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns the specified role to the user with the given username
|
||||
*
|
||||
* A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles)
|
||||
*
|
||||
* @param string $username the username of the user to assign the role to
|
||||
* @param int $role the role as one of the constants from the {@see Role} class
|
||||
* @throws UnknownUsernameException if no user with the specified username has been found
|
||||
* @throws AmbiguousUsernameException if multiple users with the specified username have been found
|
||||
*
|
||||
* @see Role
|
||||
*/
|
||||
public function addRoleForUserByUsername($username, $role) {
|
||||
$userData = $this->getUserDataByUsername(
|
||||
\trim($username),
|
||||
[ 'id' ]
|
||||
);
|
||||
|
||||
$this->addRoleForUserByColumnValue(
|
||||
'id',
|
||||
(int) $userData['id'],
|
||||
$role
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes away the specified role from the user with the given ID
|
||||
*
|
||||
* A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles)
|
||||
*
|
||||
* @param int $userId the ID of the user to take the role away from
|
||||
* @param int $role the role as one of the constants from the {@see Role} class
|
||||
* @throws UnknownIdException if no user with the specified ID has been found
|
||||
*
|
||||
* @see Role
|
||||
*/
|
||||
public function removeRoleForUserById($userId, $role) {
|
||||
$userFound = $this->removeRoleForUserByColumnValue(
|
||||
'id',
|
||||
(int) $userId,
|
||||
$role
|
||||
);
|
||||
|
||||
if ($userFound === false) {
|
||||
throw new UnknownIdException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes away the specified role from the user with the given email address
|
||||
*
|
||||
* A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles)
|
||||
*
|
||||
* @param string $userEmail the email address of the user to take the role away from
|
||||
* @param int $role the role as one of the constants from the {@see Role} class
|
||||
* @throws InvalidEmailException if no user with the specified email address has been found
|
||||
*
|
||||
* @see Role
|
||||
*/
|
||||
public function removeRoleForUserByEmail($userEmail, $role) {
|
||||
$userEmail = self::validateEmailAddress($userEmail);
|
||||
|
||||
$userFound = $this->removeRoleForUserByColumnValue(
|
||||
'email',
|
||||
$userEmail,
|
||||
$role
|
||||
);
|
||||
|
||||
if ($userFound === false) {
|
||||
throw new InvalidEmailException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes away the specified role from the user with the given username
|
||||
*
|
||||
* A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles)
|
||||
*
|
||||
* @param string $username the username of the user to take the role away from
|
||||
* @param int $role the role as one of the constants from the {@see Role} class
|
||||
* @throws UnknownUsernameException if no user with the specified username has been found
|
||||
* @throws AmbiguousUsernameException if multiple users with the specified username have been found
|
||||
*
|
||||
* @see Role
|
||||
*/
|
||||
public function removeRoleForUserByUsername($username, $role) {
|
||||
$userData = $this->getUserDataByUsername(
|
||||
\trim($username),
|
||||
[ 'id' ]
|
||||
);
|
||||
|
||||
$this->removeRoleForUserByColumnValue(
|
||||
'id',
|
||||
(int) $userData['id'],
|
||||
$role
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the user with the given ID has the specified role
|
||||
*
|
||||
* @param int $userId the ID of the user to check the roles for
|
||||
* @param int $role the role as one of the constants from the {@see Role} class
|
||||
* @return bool
|
||||
* @throws UnknownIdException if no user with the specified ID has been found
|
||||
*
|
||||
* @see Role
|
||||
*/
|
||||
public function doesUserHaveRole($userId, $role) {
|
||||
$userId = (int) $userId;
|
||||
$role = (int) $role;
|
||||
|
||||
$rolesBitmask = $this->db->selectValue(
|
||||
'SELECT roles_mask FROM ' . $this->dbTablePrefix . 'users WHERE id = ?',
|
||||
[ $userId ]
|
||||
);
|
||||
|
||||
if ($rolesBitmask === null) {
|
||||
throw new UnknownIdException();
|
||||
}
|
||||
|
||||
return ($rolesBitmask & $role) === $role;
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs in as the user with the specified ID
|
||||
*
|
||||
* @param int $id the ID of the user to sign in as
|
||||
* @throws UnknownIdException if no user with the specified ID has been found
|
||||
* @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function logInAsUserById($id) {
|
||||
$numberOfMatchedUsers = $this->logInAsUserByColumnValue('id', (int) $id);
|
||||
|
||||
if ($numberOfMatchedUsers === 0) {
|
||||
throw new UnknownIdException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs in as the user with the specified email address
|
||||
*
|
||||
* @param string $email the email address of the user to sign in as
|
||||
* @throws InvalidEmailException if no user with the specified email address has been found
|
||||
* @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function logInAsUserByEmail($email) {
|
||||
$email = self::validateEmailAddress($email);
|
||||
|
||||
$numberOfMatchedUsers = $this->logInAsUserByColumnValue('email', $email);
|
||||
|
||||
if ($numberOfMatchedUsers === 0) {
|
||||
throw new InvalidEmailException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs in as the user with the specified display name
|
||||
*
|
||||
* @param string $username the display name of the user to sign in as
|
||||
* @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 EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function logInAsUserByUsername($username) {
|
||||
$numberOfMatchedUsers = $this->logInAsUserByColumnValue('username', \trim($username));
|
||||
|
||||
if ($numberOfMatchedUsers === 0) {
|
||||
throw new UnknownUsernameException();
|
||||
}
|
||||
elseif ($numberOfMatchedUsers > 1) {
|
||||
throw new AmbiguousUsernameException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -130,7 +353,7 @@ final class Administration extends UserManager {
|
||||
private function deleteUsersByColumnValue($columnName, $columnValue) {
|
||||
try {
|
||||
return $this->db->delete(
|
||||
'users',
|
||||
$this->dbTablePrefix . 'users',
|
||||
[
|
||||
$columnName => $columnValue
|
||||
]
|
||||
@@ -141,4 +364,136 @@ final class Administration extends UserManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Modifies the roles for the user 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
|
||||
* @param callable $modification the modification to apply to the existing bitmask of roles
|
||||
* @return bool whether any user with the given column constraints has been found
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*
|
||||
* @see Role
|
||||
*/
|
||||
private function modifyRolesForUserByColumnValue($columnName, $columnValue, callable $modification) {
|
||||
try {
|
||||
$userData = $this->db->selectRow(
|
||||
'SELECT id, roles_mask FROM ' . $this->dbTablePrefix . 'users WHERE ' . $columnName . ' = ?',
|
||||
[ $columnValue ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
}
|
||||
|
||||
if ($userData === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$newRolesBitmask = $modification($userData['roles_mask']);
|
||||
|
||||
try {
|
||||
$this->db->exec(
|
||||
'UPDATE ' . $this->dbTablePrefix . 'users SET roles_mask = ? WHERE id = ?',
|
||||
[
|
||||
$newRolesBitmask,
|
||||
(int) $userData['id']
|
||||
]
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns the specified role to the user 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
|
||||
* @param int $role the role as one of the constants from the {@see Role} class
|
||||
* @return bool whether any user with the given column constraints has been found
|
||||
*
|
||||
* @see Role
|
||||
*/
|
||||
private function addRoleForUserByColumnValue($columnName, $columnValue, $role) {
|
||||
$role = (int) $role;
|
||||
|
||||
return $this->modifyRolesForUserByColumnValue(
|
||||
$columnName,
|
||||
$columnValue,
|
||||
function ($oldRolesBitmask) use ($role) {
|
||||
return $oldRolesBitmask | $role;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes away the specified role from the user 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
|
||||
* @param int $role the role as one of the constants from the {@see Role} class
|
||||
* @return bool whether any user with the given column constraints has been found
|
||||
*
|
||||
* @see Role
|
||||
*/
|
||||
private function removeRoleForUserByColumnValue($columnName, $columnValue, $role) {
|
||||
$role = (int) $role;
|
||||
|
||||
return $this->modifyRolesForUserByColumnValue(
|
||||
$columnName,
|
||||
$columnValue,
|
||||
function ($oldRolesBitmask) use ($role) {
|
||||
return $oldRolesBitmask & ~$role;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs in as the user for which 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 matched users (where only a value of one means that the login may have been successful)
|
||||
* @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
private function logInAsUserByColumnValue($columnName, $columnValue) {
|
||||
try {
|
||||
$users = $this->db->select(
|
||||
'SELECT verified, id, email, username, status, roles_mask FROM ' . $this->dbTablePrefix . 'users WHERE ' . $columnName . ' = ? LIMIT 2 OFFSET 0',
|
||||
[ $columnValue ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
}
|
||||
|
||||
$numberOfMatchingUsers = \count($users);
|
||||
|
||||
if ($numberOfMatchingUsers === 1) {
|
||||
$user = $users[0];
|
||||
|
||||
if ((int) $user['verified'] === 1) {
|
||||
$this->onLoginSuccessful($user['id'], $user['email'], $user['username'], $user['status'], $user['roles_mask'], false);
|
||||
}
|
||||
else {
|
||||
throw new EmailNotVerifiedException();
|
||||
}
|
||||
}
|
||||
|
||||
return $numberOfMatchingUsers;
|
||||
}
|
||||
|
||||
}
|
||||
|
1257
src/Auth.php
1257
src/Auth.php
File diff suppressed because it is too large
Load Diff
@@ -1,34 +0,0 @@
|
||||
<?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 Base64 {
|
||||
|
||||
const SPECIAL_CHARS_ORIGINAL = '+/=';
|
||||
const SPECIAL_CHARS_SAFE = '._-';
|
||||
|
||||
public static function encode($data, $safeChars = false) {
|
||||
$result = base64_encode($data);
|
||||
|
||||
if ($safeChars) {
|
||||
$result = strtr($result, self::SPECIAL_CHARS_ORIGINAL, self::SPECIAL_CHARS_SAFE);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public static function decode($data) {
|
||||
$data = strtr($data, self::SPECIAL_CHARS_SAFE, self::SPECIAL_CHARS_ORIGINAL);
|
||||
|
||||
$result = base64_decode($data, true);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
}
|
@@ -34,14 +34,18 @@ class DuplicateUsernameException extends AuthException {}
|
||||
|
||||
class AmbiguousUsernameException extends AuthException {}
|
||||
|
||||
class AttemptCancelledException extends AuthException {}
|
||||
|
||||
class ResetDisabledException extends AuthException {}
|
||||
|
||||
class ConfirmationRequestNotFound 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 {}
|
||||
|
46
src/Role.php
Normal file
46
src/Role.php
Normal file
@@ -0,0 +1,46 @@
|
||||
<?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 Role {
|
||||
|
||||
const ADMIN = 1;
|
||||
const AUTHOR = 2;
|
||||
const COLLABORATOR = 4;
|
||||
const CONSULTANT = 8;
|
||||
const CONSUMER = 16;
|
||||
const CONTRIBUTOR = 32;
|
||||
const COORDINATOR = 64;
|
||||
const CREATOR = 128;
|
||||
const DEVELOPER = 256;
|
||||
const DIRECTOR = 512;
|
||||
const EDITOR = 1024;
|
||||
const EMPLOYEE = 2048;
|
||||
const MAINTAINER = 4096;
|
||||
const MANAGER = 8192;
|
||||
const MODERATOR = 16384;
|
||||
const PUBLISHER = 32768;
|
||||
const REVIEWER = 65536;
|
||||
const SUBSCRIBER = 131072;
|
||||
const SUPER_ADMIN = 262144;
|
||||
const SUPER_EDITOR = 524288;
|
||||
const SUPER_MODERATOR = 1048576;
|
||||
const TRANSLATOR = 2097152;
|
||||
// const XXX = 4194304;
|
||||
// const XXX = 8388608;
|
||||
// const XXX = 16777216;
|
||||
// const XXX = 33554432;
|
||||
// const XXX = 67108864;
|
||||
// const XXX = 134217728;
|
||||
// const XXX = 268435456;
|
||||
// const XXX = 536870912;
|
||||
|
||||
private function __construct() {}
|
||||
|
||||
}
|
@@ -8,6 +8,8 @@
|
||||
|
||||
namespace Delight\Auth;
|
||||
|
||||
use Delight\Base64\Base64;
|
||||
use Delight\Cookie\Session;
|
||||
use Delight\Db\PdoDatabase;
|
||||
use Delight\Db\PdoDsn;
|
||||
use Delight\Db\Throwable\Error;
|
||||
@@ -22,12 +24,26 @@ require_once __DIR__ . '/Exceptions.php';
|
||||
*/
|
||||
abstract class UserManager {
|
||||
|
||||
const THROTTLE_ACTION_LOGIN = 'login';
|
||||
const THROTTLE_ACTION_REGISTER = 'register';
|
||||
const THROTTLE_ACTION_CONSUME_TOKEN = 'confirm_email';
|
||||
/** @var string session field for whether the client is currently signed in */
|
||||
const SESSION_FIELD_LOGGED_IN = 'auth_logged_in';
|
||||
/** @var string session field for the ID of the user who is currently signed in (if any) */
|
||||
const SESSION_FIELD_USER_ID = 'auth_user_id';
|
||||
/** @var string session field for the email address of the user who is currently signed in (if any) */
|
||||
const SESSION_FIELD_EMAIL = 'auth_email';
|
||||
/** @var string session field for the display name (if any) of the user who is currently signed in (if any) */
|
||||
const SESSION_FIELD_USERNAME = 'auth_username';
|
||||
/** @var string session field for the status of the user who is currently signed in (if any) as one of the constants from the {@see Status} class */
|
||||
const SESSION_FIELD_STATUS = 'auth_status';
|
||||
/** @var string session field for the roles of the user who is currently signed in (if any) as a bitmask using constants from the {@see Role} class */
|
||||
const SESSION_FIELD_ROLES = 'auth_roles';
|
||||
/** @var string session field for whether the user who is currently signed in (if any) has been remembered (instead of them having authenticated actively) */
|
||||
const SESSION_FIELD_REMEMBERED = 'auth_remembered';
|
||||
const CONFIRMATION_REQUESTS_TTL_IN_SECONDS = 60 * 60 * 24;
|
||||
|
||||
/** @var PdoDatabase the database connection to operate on */
|
||||
protected $db;
|
||||
/** @var string the prefix for the names of all database tables used by this component */
|
||||
protected $dbTablePrefix;
|
||||
|
||||
/**
|
||||
* Creates a random string with the given maximum length
|
||||
@@ -39,19 +55,20 @@ abstract class UserManager {
|
||||
*/
|
||||
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;
|
||||
$bytes = \floor((int) $maxLength / 4) * 3;
|
||||
|
||||
// get random data
|
||||
$data = openssl_random_pseudo_bytes($bytes);
|
||||
$data = \openssl_random_pseudo_bytes($bytes);
|
||||
|
||||
// return the Base64-encoded result
|
||||
return Base64::encode($data, true);
|
||||
return Base64::encodeUrlSafe($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param PdoDatabase|PdoDsn|\PDO $databaseConnection the database connection to operate on
|
||||
* @param string|null $dbTablePrefix (optional) the prefix for the names of all database tables used by this component
|
||||
*/
|
||||
protected function __construct($databaseConnection) {
|
||||
protected function __construct($databaseConnection, $dbTablePrefix = null) {
|
||||
if ($databaseConnection instanceof PdoDatabase) {
|
||||
$this->db = $databaseConnection;
|
||||
}
|
||||
@@ -67,15 +84,7 @@ abstract class UserManager {
|
||||
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');
|
||||
}
|
||||
}
|
||||
});
|
||||
$this->dbTablePrefix = (string) $dbTablePrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -104,16 +113,17 @@ abstract class UserManager {
|
||||
* @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)
|
||||
*
|
||||
* @see confirmEmail
|
||||
* @see confirmEmailAndSignIn
|
||||
*/
|
||||
protected function createUserInternal($requireUniqueUsername, $email, $password, $username = null, callable $callback = null) {
|
||||
$this->throttle(self::THROTTLE_ACTION_REGISTER);
|
||||
|
||||
ignore_user_abort(true);
|
||||
\ignore_user_abort(true);
|
||||
|
||||
$email = self::validateEmailAddress($email);
|
||||
$password = self::validatePassword($password);
|
||||
|
||||
$username = isset($username) ? trim($username) : null;
|
||||
$username = isset($username) ? \trim($username) : null;
|
||||
|
||||
// if the supplied username is the empty string or has consisted of whitespace only
|
||||
if ($username === '') {
|
||||
@@ -127,7 +137,7 @@ abstract class UserManager {
|
||||
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 = ?',
|
||||
'SELECT COUNT(*) FROM ' . $this->dbTablePrefix . 'users WHERE username = ?',
|
||||
[ $username ]
|
||||
);
|
||||
|
||||
@@ -139,18 +149,18 @@ abstract class UserManager {
|
||||
}
|
||||
}
|
||||
|
||||
$password = password_hash($password, PASSWORD_DEFAULT);
|
||||
$verified = isset($callback) && is_callable($callback) ? 0 : 1;
|
||||
$password = \password_hash($password, \PASSWORD_DEFAULT);
|
||||
$verified = \is_callable($callback) ? 0 : 1;
|
||||
|
||||
try {
|
||||
$this->db->insert(
|
||||
'users',
|
||||
$this->dbTablePrefix . 'users',
|
||||
[
|
||||
'email' => $email,
|
||||
'password' => $password,
|
||||
'username' => $username,
|
||||
'verified' => $verified,
|
||||
'registered' => time()
|
||||
'registered' => \time()
|
||||
]
|
||||
);
|
||||
}
|
||||
@@ -165,12 +175,39 @@ abstract class UserManager {
|
||||
$newUserId = (int) $this->db->getLastInsertId();
|
||||
|
||||
if ($verified === 0) {
|
||||
$this->createConfirmationRequest($email, $callback);
|
||||
$this->createConfirmationRequest($newUserId, $email, $callback);
|
||||
}
|
||||
|
||||
return $newUserId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when a user has successfully logged in
|
||||
*
|
||||
* This may happen via the standard login, via the "remember me" feature, or due to impersonation by administrators
|
||||
*
|
||||
* @param int $userId the ID of the user
|
||||
* @param string $email the email address of the user
|
||||
* @param string $username the display name (if any) of the user
|
||||
* @param int $status the status of the user as one of the constants from the {@see Status} class
|
||||
* @param int $roles the roles of the user as a bitmask using constants from the {@see Role} class
|
||||
* @param bool $remembered whether the user has been remembered (instead of them having authenticated actively)
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
protected function onLoginSuccessful($userId, $email, $username, $status, $roles, $remembered) {
|
||||
// re-generate the session ID to prevent session fixation attacks (requests a cookie to be written on the client)
|
||||
Session::regenerate(true);
|
||||
|
||||
// save the user data in the session variables maintained by this library
|
||||
$_SESSION[self::SESSION_FIELD_LOGGED_IN] = true;
|
||||
$_SESSION[self::SESSION_FIELD_USER_ID] = (int) $userId;
|
||||
$_SESSION[self::SESSION_FIELD_EMAIL] = $email;
|
||||
$_SESSION[self::SESSION_FIELD_USERNAME] = $username;
|
||||
$_SESSION[self::SESSION_FIELD_STATUS] = (int) $status;
|
||||
$_SESSION[self::SESSION_FIELD_ROLES] = (int) $roles;
|
||||
$_SESSION[self::SESSION_FIELD_REMEMBERED] = $remembered;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the requested user data for the account with the specified username (if any)
|
||||
*
|
||||
@@ -185,10 +222,10 @@ abstract class UserManager {
|
||||
*/
|
||||
protected function getUserDataByUsername($username, array $requestedColumns) {
|
||||
try {
|
||||
$projection = implode(', ', $requestedColumns);
|
||||
$projection = \implode(', ', $requestedColumns);
|
||||
|
||||
$users = $this->db->select(
|
||||
'SELECT ' . $projection . ' FROM users WHERE username = ? LIMIT 0, 2',
|
||||
'SELECT ' . $projection . ' FROM ' . $this->dbTablePrefix . 'users WHERE username = ? LIMIT 2 OFFSET 0',
|
||||
[ $username ]
|
||||
);
|
||||
}
|
||||
@@ -200,7 +237,7 @@ abstract class UserManager {
|
||||
throw new UnknownUsernameException();
|
||||
}
|
||||
else {
|
||||
if (count($users) === 1) {
|
||||
if (\count($users) === 1) {
|
||||
return $users[0];
|
||||
}
|
||||
else {
|
||||
@@ -221,9 +258,9 @@ abstract class UserManager {
|
||||
throw new InvalidEmailException();
|
||||
}
|
||||
|
||||
$email = trim($email);
|
||||
$email = \trim($email);
|
||||
|
||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
if (!\filter_var($email, \FILTER_VALIDATE_EMAIL)) {
|
||||
throw new InvalidEmailException();
|
||||
}
|
||||
|
||||
@@ -242,25 +279,15 @@ abstract class UserManager {
|
||||
throw new InvalidPasswordException();
|
||||
}
|
||||
|
||||
$password = trim($password);
|
||||
$password = \trim($password);
|
||||
|
||||
if (strlen($password) < 1) {
|
||||
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
|
||||
*
|
||||
@@ -272,22 +299,24 @@ abstract class UserManager {
|
||||
*
|
||||
* When the user wants to verify their email address as a next step, both pieces will be required again
|
||||
*
|
||||
* @param int $userId the user's ID
|
||||
* @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) {
|
||||
protected function createConfirmationRequest($userId, $email, callable $callback) {
|
||||
$selector = self::createRandomString(16);
|
||||
$token = self::createRandomString(16);
|
||||
$tokenHashed = password_hash($token, PASSWORD_DEFAULT);
|
||||
$tokenHashed = \password_hash($token, \PASSWORD_DEFAULT);
|
||||
|
||||
// the request shall be valid for one day
|
||||
$expires = time() + 60 * 60 * 24;
|
||||
$expires = \time() + self::CONFIRMATION_REQUESTS_TTL_IN_SECONDS;
|
||||
|
||||
try {
|
||||
$this->db->insert(
|
||||
'users_confirmations',
|
||||
$this->dbTablePrefix . 'users_confirmations',
|
||||
[
|
||||
'user_id' => (int) $userId,
|
||||
'email' => $email,
|
||||
'selector' => $selector,
|
||||
'token' => $tokenHashed,
|
||||
@@ -299,7 +328,7 @@ abstract class UserManager {
|
||||
throw new DatabaseError();
|
||||
}
|
||||
|
||||
if (isset($callback) && is_callable($callback)) {
|
||||
if (\is_callable($callback)) {
|
||||
$callback($selector, $token);
|
||||
}
|
||||
else {
|
||||
|
595
tests/index.php
595
tests/index.php
@@ -6,34 +6,43 @@
|
||||
* Licensed under the MIT License (https://opensource.org/licenses/MIT)
|
||||
*/
|
||||
|
||||
/*
|
||||
* WARNING:
|
||||
*
|
||||
* Do *not* use these files from the `tests` directory as the foundation
|
||||
* for the usage of this library in your own code. Instead, please follow
|
||||
* the `README.md` file in the root directory of this project.
|
||||
*/
|
||||
|
||||
// enable error reporting
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 'stdout');
|
||||
\error_reporting(\E_ALL);
|
||||
\ini_set('display_errors', 'stdout');
|
||||
|
||||
// enable assertions
|
||||
ini_set('assert.active', 1);
|
||||
@ini_set('zend.assertions', 1);
|
||||
ini_set('assert.exception', 1);
|
||||
\ini_set('assert.active', 1);
|
||||
@\ini_set('zend.assertions', 1);
|
||||
\ini_set('assert.exception', 1);
|
||||
|
||||
header('Content-type: text/html; charset=utf-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');
|
||||
$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');
|
||||
// $db = new \PDO('sqlite:../Databases/php_auth.sqlite');
|
||||
|
||||
$auth = new \Delight\Auth\Auth($db);
|
||||
|
||||
$result = processRequestData($auth);
|
||||
$result = \processRequestData($auth);
|
||||
|
||||
showDebugData($auth, $result);
|
||||
\showGeneralForm();
|
||||
\showDebugData($auth, $result);
|
||||
|
||||
if ($auth->check()) {
|
||||
showAuthenticatedUserForm();
|
||||
\showAuthenticatedUserForm($auth);
|
||||
}
|
||||
else {
|
||||
showGuestUserForm();
|
||||
\showGuestUserForm();
|
||||
}
|
||||
|
||||
function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
@@ -75,7 +84,7 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
return 'wrong password';
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
return 'email not verified';
|
||||
return 'email address not verified';
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
return 'too many requests';
|
||||
@@ -90,11 +99,11 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
echo "\n";
|
||||
echo ' > Selector';
|
||||
echo "\t\t\t\t";
|
||||
echo htmlspecialchars($selector);
|
||||
echo \htmlspecialchars($selector);
|
||||
echo "\n";
|
||||
echo ' > Token';
|
||||
echo "\t\t\t\t";
|
||||
echo htmlspecialchars($token);
|
||||
echo \htmlspecialchars($token);
|
||||
echo '</pre>';
|
||||
};
|
||||
}
|
||||
@@ -131,7 +140,20 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
}
|
||||
else if ($_POST['action'] === 'confirmEmail') {
|
||||
try {
|
||||
$auth->confirmEmail($_POST['selector'], $_POST['token']);
|
||||
if (isset($_POST['login']) && $_POST['login'] > 0) {
|
||||
if ($_POST['login'] == 2) {
|
||||
// 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->confirmEmailAndSignIn($_POST['selector'], $_POST['token'], $rememberDuration);
|
||||
}
|
||||
else {
|
||||
$auth->confirmEmail($_POST['selector'], $_POST['token']);
|
||||
}
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
@@ -141,6 +163,59 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
catch (\Delight\Auth\TokenExpiredException $e) {
|
||||
return 'token expired';
|
||||
}
|
||||
catch (\Delight\Auth\UserAlreadyExistsException $e) {
|
||||
return 'email address already exists';
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
return 'too many requests';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'resendConfirmationForEmail') {
|
||||
try {
|
||||
$auth->resendConfirmationForEmail($_POST['email'], function ($selector, $token) {
|
||||
echo '<pre>';
|
||||
echo 'Email confirmation';
|
||||
echo "\n";
|
||||
echo ' > Selector';
|
||||
echo "\t\t\t\t";
|
||||
echo \htmlspecialchars($selector);
|
||||
echo "\n";
|
||||
echo ' > Token';
|
||||
echo "\t\t\t\t";
|
||||
echo \htmlspecialchars($token);
|
||||
echo '</pre>';
|
||||
});
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
catch (\Delight\Auth\ConfirmationRequestNotFound $e) {
|
||||
return 'no request found';
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
return 'too many requests';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'resendConfirmationForUserId') {
|
||||
try {
|
||||
$auth->resendConfirmationForUserId($_POST['userId'], function ($selector, $token) {
|
||||
echo '<pre>';
|
||||
echo 'Email confirmation';
|
||||
echo "\n";
|
||||
echo ' > Selector';
|
||||
echo "\t\t\t\t";
|
||||
echo \htmlspecialchars($selector);
|
||||
echo "\n";
|
||||
echo ' > Token';
|
||||
echo "\t\t\t\t";
|
||||
echo \htmlspecialchars($token);
|
||||
echo '</pre>';
|
||||
});
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
catch (\Delight\Auth\ConfirmationRequestNotFound $e) {
|
||||
return 'no request found';
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
return 'too many requests';
|
||||
}
|
||||
@@ -153,11 +228,11 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
echo "\n";
|
||||
echo ' > Selector';
|
||||
echo "\t\t\t\t";
|
||||
echo htmlspecialchars($selector);
|
||||
echo \htmlspecialchars($selector);
|
||||
echo "\n";
|
||||
echo ' > Token';
|
||||
echo "\t\t\t\t";
|
||||
echo htmlspecialchars($token);
|
||||
echo \htmlspecialchars($token);
|
||||
echo '</pre>';
|
||||
});
|
||||
|
||||
@@ -167,7 +242,10 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
return 'invalid email address';
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
return 'email not verified';
|
||||
return 'email address not verified';
|
||||
}
|
||||
catch (\Delight\Auth\ResetDisabledException $e) {
|
||||
return 'password reset disabled';
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
return 'too many requests';
|
||||
@@ -185,6 +263,9 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
catch (\Delight\Auth\TokenExpiredException $e) {
|
||||
return 'token expired';
|
||||
}
|
||||
catch (\Delight\Auth\ResetDisabledException $e) {
|
||||
return 'password reset disabled';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
return 'invalid password';
|
||||
}
|
||||
@@ -192,6 +273,17 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
return 'too many requests';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'reconfirmPassword') {
|
||||
try {
|
||||
return $auth->reconfirmPassword($_POST['password']) ? 'correct' : 'wrong';
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
return 'not logged in';
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
return 'too many requests';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'changePassword') {
|
||||
try {
|
||||
$auth->changePassword($_POST['oldPassword'], $_POST['newPassword']);
|
||||
@@ -204,9 +296,74 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
return 'invalid password(s)';
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
return 'too many requests';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'logout') {
|
||||
$auth->logout();
|
||||
else if ($_POST['action'] === 'changePasswordWithoutOldPassword') {
|
||||
try {
|
||||
$auth->changePasswordWithoutOldPassword($_POST['newPassword']);
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
return 'not logged in';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
return 'invalid password';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'changeEmail') {
|
||||
try {
|
||||
$auth->changeEmail($_POST['newEmail'], function ($selector, $token) {
|
||||
echo '<pre>';
|
||||
echo 'Email confirmation';
|
||||
echo "\n";
|
||||
echo ' > Selector';
|
||||
echo "\t\t\t\t";
|
||||
echo \htmlspecialchars($selector);
|
||||
echo "\n";
|
||||
echo ' > Token';
|
||||
echo "\t\t\t\t";
|
||||
echo \htmlspecialchars($token);
|
||||
echo '</pre>';
|
||||
});
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
return 'invalid email address';
|
||||
}
|
||||
catch (\Delight\Auth\UserAlreadyExistsException $e) {
|
||||
return 'email address already exists';
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
return 'account not verified';
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
return 'not logged in';
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
return 'too many requests';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'setPasswordResetEnabled') {
|
||||
try {
|
||||
$auth->setPasswordResetEnabled($_POST['enabled'] == 1);
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
return 'not logged in';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'logOut') {
|
||||
$auth->logOut();
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
else if ($_POST['action'] === 'logOutAndDestroySession') {
|
||||
$auth->logOutAndDestroySession();
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
@@ -265,13 +422,166 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'either ID, email or username required';
|
||||
return 'either ID, email address or username required';
|
||||
}
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
else if ($_POST['action'] === 'admin.addRole') {
|
||||
if (isset($_POST['role'])) {
|
||||
if (isset($_POST['id'])) {
|
||||
try {
|
||||
$auth->admin()->addRoleForUserById($_POST['id'], $_POST['role']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
return 'unknown ID';
|
||||
}
|
||||
}
|
||||
elseif (isset($_POST['email'])) {
|
||||
try {
|
||||
$auth->admin()->addRoleForUserByEmail($_POST['email'], $_POST['role']);
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
return 'unknown email address';
|
||||
}
|
||||
}
|
||||
elseif (isset($_POST['username'])) {
|
||||
try {
|
||||
$auth->admin()->addRoleForUserByUsername($_POST['username'], $_POST['role']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
return 'unknown username';
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
return 'ambiguous username';
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'either ID, email address or username required';
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'role required';
|
||||
}
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
else if ($_POST['action'] === 'admin.removeRole') {
|
||||
if (isset($_POST['role'])) {
|
||||
if (isset($_POST['id'])) {
|
||||
try {
|
||||
$auth->admin()->removeRoleForUserById($_POST['id'], $_POST['role']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
return 'unknown ID';
|
||||
}
|
||||
}
|
||||
elseif (isset($_POST['email'])) {
|
||||
try {
|
||||
$auth->admin()->removeRoleForUserByEmail($_POST['email'], $_POST['role']);
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
return 'unknown email address';
|
||||
}
|
||||
}
|
||||
elseif (isset($_POST['username'])) {
|
||||
try {
|
||||
$auth->admin()->removeRoleForUserByUsername($_POST['username'], $_POST['role']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
return 'unknown username';
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
return 'ambiguous username';
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'either ID, email address or username required';
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'role required';
|
||||
}
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
else if ($_POST['action'] === 'admin.hasRole') {
|
||||
if (isset($_POST['id'])) {
|
||||
if (isset($_POST['role'])) {
|
||||
try {
|
||||
return $auth->admin()->doesUserHaveRole($_POST['id'], $_POST['role']) ? 'yes' : 'no';
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
return 'unknown ID';
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'role required';
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'ID required';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'admin.logInAsUserById') {
|
||||
if (isset($_POST['id'])) {
|
||||
try {
|
||||
$auth->admin()->logInAsUserById($_POST['id']);
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
return 'unknown ID';
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
return 'email address not verified';
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'ID required';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'admin.logInAsUserByEmail') {
|
||||
if (isset($_POST['email'])) {
|
||||
try {
|
||||
$auth->admin()->logInAsUserByEmail($_POST['email']);
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
return 'unknown email address';
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
return 'email address not verified';
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'Email address required';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'admin.logInAsUserByUsername') {
|
||||
if (isset($_POST['username'])) {
|
||||
try {
|
||||
$auth->admin()->logInAsUserByUsername($_POST['username']);
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
return 'unknown username';
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
return 'ambiguous username';
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
return 'email address not verified';
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'Username required';
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw new Exception('Unexpected action: '.$_POST['action']);
|
||||
throw new Exception('Unexpected action: ' . $_POST['action']);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -282,44 +592,65 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
function showDebugData(\Delight\Auth\Auth $auth, $result) {
|
||||
echo '<pre>';
|
||||
|
||||
echo 'Last operation'."\t\t\t\t";
|
||||
var_dump($result);
|
||||
echo 'Session ID'."\t\t\t\t";
|
||||
var_dump(session_id());
|
||||
echo 'Last operation' . "\t\t\t\t";
|
||||
\var_dump($result);
|
||||
echo 'Session ID' . "\t\t\t\t";
|
||||
\var_dump(\session_id());
|
||||
echo "\n";
|
||||
|
||||
echo '$auth->isLoggedIn()'."\t\t\t";
|
||||
var_dump($auth->isLoggedIn());
|
||||
echo '$auth->check()'."\t\t\t\t";
|
||||
var_dump($auth->check());
|
||||
echo '$auth->isLoggedIn()' . "\t\t\t";
|
||||
\var_dump($auth->isLoggedIn());
|
||||
echo '$auth->check()' . "\t\t\t\t";
|
||||
\var_dump($auth->check());
|
||||
echo "\n";
|
||||
|
||||
echo '$auth->getUserId()'."\t\t\t";
|
||||
var_dump($auth->getUserId());
|
||||
echo '$auth->id()'."\t\t\t\t";
|
||||
var_dump($auth->id());
|
||||
echo '$auth->getUserId()' . "\t\t\t";
|
||||
\var_dump($auth->getUserId());
|
||||
echo '$auth->id()' . "\t\t\t\t";
|
||||
\var_dump($auth->id());
|
||||
echo "\n";
|
||||
|
||||
echo '$auth->getEmail()'."\t\t\t";
|
||||
var_dump($auth->getEmail());
|
||||
echo '$auth->getUsername()'."\t\t\t";
|
||||
var_dump($auth->getUsername());
|
||||
echo '$auth->getEmail()' . "\t\t\t";
|
||||
\var_dump($auth->getEmail());
|
||||
echo '$auth->getUsername()' . "\t\t\t";
|
||||
\var_dump($auth->getUsername());
|
||||
|
||||
echo '$auth->getStatus()'."\t\t\t";
|
||||
echo convertStatusToText($auth);
|
||||
echo '$auth->getStatus()' . "\t\t\t";
|
||||
echo \convertStatusToText($auth);
|
||||
echo ' / ';
|
||||
var_dump($auth->getStatus());
|
||||
\var_dump($auth->getStatus());
|
||||
|
||||
echo '$auth->isRemembered()'."\t\t\t";
|
||||
var_dump($auth->isRemembered());
|
||||
echo '$auth->getIpAddress()'."\t\t\t";
|
||||
var_dump($auth->getIpAddress());
|
||||
echo "\n";
|
||||
|
||||
echo 'Auth::createRandomString()'."\t\t";
|
||||
var_dump(\Delight\Auth\Auth::createRandomString());
|
||||
echo 'Auth::createUuid()'."\t\t\t";
|
||||
var_dump(\Delight\Auth\Auth::createUuid());
|
||||
echo 'Roles (super moderator)' . "\t\t\t";
|
||||
\var_dump($auth->hasRole(\Delight\Auth\Role::SUPER_MODERATOR));
|
||||
|
||||
echo 'Roles (developer *or* manager)' . "\t\t";
|
||||
\var_dump($auth->hasAnyRole(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER));
|
||||
|
||||
echo 'Roles (developer *and* manager)' . "\t\t";
|
||||
\var_dump($auth->hasAllRoles(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER));
|
||||
|
||||
echo "\n";
|
||||
|
||||
echo '$auth->isRemembered()' . "\t\t\t";
|
||||
\var_dump($auth->isRemembered());
|
||||
echo '$auth->getIpAddress()' . "\t\t\t";
|
||||
\var_dump($auth->getIpAddress());
|
||||
echo "\n";
|
||||
|
||||
echo 'Session name' . "\t\t\t\t";
|
||||
\var_dump(\session_name());
|
||||
echo 'Auth::createRememberCookieName()' . "\t";
|
||||
\var_dump(\Delight\Auth\Auth::createRememberCookieName());
|
||||
echo "\n";
|
||||
|
||||
echo 'Auth::createCookieName(\'session\')' . "\t";
|
||||
\var_dump(\Delight\Auth\Auth::createCookieName('session'));
|
||||
echo 'Auth::createRandomString()' . "\t\t";
|
||||
\var_dump(\Delight\Auth\Auth::createRandomString());
|
||||
echo 'Auth::createUuid()' . "\t\t\t";
|
||||
\var_dump(\Delight\Auth\Auth::createUuid());
|
||||
|
||||
echo '</pre>';
|
||||
}
|
||||
@@ -360,8 +691,12 @@ function showGeneralForm() {
|
||||
echo '</form>';
|
||||
}
|
||||
|
||||
function showAuthenticatedUserForm() {
|
||||
showGeneralForm();
|
||||
function showAuthenticatedUserForm(\Delight\Auth\Auth $auth) {
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="reconfirmPassword" />';
|
||||
echo '<input type="text" name="password" placeholder="Password" /> ';
|
||||
echo '<button type="submit">Reconfirm password</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="changePassword" />';
|
||||
@@ -371,19 +706,45 @@ function showAuthenticatedUserForm() {
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="logout" />';
|
||||
echo '<button type="submit">Logout</button>';
|
||||
echo '<input type="hidden" name="action" value="changePasswordWithoutOldPassword" />';
|
||||
echo '<input type="text" name="newPassword" placeholder="New password" /> ';
|
||||
echo '<button type="submit">Change password without old password</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="changeEmail" />';
|
||||
echo '<input type="text" name="newEmail" placeholder="New email address" /> ';
|
||||
echo '<button type="submit">Change email address</button>';
|
||||
echo '</form>';
|
||||
|
||||
\showConfirmEmailForm();
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="setPasswordResetEnabled" />';
|
||||
echo '<select name="enabled" size="1">';
|
||||
echo '<option value="0"' . ($auth->isPasswordResetEnabled() ? '' : ' selected="selected"') . '>Disabled</option>';
|
||||
echo '<option value="1"' . ($auth->isPasswordResetEnabled() ? ' selected="selected"' : '') . '>Enabled</option>';
|
||||
echo '</select> ';
|
||||
echo '<button type="submit">Control password resets</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="logOut" />';
|
||||
echo '<button type="submit">Log out</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="logOutAndDestroySession" />';
|
||||
echo '<button type="submit">Log out and destroy session</button>';
|
||||
echo '</form>';
|
||||
}
|
||||
|
||||
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="email" placeholder="Email address" /> ';
|
||||
echo '<input type="text" name="password" placeholder="Password" /> ';
|
||||
echo '<select name="remember" size="1">';
|
||||
echo '<option value="0">Remember (keep logged in)? — No</option>';
|
||||
@@ -405,7 +766,7 @@ function showGuestUserForm() {
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="register" />';
|
||||
echo '<input type="text" name="email" placeholder="Email" /> ';
|
||||
echo '<input type="text" name="email" placeholder="Email address" /> ';
|
||||
echo '<input type="text" name="password" placeholder="Password" /> ';
|
||||
echo '<input type="text" name="username" placeholder="Username (optional)" /> ';
|
||||
echo '<select name="require_verification" size="1">';
|
||||
@@ -419,16 +780,11 @@ function showGuestUserForm() {
|
||||
echo '<button type="submit">Register</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="confirmEmail" />';
|
||||
echo '<input type="text" name="selector" placeholder="Selector" /> ';
|
||||
echo '<input type="text" name="token" placeholder="Token" /> ';
|
||||
echo '<button type="submit">Confirm email</button>';
|
||||
echo '</form>';
|
||||
\showConfirmEmailForm();
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="forgotPassword" />';
|
||||
echo '<input type="text" name="email" placeholder="Email" /> ';
|
||||
echo '<input type="text" name="email" placeholder="Email address" /> ';
|
||||
echo '<button type="submit">Forgot password</button>';
|
||||
echo '</form>';
|
||||
|
||||
@@ -444,7 +800,7 @@ function showGuestUserForm() {
|
||||
|
||||
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="email" placeholder="Email address" /> ';
|
||||
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">';
|
||||
@@ -462,7 +818,7 @@ function showGuestUserForm() {
|
||||
|
||||
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 '<input type="text" name="email" placeholder="Email address" /> ';
|
||||
echo '<button type="submit">Delete user by email</button>';
|
||||
echo '</form>';
|
||||
|
||||
@@ -471,4 +827,109 @@ function showGuestUserForm() {
|
||||
echo '<input type="text" name="username" placeholder="Username" /> ';
|
||||
echo '<button type="submit">Delete user by username</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.addRole" />';
|
||||
echo '<input type="text" name="id" placeholder="ID" /> ';
|
||||
echo '<select name="role">' . \createRolesOptions() . '</select>';
|
||||
echo '<button type="submit">Add role for user by ID</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.addRole" />';
|
||||
echo '<input type="text" name="email" placeholder="Email address" /> ';
|
||||
echo '<select name="role">' . \createRolesOptions() . '</select>';
|
||||
echo '<button type="submit">Add role for user by email</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.addRole" />';
|
||||
echo '<input type="text" name="username" placeholder="Username" /> ';
|
||||
echo '<select name="role">' . \createRolesOptions() . '</select>';
|
||||
echo '<button type="submit">Add role for user by username</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.removeRole" />';
|
||||
echo '<input type="text" name="id" placeholder="ID" /> ';
|
||||
echo '<select name="role">' . \createRolesOptions() . '</select>';
|
||||
echo '<button type="submit">Remove role for user by ID</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.removeRole" />';
|
||||
echo '<input type="text" name="email" placeholder="Email address" /> ';
|
||||
echo '<select name="role">' . \createRolesOptions() . '</select>';
|
||||
echo '<button type="submit">Remove role for user by email</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.removeRole" />';
|
||||
echo '<input type="text" name="username" placeholder="Username" /> ';
|
||||
echo '<select name="role">' . \createRolesOptions() . '</select>';
|
||||
echo '<button type="submit">Remove role for user by username</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.hasRole" />';
|
||||
echo '<input type="text" name="id" placeholder="ID" /> ';
|
||||
echo '<select name="role">' . \createRolesOptions() . '</select>';
|
||||
echo '<button type="submit">Does user have role?</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.logInAsUserById" />';
|
||||
echo '<input type="text" name="id" placeholder="ID" /> ';
|
||||
echo '<button type="submit">Log in as user by ID</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.logInAsUserByEmail" />';
|
||||
echo '<input type="text" name="email" placeholder="Email address" /> ';
|
||||
echo '<button type="submit">Log in as user by email address</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.logInAsUserByUsername" />';
|
||||
echo '<input type="text" name="username" placeholder="Username" /> ';
|
||||
echo '<button type="submit">Log in as user by username</button>';
|
||||
echo '</form>';
|
||||
}
|
||||
|
||||
function showConfirmEmailForm() {
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="confirmEmail" />';
|
||||
echo '<input type="text" name="selector" placeholder="Selector" /> ';
|
||||
echo '<input type="text" name="token" placeholder="Token" /> ';
|
||||
echo '<select name="login" size="1">';
|
||||
echo '<option value="0">Sign in automatically? — No</option>';
|
||||
echo '<option value="1">Sign in automatically? — Yes</option>';
|
||||
echo '<option value="2">Sign in automatically? — Yes (and remember)</option>';
|
||||
echo '</select> ';
|
||||
echo '<button type="submit">Confirm email</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="resendConfirmationForEmail" />';
|
||||
echo '<input type="text" name="email" placeholder="Email address" /> ';
|
||||
echo '<button type="submit">Re-send confirmation</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="resendConfirmationForUserId" />';
|
||||
echo '<input type="text" name="userId" placeholder="User ID" /> ';
|
||||
echo '<button type="submit">Re-send confirmation</button>';
|
||||
echo '</form>';
|
||||
}
|
||||
|
||||
function createRolesOptions() {
|
||||
$roleReflection = new ReflectionClass(\Delight\Auth\Role::class);
|
||||
|
||||
$out = '';
|
||||
|
||||
foreach ($roleReflection->getConstants() as $roleName => $roleValue) {
|
||||
$out .= '<option value="' . $roleValue . '">' . $roleName . '</option>';
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
Reference in New Issue
Block a user