mirror of
https://github.com/delight-im/PHP-Auth.git
synced 2025-08-08 09:06:29 +02:00
Compare commits
107 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
157a7095b0 | ||
|
0f976a260b | ||
|
dcd893a12c | ||
|
0086419175 | ||
|
d49b35690c | ||
|
171519fdf3 | ||
|
14ce7b1e8f | ||
|
49c70eff41 | ||
|
2f772b00c8 | ||
|
5214da1f59 | ||
|
d8847fb197 | ||
|
1757ad3fd1 | ||
|
54f6c5320a | ||
|
4b3f2ab91c | ||
|
df990b5b75 | ||
|
7b2ac9b107 | ||
|
ad90c7d04a | ||
|
c0baa517fa | ||
|
3120e3a6a5 | ||
|
4cd6360fc7 | ||
|
382832457d | ||
|
f70923679f | ||
|
521e73662d | ||
|
2b3bf611e2 | ||
|
352260c759 | ||
|
cbf2b52f29 | ||
|
c685f22937 | ||
|
9d08c939a0 | ||
|
7a8508d56e | ||
|
f6607f664d | ||
|
49a4ef8280 | ||
|
50c284fff7 | ||
|
83c74689a3 | ||
|
6d34606336 | ||
|
be5b744470 | ||
|
4f6692bd25 | ||
|
0f8116e654 | ||
|
25f7a8908d | ||
|
a7c1ebcc9f | ||
|
71ce2b58c9 | ||
|
4c4c4c23f6 | ||
|
00a8a49f17 | ||
|
9f71eff176 | ||
|
fdd95e8b89 | ||
|
73b9232f63 | ||
|
20f484567a | ||
|
79c5a4f6d5 | ||
|
3ae1769256 | ||
|
58f1f34593 | ||
|
4d7b66ee5a | ||
|
62270a2c48 | ||
|
9848082bbb | ||
|
29afbdfc93 | ||
|
62f4b39dcf | ||
|
235008fdb8 | ||
|
adc1d73539 | ||
|
c3d44eab3e | ||
|
ade63d07df | ||
|
d9297709af | ||
|
7be05ddde2 | ||
|
095b8ccc70 | ||
|
550a6d0355 | ||
|
c494e0fa13 | ||
|
d7d9899167 | ||
|
05165a44a6 | ||
|
c3f2097750 | ||
|
395a065fd4 | ||
|
627c592891 | ||
|
2a6d1c4f7d | ||
|
a63e5ec053 | ||
|
4115340927 | ||
|
09dac6a5f5 | ||
|
3a7a860c6d | ||
|
131aea3ded | ||
|
e14f3d1925 | ||
|
1d54ff2f6b | ||
|
ec6afdad48 | ||
|
58e69fdd0e | ||
|
e7e174b05d | ||
|
8f35cc9965 | ||
|
142ccc362f | ||
|
bce31f9cfc | ||
|
3ddc7af1b4 | ||
|
62d9e44aa4 | ||
|
1121685cef | ||
|
2f9bab4779 | ||
|
89e99d727d | ||
|
21341d3c18 | ||
|
a1ae66374b | ||
|
477164e8ec | ||
|
9478a43e9b | ||
|
1ba8e1ff21 | ||
|
1657102f75 | ||
|
d246248ab5 | ||
|
94531f24d3 | ||
|
2f29830ed9 | ||
|
42a8c1616c | ||
|
a2be4c61ee | ||
|
d9f9198b45 | ||
|
13b58abebc | ||
|
b0bf7647ce | ||
|
012577227a | ||
|
d834623954 | ||
|
d3594898cc | ||
|
7d44158c32 | ||
|
04edd9f88f | ||
|
cd2ac47912 |
@@ -18,6 +18,7 @@ CREATE TABLE IF NOT EXISTS `users` (
|
||||
`roles_mask` int(10) unsigned NOT NULL DEFAULT '0',
|
||||
`registered` int(10) unsigned NOT NULL,
|
||||
`last_login` int(10) unsigned DEFAULT NULL,
|
||||
`force_logout` mediumint(7) unsigned NOT NULL DEFAULT '0',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `email` (`email`)
|
||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
58
Database/PostgreSQL.sql
Normal file
58
Database/PostgreSQL.sql
Normal file
@@ -0,0 +1,58 @@
|
||||
-- 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)
|
||||
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "users" (
|
||||
"id" SERIAL PRIMARY KEY CHECK ("id" >= 0),
|
||||
"email" VARCHAR(249) UNIQUE NOT NULL,
|
||||
"password" VARCHAR(255) NOT NULL,
|
||||
"username" VARCHAR(100) DEFAULT NULL,
|
||||
"status" SMALLINT NOT NULL DEFAULT '0' CHECK ("status" >= 0),
|
||||
"verified" SMALLINT NOT NULL DEFAULT '0' CHECK ("verified" >= 0),
|
||||
"resettable" SMALLINT NOT NULL DEFAULT '1' CHECK ("resettable" >= 0),
|
||||
"roles_mask" INTEGER NOT NULL DEFAULT '0' CHECK ("roles_mask" >= 0),
|
||||
"registered" INTEGER NOT NULL CHECK ("registered" >= 0),
|
||||
"last_login" INTEGER DEFAULT NULL CHECK ("last_login" >= 0),
|
||||
"force_logout" INTEGER NOT NULL DEFAULT '0' CHECK ("force_logout" >= 0)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "users_confirmations" (
|
||||
"id" SERIAL PRIMARY KEY CHECK ("id" >= 0),
|
||||
"user_id" INTEGER NOT NULL CHECK ("user_id" >= 0),
|
||||
"email" VARCHAR(249) NOT NULL,
|
||||
"selector" VARCHAR(16) UNIQUE NOT NULL,
|
||||
"token" VARCHAR(255) NOT NULL,
|
||||
"expires" INTEGER NOT NULL CHECK ("expires" >= 0)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS "email_expires" ON "users_confirmations" ("email", "expires");
|
||||
CREATE INDEX IF NOT EXISTS "user_id" ON "users_confirmations" ("user_id");
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "users_remembered" (
|
||||
"id" BIGSERIAL PRIMARY KEY CHECK ("id" >= 0),
|
||||
"user" INTEGER NOT NULL CHECK ("user" >= 0),
|
||||
"selector" VARCHAR(24) UNIQUE NOT NULL,
|
||||
"token" VARCHAR(255) NOT NULL,
|
||||
"expires" INTEGER NOT NULL CHECK ("expires" >= 0)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS "user" ON "users_remembered" ("user");
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "users_resets" (
|
||||
"id" BIGSERIAL PRIMARY KEY CHECK ("id" >= 0),
|
||||
"user" INTEGER NOT NULL CHECK ("user" >= 0),
|
||||
"selector" VARCHAR(20) UNIQUE NOT NULL,
|
||||
"token" VARCHAR(255) NOT NULL,
|
||||
"expires" INTEGER NOT NULL CHECK ("expires" >= 0)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS "user_expires" ON "users_resets" ("user", "expires");
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "users_throttling" (
|
||||
"bucket" VARCHAR(44) PRIMARY KEY,
|
||||
"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 IF NOT EXISTS "expires_at" ON "users_throttling" ("expires_at");
|
||||
|
||||
COMMIT;
|
@@ -15,6 +15,7 @@ CREATE TABLE "users" (
|
||||
"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,
|
||||
"force_logout" INTEGER NOT NULL CHECK ("force_logout" >= 0) DEFAULT "0",
|
||||
CONSTRAINT "email" UNIQUE ("email")
|
||||
);
|
||||
|
||||
|
38
Migration.md
38
Migration.md
@@ -1,6 +1,7 @@
|
||||
# Migration
|
||||
|
||||
* [General](#general)
|
||||
* [From `v7.x.x` to `v8.x.x`](#from-v7xx-to-v8xx)
|
||||
* [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)
|
||||
@@ -10,21 +11,40 @@
|
||||
|
||||
## General
|
||||
|
||||
Update your version of this library via Composer [[?]](https://github.com/delight-im/Knowledge/blob/master/Composer%20(PHP).md):
|
||||
Update your version of this library using Composer and its `composer update` or `composer require` commands [[?]](https://github.com/delight-im/Knowledge/blob/master/Composer%20(PHP).md#how-do-i-update-libraries-or-modules-within-my-application).
|
||||
|
||||
```
|
||||
$ composer update delight-im/auth
|
||||
```
|
||||
## From `v7.x.x` to `v8.x.x`
|
||||
|
||||
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):
|
||||
* The database schema has changed.
|
||||
|
||||
```
|
||||
$ composer require delight-im/auth
|
||||
```
|
||||
* The MySQL database schema has changed. Use the statement below to update your database:
|
||||
|
||||
```sql
|
||||
ALTER TABLE users
|
||||
ADD COLUMN `force_logout` mediumint(7) unsigned NOT NULL DEFAULT '0' AFTER `last_login`;
|
||||
```
|
||||
|
||||
* The PostgreSQL database schema has changed. Use the statement below to update your database:
|
||||
|
||||
```sql
|
||||
ALTER TABLE users
|
||||
ADD COLUMN "force_logout" INTEGER NOT NULL DEFAULT '0' CHECK ("force_logout" >= 0);
|
||||
```
|
||||
|
||||
* The SQLite database schema has changed. Use the statement below to update your database:
|
||||
|
||||
```sql
|
||||
ALTER TABLE users
|
||||
ADD COLUMN "force_logout" INTEGER NOT NULL CHECK ("force_logout" >= 0) DEFAULT "0";
|
||||
```
|
||||
|
||||
* The method `logOutAndDestroySession` has been removed from class `Auth`. Instead, call the two separate methods `logOut` and `destroySession` from class `Auth` one after another for the same effect.
|
||||
|
||||
* If you have been using the return values of the methods `confirmEmail` or `confirmEmailAndSignIn` from class `Auth`, these return values have changed. Instead of only returning the new email address (which has just been verified), both methods now return an array with the old email address (if any) at index zero and the new email address (which has just been verified) at index one.
|
||||
|
||||
## 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 method `logOutButKeepSession` from class `Auth` is now simply called `logOut`. Therefore, the former method `logout` is now called `logOutAndDestroySession`.
|
||||
|
||||
* 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`.
|
||||
|
||||
|
379
README.md
379
README.md
@@ -18,9 +18,9 @@ Completely framework-agnostic and database-agnostic.
|
||||
|
||||
* PHP 5.6.0+
|
||||
* PDO (PHP Data Objects) extension (`pdo`)
|
||||
* MySQL Native Driver (`mysqlnd`) **or** SQLite driver (`sqlite`)
|
||||
* MySQL Native Driver (`mysqlnd`) **or** PostgreSQL driver (`pgsql`) **or** SQLite driver (`sqlite`)
|
||||
* OpenSSL extension (`openssl`)
|
||||
* MySQL 5.5.3+ **or** MariaDB 5.5.23+ **or** SQLite 3.14.1+ **or** other SQL databases that you create the [schema](Database) for
|
||||
* MySQL 5.5.3+ **or** MariaDB 5.5.23+ **or** PostgreSQL 9.5.10+ **or** SQLite 3.14.1+ **or** [other SQL databases](Database)
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -38,7 +38,9 @@ Completely framework-agnostic and database-agnostic.
|
||||
|
||||
1. Set up a database and create the required tables:
|
||||
|
||||
* [MariaDB](Database/MySQL.sql)
|
||||
* [MySQL](Database/MySQL.sql)
|
||||
* [PostgreSQL](Database/PostgreSQL.sql)
|
||||
* [SQLite](Database/SQLite.sql)
|
||||
|
||||
## Upgrading
|
||||
@@ -53,6 +55,9 @@ Migrating from an earlier version of this project? See our [upgrade guide](Migra
|
||||
* [Email verification](#email-verification)
|
||||
* [Keeping the user logged in](#keeping-the-user-logged-in)
|
||||
* [Password reset (“forgot password”)](#password-reset-forgot-password)
|
||||
* [Initiating the request](#step-1-of-3-initiating-the-request)
|
||||
* [Verifying an attempt](#step-2-of-3-verifying-an-attempt)
|
||||
* [Updating the password](#step-3-of-3-updating-the-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)
|
||||
@@ -62,6 +67,7 @@ Migrating from an earlier version of this project? See our [upgrade guide](Migra
|
||||
* [User ID](#user-id)
|
||||
* [Email address](#email-address)
|
||||
* [Display name](#display-name)
|
||||
* [Status information](#status-information)
|
||||
* [Checking whether the user was “remembered”](#checking-whether-the-user-was-remembered)
|
||||
* [IP address](#ip-address)
|
||||
* [Additional user information](#additional-user-information)
|
||||
@@ -80,6 +86,7 @@ Migrating from an earlier version of this project? See our [upgrade guide](Migra
|
||||
* [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)
|
||||
* [Changing a user’s password](#changing-a-users-password)
|
||||
* [Cookies](#cookies)
|
||||
* [Renaming the library’s cookies](#renaming-the-librarys-cookies)
|
||||
* [Defining the domain scope for cookies](#defining-the-domain-scope-for-cookies)
|
||||
@@ -96,18 +103,22 @@ Migrating from an earlier version of this project? See our [upgrade guide](Migra
|
||||
```php
|
||||
// $db = new \PDO('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
|
||||
// or
|
||||
// $db = new \PDO('pgsql:dbname=my-database;host=localhost;port=5432', 'my-username', 'my-password');
|
||||
// or
|
||||
// $db = new \PDO('sqlite:../Databases/my-database.sqlite');
|
||||
|
||||
// or
|
||||
|
||||
// $db = new \Delight\Db\PdoDsn('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
|
||||
// or
|
||||
// $db = new \Delight\Db\PdoDsn('pgsql:dbname=my-database;host=localhost;port=5432', 'my-username', 'my-password');
|
||||
// or
|
||||
// $db = new \Delight\Db\PdoDsn('sqlite:../Databases/my-database.sqlite');
|
||||
|
||||
$auth = new \Delight\Auth\Auth($db);
|
||||
```
|
||||
|
||||
If you have an open `PDO` connection already, just re-use it.
|
||||
If you have an open `PDO` connection already, just re-use it. The database user (e.g. `my-username`) needs at least the privileges `SELECT`, `INSERT`, `UPDATE` and `DELETE` for the tables used by this library (or their parent database).
|
||||
|
||||
If your web server is behind a proxy server and `$_SERVER['REMOTE_ADDR']` only contains the proxy’s IP address, you must pass the user’s real IP address to the constructor in the second argument, which is named `$ipAddress`. The default is the usual remote IP address received by PHP.
|
||||
|
||||
@@ -115,30 +126,36 @@ Should your database tables for this library need a common prefix, e.g. `my_user
|
||||
|
||||
During development, you may want to disable the request limiting or throttling performed by this library. To do so, pass `false` to the constructor as the fourth argument, which is named `$throttling`. The feature is enabled by default.
|
||||
|
||||
During the lifetime of a session, some user data may be changed remotely, either by a client in another session or by an administrator. That means this information must be regularly resynchronized with its authoritative source in the database, which this library does automatically. By default, this happens every five minutes. If you want to change this interval, pass a custom interval in seconds to the constructor as the fifth argument, which is named `$sessionResyncInterval`.
|
||||
|
||||
If all your database tables need a common database name, schema name, or other qualifier that must be specified explicitly, you can optionally pass that qualifier to the constructor as the sixth parameter, which is named `$dbSchema`.
|
||||
|
||||
### Registration (sign up)
|
||||
|
||||
```php
|
||||
try {
|
||||
$userId = $auth->register($_POST['email'], $_POST['password'], $_POST['username'], function ($selector, $token) {
|
||||
// send `$selector` and `$token` to the user (e.g. via email)
|
||||
echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)';
|
||||
});
|
||||
|
||||
// we have signed up a new user with the ID `$userId`
|
||||
echo 'We have signed up a new user with the ID ' . $userId;
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// invalid email address
|
||||
die('Invalid email address');
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
// invalid password
|
||||
die('Invalid password');
|
||||
}
|
||||
catch (\Delight\Auth\UserAlreadyExistsException $e) {
|
||||
// user already exists
|
||||
die('User already exists');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** The anonymous callback function is a [closure](http://php.net/manual/en/functions.anonymous.php). Thus, besides its own parameters, only [superglobals](http://php.net/manual/en/language.variables.superglobals.php) like `$_GET`, `$_POST`, `$_COOKIE` and `$_SERVER` are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a `use` clause after the parameter list.
|
||||
|
||||
The username in the third parameter is optional. You can pass `null` there if you don’t want to manage usernames.
|
||||
|
||||
If you want to enforce unique usernames, on the other hand, simply call `registerWithUniqueUsername` instead of `register`, and be prepared to catch the `DuplicateUsernameException`.
|
||||
@@ -151,25 +168,27 @@ $url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector)
|
||||
|
||||
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.
|
||||
|
||||
Need to store additional user information? Read on [here](#additional-user-information).
|
||||
|
||||
### Login (sign in)
|
||||
|
||||
```php
|
||||
try {
|
||||
$auth->login($_POST['email'], $_POST['password']);
|
||||
|
||||
// user is logged in
|
||||
echo 'User is logged in';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// wrong email address
|
||||
die('Wrong email address');
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
// wrong password
|
||||
die('Wrong password');
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email not verified
|
||||
die('Email not verified');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -183,24 +202,26 @@ Extract the selector and token from the URL that the user clicked on in the veri
|
||||
try {
|
||||
$auth->confirmEmail($_GET['selector'], $_GET['token']);
|
||||
|
||||
// email address has been verified
|
||||
echo 'Email address has been verified';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
|
||||
// invalid token
|
||||
die('Invalid token');
|
||||
}
|
||||
catch (\Delight\Auth\TokenExpiredException $e) {
|
||||
// token expired
|
||||
die('Token expired');
|
||||
}
|
||||
catch (\Delight\Auth\UserAlreadyExistsException $e) {
|
||||
// email address already exists
|
||||
die('Email address already exists');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('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.
|
||||
|
||||
On success, the two methods `confirmEmail` and `confirmEmailAndSignIn` both return an array with the user’s new email address, which has just been verified, at index one. If the confirmation was for an address change instead of a simple address verification, the user’s old email address will be included in the array at index zero.
|
||||
|
||||
### Keeping the user logged in
|
||||
|
||||
The third parameter to the `Auth#login` and `Auth#confirmEmailAndSignIn` methods controls whether the login is persistent with a long-lived cookie. With such a persistent login, users may stay authenticated for a long time, even when the browser session has already been closed and the session cookies have expired. Typically, you’ll want to keep the user logged in for weeks or months with this feature, which is known as “remember me” or “keep me logged in”. Many users will find this more convenient, but it may be less secure if they leave their devices unattended.
|
||||
@@ -228,72 +249,111 @@ Omit the third parameter or set it to `null` to disable the feature. Otherwise,
|
||||
|
||||
### Password reset (“forgot password”)
|
||||
|
||||
#### Step 1 of 3: Initiating the request
|
||||
|
||||
```php
|
||||
try {
|
||||
$auth->forgotPassword($_POST['email'], function ($selector, $token) {
|
||||
// send `$selector` and `$token` to the user (e.g. via email)
|
||||
echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)';
|
||||
});
|
||||
|
||||
// request has been generated
|
||||
echo 'Request has been generated';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// invalid email address
|
||||
die('Invalid email address');
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email not verified
|
||||
die('Email not verified');
|
||||
}
|
||||
catch (\Delight\Auth\ResetDisabledException $e) {
|
||||
// password reset is disabled
|
||||
die('Password reset is disabled');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** The anonymous callback function is a [closure](http://php.net/manual/en/functions.anonymous.php). Thus, besides its own parameters, only [superglobals](http://php.net/manual/en/language.variables.superglobals.php) like `$_GET`, `$_POST`, `$_COOKIE` and `$_SERVER` are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a `use` clause after the parameter list.
|
||||
|
||||
You should build an URL with the selector and token and send it to the user, e.g.:
|
||||
|
||||
```php
|
||||
$url = 'https://www.example.com/reset_password?selector=' . \urlencode($selector) . '&token=' . \urlencode($token);
|
||||
```
|
||||
|
||||
If the default lifetime of the password reset requests does not work for you, you can use the third parameter of `Auth#forgotPassword` to specify a custom interval in seconds after which the requests should expire.
|
||||
|
||||
#### Step 2 of 3: Verifying an attempt
|
||||
|
||||
As the next step, users will click on the link that they received. Extract the selector and token from the URL.
|
||||
|
||||
If the selector/token pair is valid, let the user choose a new password:
|
||||
|
||||
```php
|
||||
if ($auth->canResetPassword($_POST['selector'], $_POST['token'])) {
|
||||
// put the selector into a `hidden` field (or keep it in the URL)
|
||||
// put the token into a `hidden` field (or keep it in the URL)
|
||||
try {
|
||||
$auth->canResetPasswordOrThrow($_GET['selector'], $_GET['token']);
|
||||
|
||||
// ask the user for their new password
|
||||
echo 'Put the selector into a "hidden" field (or keep it in the URL)';
|
||||
echo 'Put the token into a "hidden" field (or keep it in the URL)';
|
||||
|
||||
echo 'Ask the user for their new password';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
|
||||
die('Invalid token');
|
||||
}
|
||||
catch (\Delight\Auth\TokenExpiredException $e) {
|
||||
die('Token expired');
|
||||
}
|
||||
catch (\Delight\Auth\ResetDisabledException $e) {
|
||||
die('Password reset is disabled');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
Alternatively, if you don’t need any error messages but only want to check the validity, you can use the slightly simpler version:
|
||||
|
||||
```php
|
||||
if ($auth->canResetPassword($_GET['selector'], $_GET['token'])) {
|
||||
echo 'Put the selector into a "hidden" field (or keep it in the URL)';
|
||||
echo 'Put the token into a "hidden" field (or keep it in the URL)';
|
||||
|
||||
echo 'Ask the user for their new password';
|
||||
}
|
||||
```
|
||||
|
||||
#### Step 3 of 3: Updating the password
|
||||
|
||||
Now when you have the new password for the user (and still have the other two pieces of information), you can reset the password:
|
||||
|
||||
```php
|
||||
try {
|
||||
$auth->resetPassword($_POST['selector'], $_POST['token'], $_POST['password']);
|
||||
|
||||
// password has been reset
|
||||
echo 'Password has been reset';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
|
||||
// invalid token
|
||||
die('Invalid token');
|
||||
}
|
||||
catch (\Delight\Auth\TokenExpiredException $e) {
|
||||
// token expired
|
||||
die('Token expired');
|
||||
}
|
||||
catch (\Delight\Auth\ResetDisabledException $e) {
|
||||
// password reset is disabled
|
||||
die('Password reset is disabled');
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
// invalid password
|
||||
die('Invalid password');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
Do you want to have the respective user signed in automatically when their password reset succeeds? Simply use `Auth#resetPasswordAndSignIn` instead of `Auth#resetPassword` to log in the user immediately.
|
||||
|
||||
If you need the user’s ID or email address, e.g. for sending them a notification that their password has successfully been reset, just use the return value of `Auth#resetPassword`, which is an array containing two entries named `id` and `email`.
|
||||
|
||||
### Changing the current user’s password
|
||||
|
||||
If a user is currently logged in, they may change their password.
|
||||
@@ -302,16 +362,16 @@ If a user is currently logged in, they may change their password.
|
||||
try {
|
||||
$auth->changePassword($_POST['oldPassword'], $_POST['newPassword']);
|
||||
|
||||
// password has been changed
|
||||
echo 'Password has been changed';
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
// not logged in
|
||||
die('Not logged in');
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
// invalid password(s)
|
||||
die('Invalid password(s)');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -329,32 +389,34 @@ If a user is currently logged in, they may change their email address.
|
||||
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)
|
||||
echo '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
|
||||
echo '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
|
||||
echo 'We can\'t say if the user is who they claim to be';
|
||||
}
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// invalid email address
|
||||
die('Invalid email address');
|
||||
}
|
||||
catch (\Delight\Auth\UserAlreadyExistsException $e) {
|
||||
// email address already exists
|
||||
die('Email address already exists');
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// account not verified
|
||||
die('Account not verified');
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
// not logged in
|
||||
die('Not logged in');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** The anonymous callback function is a [closure](http://php.net/manual/en/functions.anonymous.php). Thus, besides its own parameters, only [superglobals](http://php.net/manual/en/language.variables.superglobals.php) like `$_GET`, `$_POST`, `$_COOKIE` and `$_SERVER` are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a `use` clause after the parameter list.
|
||||
|
||||
For email verification, you should build an URL with the selector and token and send it to the user, e.g.:
|
||||
|
||||
```php
|
||||
@@ -363,6 +425,8 @@ $url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector)
|
||||
|
||||
After the request to change the email address has been made, or even better, after the change has been confirmed by the user, you should send an email to their account’s *previous* email address as an out-of-band notification informing the account owner about this critical change.
|
||||
|
||||
**Note:** Changes to a user’s email address take effect in the local session immediately, as expected. In other sessions (e.g. on other devices), the changes may need up to five minutes to take effect, though. This increases performance and usually poses no problem. If you want to change this behavior, nevertheless, simply decrease (or perhaps increase) the value that you pass to the [`Auth` constructor](#creating-a-new-instance) as the argument named `$sessionResyncInterval`.
|
||||
|
||||
### Re-sending confirmation requests
|
||||
|
||||
If an earlier confirmation request could not be delivered to the user, or if the user missed that request, or if they just don’t want to wait any longer, you may re-send an earlier request like this:
|
||||
@@ -370,16 +434,16 @@ If an earlier confirmation request could not be delivered to the user, or if the
|
||||
```php
|
||||
try {
|
||||
$auth->resendConfirmationForEmail($_POST['email'], function ($selector, $token) {
|
||||
// send `$selector` and `$token` to the user (e.g. via email)
|
||||
echo '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)
|
||||
echo '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
|
||||
die('No earlier request found that could be re-sent');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// there have been too many requests -- try again later
|
||||
die('There have been too many requests -- try again later');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -388,19 +452,21 @@ If you want to specify the user by their ID instead of by their email address, t
|
||||
```php
|
||||
try {
|
||||
$auth->resendConfirmationForUserId($_POST['userId'], function ($selector, $token) {
|
||||
// send `$selector` and `$token` to the user (e.g. via email)
|
||||
echo '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)
|
||||
echo '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
|
||||
die('No earlier request found that could be re-sent');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// there have been too many requests -- try again later
|
||||
die('There have been too many requests -- try again later');
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** The anonymous callback function is a [closure](http://php.net/manual/en/functions.anonymous.php). Thus, besides its own parameters, only [superglobals](http://php.net/manual/en/language.variables.superglobals.php) like `$_GET`, `$_POST`, `$_COOKIE` and `$_SERVER` are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a `use` clause after the parameter list.
|
||||
|
||||
Usually, you should build an URL with the selector and token and send it to the user, e.g. as follows:
|
||||
|
||||
```php
|
||||
@@ -411,22 +477,44 @@ $url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector)
|
||||
|
||||
```php
|
||||
$auth->logOut();
|
||||
// or
|
||||
$auth->logOutAndDestroySession();
|
||||
|
||||
// user has been signed out
|
||||
// or
|
||||
|
||||
try {
|
||||
$auth->logOutEverywhereElse();
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
die('Not logged in');
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
try {
|
||||
$auth->logOutEverywhere();
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
die('Not logged in');
|
||||
}
|
||||
```
|
||||
|
||||
Additionally, if you store custom information in the session as well, and if you want that information to be deleted, you can destroy the entire session by calling a second method:
|
||||
|
||||
```php
|
||||
$auth->destroySession();
|
||||
```
|
||||
|
||||
**Note:** Global logouts take effect in the local session immediately, as expected. In other sessions (e.g. on other devices), the changes may need up to five minutes to take effect, though. This increases performance and usually poses no problem. If you want to change this behavior, nevertheless, simply decrease (or perhaps increase) the value that you pass to the [`Auth` constructor](#creating-a-new-instance) as the argument named `$sessionResyncInterval`.
|
||||
|
||||
### Accessing user information
|
||||
|
||||
#### Login state
|
||||
|
||||
```php
|
||||
if ($auth->isLoggedIn()) {
|
||||
// user is signed in
|
||||
echo 'User is signed in';
|
||||
}
|
||||
else {
|
||||
// user is *not* signed in yet
|
||||
echo 'User is not signed in yet';
|
||||
}
|
||||
```
|
||||
|
||||
@@ -453,7 +541,7 @@ If the user is not currently signed in, this returns `null`.
|
||||
#### Display name
|
||||
|
||||
```php
|
||||
$email = $auth->getUsername();
|
||||
$username = $auth->getUsername();
|
||||
```
|
||||
|
||||
Remember that usernames are optional and there is only a username if you supplied it during registration.
|
||||
@@ -464,27 +552,27 @@ If the user is not currently signed in, this returns `null`.
|
||||
|
||||
```php
|
||||
if ($auth->isNormal()) {
|
||||
// user is in default state
|
||||
echo 'User is in default state';
|
||||
}
|
||||
|
||||
if ($auth->isArchived()) {
|
||||
// user has been archived
|
||||
echo 'User has been archived';
|
||||
}
|
||||
|
||||
if ($auth->isBanned()) {
|
||||
// user has been banned
|
||||
echo 'User has been banned';
|
||||
}
|
||||
|
||||
if ($auth->isLocked()) {
|
||||
// user has been locked
|
||||
echo 'User has been locked';
|
||||
}
|
||||
|
||||
if ($auth->isPendingReview()) {
|
||||
// user is pending review
|
||||
echo 'User is pending review';
|
||||
}
|
||||
|
||||
if ($auth->isSuspended()) {
|
||||
// user has been suspended
|
||||
echo 'User has been suspended';
|
||||
}
|
||||
```
|
||||
|
||||
@@ -492,10 +580,10 @@ if ($auth->isSuspended()) {
|
||||
|
||||
```php
|
||||
if ($auth->isRemembered()) {
|
||||
// user did not sign in but was logged in through their long-lived cookie
|
||||
echo 'User did not sign in but was logged in through their long-lived cookie';
|
||||
}
|
||||
else {
|
||||
// user signed in manually
|
||||
echo 'User signed in manually';
|
||||
}
|
||||
```
|
||||
|
||||
@@ -541,17 +629,17 @@ For example, when a user has been remembered by a long-lived cookie and thus `Au
|
||||
```php
|
||||
try {
|
||||
if ($auth->reconfirmPassword($_POST['password'])) {
|
||||
// the user really seems to be who they claim to be
|
||||
echo '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
|
||||
echo 'We can\'t say if the user is who they claim to be';
|
||||
}
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
// the user is not signed in
|
||||
die('The user is not signed in');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -565,24 +653,30 @@ Users may have no role at all (which they do by default), exactly one role, or a
|
||||
|
||||
```php
|
||||
if ($auth->hasRole(\Delight\Auth\Role::SUPER_MODERATOR)) {
|
||||
// the user is a super moderator
|
||||
echo '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
|
||||
echo '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
|
||||
echo '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.
|
||||
|
||||
Alternatively, you can get a list of all the roles that have been assigned to the user:
|
||||
|
||||
```php
|
||||
$auth->getRoles();
|
||||
```
|
||||
|
||||
#### Available roles
|
||||
|
||||
```php
|
||||
@@ -610,7 +704,15 @@ While the method `hasRole` takes exactly one role as its argument, the two metho
|
||||
\Delight\Auth\Role::TRANSLATOR;
|
||||
```
|
||||
|
||||
You can use any of these roles and ignore those that you don’t need.
|
||||
You can use any of these roles and ignore those that you don’t need. The list above can also be retrieved programmatically, in one of three formats:
|
||||
|
||||
```php
|
||||
\Delight\Auth\Role::getMap();
|
||||
// or
|
||||
\Delight\Auth\Role::getNames();
|
||||
// or
|
||||
\Delight\Auth\Role::getValues();
|
||||
```
|
||||
|
||||
#### Permissions (or access rights, privileges or capabilities)
|
||||
|
||||
@@ -630,20 +732,20 @@ function canEditArticle(\Delight\Auth\Auth $auth) {
|
||||
|
||||
// ...
|
||||
|
||||
if (canEditArticle($app->auth())) {
|
||||
// the user can edit articles here
|
||||
if (canEditArticle($auth)) {
|
||||
echo 'The user can edit articles here';
|
||||
}
|
||||
|
||||
// ...
|
||||
|
||||
if (canEditArticle($app->auth())) {
|
||||
// ... and here
|
||||
if (canEditArticle($auth)) {
|
||||
echo '... and here';
|
||||
}
|
||||
|
||||
// ...
|
||||
|
||||
if (canEditArticle($app->auth())) {
|
||||
// ... and here
|
||||
if (canEditArticle($auth)) {
|
||||
echo '... and here';
|
||||
}
|
||||
```
|
||||
|
||||
@@ -699,17 +801,17 @@ try {
|
||||
if ($auth->reconfirmPassword($_POST['password'])) {
|
||||
$auth->setPasswordResetEnabled($_POST['enabled'] == 1);
|
||||
|
||||
// the setting has been changed
|
||||
echo 'The setting has been changed';
|
||||
}
|
||||
else {
|
||||
// we can't say if the user is who they claim to be
|
||||
echo 'We can\'t say if the user is who they claim to be';
|
||||
}
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
// the user is not signed in
|
||||
die('The user is not signed in');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -732,7 +834,7 @@ 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
|
||||
echo 'Do something with the resource or feature';
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// operation cancelled
|
||||
@@ -766,16 +868,16 @@ Do not forget to implement secure access control before exposing access to this
|
||||
try {
|
||||
$userId = $auth->admin()->createUser($_POST['email'], $_POST['password'], $_POST['username']);
|
||||
|
||||
// we have signed up a new user with the ID `$userId`
|
||||
echo 'We have signed up a new user with the ID ' . $userId;
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// invalid email address
|
||||
die('Invalid email address');
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
// invalid password
|
||||
die('Invalid password');
|
||||
}
|
||||
catch (\Delight\Auth\UserAlreadyExistsException $e) {
|
||||
// user already exists
|
||||
die('User already exists');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -792,7 +894,7 @@ try {
|
||||
$auth->admin()->deleteUserById($_POST['id']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown ID
|
||||
die('Unknown ID');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -803,7 +905,7 @@ try {
|
||||
$auth->admin()->deleteUserByEmail($_POST['email']);
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// unknown email address
|
||||
die('Unknown email address');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -814,13 +916,23 @@ try {
|
||||
$auth->admin()->deleteUserByUsername($_POST['username']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
// unknown username
|
||||
die('Unknown username');
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
// ambiguous username
|
||||
die('Ambiguous username');
|
||||
}
|
||||
```
|
||||
|
||||
#### Retrieving a list of registered users
|
||||
|
||||
When fetching a list of all users, the requirements vary greatly between projects and use cases, and customization is common. For example, you might want to fetch different columns, join related tables, filter by certain criteria, change how results are sorted (in varying direction), and limit the number of results (while providing an offset).
|
||||
|
||||
That’s why it’s easier to use a single custom SQL query. Start with the following:
|
||||
|
||||
```sql
|
||||
SELECT id, email, username, status, verified, roles_mask, registered, last_login FROM users;
|
||||
```
|
||||
|
||||
#### Assigning roles to users
|
||||
|
||||
```php
|
||||
@@ -828,7 +940,7 @@ try {
|
||||
$auth->admin()->addRoleForUserById($userId, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown user ID
|
||||
die('Unknown user ID');
|
||||
}
|
||||
|
||||
// or
|
||||
@@ -837,7 +949,7 @@ try {
|
||||
$auth->admin()->addRoleForUserByEmail($userEmail, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// unknown email address
|
||||
die('Unknown email address');
|
||||
}
|
||||
|
||||
// or
|
||||
@@ -846,13 +958,15 @@ try {
|
||||
$auth->admin()->addRoleForUserByUsername($username, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
// unknown username
|
||||
die('Unknown username');
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
// ambiguous username
|
||||
die('Ambiguous username');
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** Changes to a user’s set of roles may need up to five minutes to take effect. This increases performance and usually poses no problem. If you want to change this behavior, nevertheless, simply decrease (or perhaps increase) the value that you pass to the [`Auth` constructor](#creating-a-new-instance) as the argument named `$sessionResyncInterval`.
|
||||
|
||||
#### Taking roles away from users
|
||||
|
||||
```php
|
||||
@@ -860,7 +974,7 @@ try {
|
||||
$auth->admin()->removeRoleForUserById($userId, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown user ID
|
||||
die('Unknown user ID');
|
||||
}
|
||||
|
||||
// or
|
||||
@@ -869,7 +983,7 @@ try {
|
||||
$auth->admin()->removeRoleForUserByEmail($userEmail, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// unknown email address
|
||||
die('Unknown email address');
|
||||
}
|
||||
|
||||
// or
|
||||
@@ -878,29 +992,37 @@ try {
|
||||
$auth->admin()->removeRoleForUserByUsername($username, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
// unknown username
|
||||
die('Unknown username');
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
// ambiguous username
|
||||
die('Ambiguous username');
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** Changes to a user’s set of roles may need up to five minutes to take effect. This increases performance and usually poses no problem. If you want to change this behavior, nevertheless, simply decrease (or perhaps increase) the value that you pass to the [`Auth` constructor](#creating-a-new-instance) as the argument named `$sessionResyncInterval`.
|
||||
|
||||
#### Checking roles
|
||||
|
||||
```php
|
||||
try {
|
||||
if ($auth->admin()->doesUserHaveRole($userId, \Delight\Auth\Role::ADMIN)) {
|
||||
// the specified user is an administrator
|
||||
echo 'The specified user is an administrator';
|
||||
}
|
||||
else {
|
||||
// the specified user is *not* an administrator
|
||||
echo 'The specified user is not an administrator';
|
||||
}
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown user ID
|
||||
die('Unknown user ID');
|
||||
}
|
||||
```
|
||||
|
||||
Alternatively, you can get a list of all the roles that have been assigned to the user:
|
||||
|
||||
```php
|
||||
$auth->admin()->getRolesForUserById($userId);
|
||||
```
|
||||
|
||||
#### Impersonating users (logging in as user)
|
||||
|
||||
```php
|
||||
@@ -908,10 +1030,10 @@ try {
|
||||
$auth->admin()->logInAsUserById($_POST['id']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown ID
|
||||
die('Unknown ID');
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email address not verified
|
||||
die('Email address not verified');
|
||||
}
|
||||
|
||||
// or
|
||||
@@ -920,10 +1042,10 @@ try {
|
||||
$auth->admin()->logInAsUserByEmail($_POST['email']);
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// unknown email address
|
||||
die('Unknown email address');
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email address not verified
|
||||
die('Email address not verified');
|
||||
}
|
||||
|
||||
// or
|
||||
@@ -932,13 +1054,42 @@ try {
|
||||
$auth->admin()->logInAsUserByUsername($_POST['username']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
// unknown username
|
||||
die('Unknown username');
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
// ambiguous username
|
||||
die('Ambiguous username');
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email address not verified
|
||||
die('Email address not verified');
|
||||
}
|
||||
```
|
||||
|
||||
#### Changing a user’s password
|
||||
|
||||
```php
|
||||
try {
|
||||
$auth->admin()->changePasswordForUserById($_POST['id'], $_POST['newPassword']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
die('Unknown ID');
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
die('Invalid password');
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
try {
|
||||
$auth->admin()->changePasswordForUserByUsername($_POST['username'], $_POST['newPassword']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
die('Unknown username');
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
die('Ambiguous username');
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
die('Invalid password');
|
||||
}
|
||||
```
|
||||
|
||||
|
@@ -6,7 +6,7 @@
|
||||
"ext-openssl": "*",
|
||||
"delight-im/base64": "^1.0",
|
||||
"delight-im/cookie": "^3.1",
|
||||
"delight-im/db": "^1.2"
|
||||
"delight-im/db": "^1.3"
|
||||
},
|
||||
"type": "library",
|
||||
"keywords": [ "auth", "authentication", "login", "security" ],
|
||||
|
12
composer.lock
generated
12
composer.lock
generated
@@ -4,7 +4,7 @@
|
||||
"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": "54d541ae3c5ba25b0cc06688d2b65467",
|
||||
"content-hash": "e4acd9e4ba13c4d0692f07a03a454859",
|
||||
"packages": [
|
||||
{
|
||||
"name": "delight-im/base64",
|
||||
@@ -90,16 +90,16 @@
|
||||
},
|
||||
{
|
||||
"name": "delight-im/db",
|
||||
"version": "v1.2.0",
|
||||
"version": "v1.3.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/delight-im/PHP-DB.git",
|
||||
"reference": "df99ef7c2e86c7ce206647ffe8ba74447c075b57"
|
||||
"reference": "7a03da20b5592fa445c10cd6c7245d51037292c4"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/delight-im/PHP-DB/zipball/df99ef7c2e86c7ce206647ffe8ba74447c075b57",
|
||||
"reference": "df99ef7c2e86c7ce206647ffe8ba74447c075b57",
|
||||
"url": "https://api.github.com/repos/delight-im/PHP-DB/zipball/7a03da20b5592fa445c10cd6c7245d51037292c4",
|
||||
"reference": "7a03da20b5592fa445c10cd6c7245d51037292c4",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -127,7 +127,7 @@
|
||||
"sql",
|
||||
"sqlite"
|
||||
],
|
||||
"time": "2017-03-18T20:51:59+00:00"
|
||||
"time": "2018-08-28T18:23:01+00:00"
|
||||
},
|
||||
{
|
||||
"name": "delight-im/http",
|
||||
|
@@ -9,6 +9,7 @@
|
||||
namespace Delight\Auth;
|
||||
|
||||
use Delight\Db\PdoDatabase;
|
||||
use Delight\Db\PdoDsn;
|
||||
use Delight\Db\Throwable\Error;
|
||||
|
||||
require_once __DIR__ . '/Exceptions.php';
|
||||
@@ -17,13 +18,12 @@ require_once __DIR__ . '/Exceptions.php';
|
||||
final class Administration extends UserManager {
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*
|
||||
* @param PdoDatabase $databaseConnection the database connection to operate on
|
||||
* @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
|
||||
* @param string|null $dbSchema (optional) the schema name for all database tables used by this component
|
||||
*/
|
||||
public function __construct(PdoDatabase $databaseConnection, $dbTablePrefix = null) {
|
||||
parent::__construct($databaseConnection, $dbTablePrefix);
|
||||
public function __construct($databaseConnection, $dbTablePrefix = null, $dbSchema = null) {
|
||||
parent::__construct($databaseConnection, $dbTablePrefix, $dbSchema);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -271,11 +271,14 @@ final class Administration extends UserManager {
|
||||
* @see Role
|
||||
*/
|
||||
public function doesUserHaveRole($userId, $role) {
|
||||
if (empty($role) || !\is_numeric($role)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$userId = (int) $userId;
|
||||
$role = (int) $role;
|
||||
|
||||
$rolesBitmask = $this->db->selectValue(
|
||||
'SELECT roles_mask FROM ' . $this->dbTablePrefix . 'users WHERE id = ?',
|
||||
'SELECT roles_mask FROM ' . $this->makeTableName('users') . ' WHERE id = ?',
|
||||
[ $userId ]
|
||||
);
|
||||
|
||||
@@ -283,9 +286,41 @@ final class Administration extends UserManager {
|
||||
throw new UnknownIdException();
|
||||
}
|
||||
|
||||
$role = (int) $role;
|
||||
|
||||
return ($rolesBitmask & $role) === $role;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the roles of the user with the given ID, mapping the numerical values to their descriptive names
|
||||
*
|
||||
* @param int $userId the ID of the user to return the roles for
|
||||
* @return array
|
||||
* @throws UnknownIdException if no user with the specified ID has been found
|
||||
*
|
||||
* @see Role
|
||||
*/
|
||||
public function getRolesForUserById($userId) {
|
||||
$userId = (int) $userId;
|
||||
|
||||
$rolesBitmask = $this->db->selectValue(
|
||||
'SELECT roles_mask FROM ' . $this->makeTableName('users') . ' WHERE id = ?',
|
||||
[ $userId ]
|
||||
);
|
||||
|
||||
if ($rolesBitmask === null) {
|
||||
throw new UnknownIdException();
|
||||
}
|
||||
|
||||
return \array_filter(
|
||||
Role::getMap(),
|
||||
function ($each) use ($rolesBitmask) {
|
||||
return ($rolesBitmask & $each) === $each;
|
||||
},
|
||||
\ARRAY_FILTER_USE_KEY
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs in as the user with the specified ID
|
||||
*
|
||||
@@ -340,6 +375,49 @@ final class Administration extends UserManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the password for the user with the given ID
|
||||
*
|
||||
* @param int $userId the ID of the user whose password to change
|
||||
* @param string $newPassword the new password to set
|
||||
* @throws UnknownIdException if no user with the specified ID has been found
|
||||
* @throws InvalidPasswordException if the desired new password has been invalid
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function changePasswordForUserById($userId, $newPassword) {
|
||||
$userId = (int) $userId;
|
||||
$newPassword = self::validatePassword($newPassword);
|
||||
|
||||
$this->updatePasswordInternal(
|
||||
$userId,
|
||||
$newPassword
|
||||
);
|
||||
|
||||
$this->forceLogoutForUserById($userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the password for the user with the given username
|
||||
*
|
||||
* @param string $username the username of the user whose password to change
|
||||
* @param string $newPassword the new password to set
|
||||
* @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 InvalidPasswordException if the desired new password has been invalid
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function changePasswordForUserByUsername($username, $newPassword) {
|
||||
$userData = $this->getUserDataByUsername(
|
||||
\trim($username),
|
||||
[ 'id' ]
|
||||
);
|
||||
|
||||
$this->changePasswordForUserById(
|
||||
(int) $userData['id'],
|
||||
$newPassword
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all existing users where the column with the specified name has the given value
|
||||
*
|
||||
@@ -353,14 +431,14 @@ final class Administration extends UserManager {
|
||||
private function deleteUsersByColumnValue($columnName, $columnValue) {
|
||||
try {
|
||||
return $this->db->delete(
|
||||
$this->dbTablePrefix . 'users',
|
||||
$this->makeTableNameComponents('users'),
|
||||
[
|
||||
$columnName => $columnValue
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -380,12 +458,12 @@ final class Administration extends UserManager {
|
||||
private function modifyRolesForUserByColumnValue($columnName, $columnValue, callable $modification) {
|
||||
try {
|
||||
$userData = $this->db->selectRow(
|
||||
'SELECT id, roles_mask FROM ' . $this->dbTablePrefix . 'users WHERE ' . $columnName . ' = ?',
|
||||
'SELECT id, roles_mask FROM ' . $this->makeTableName('users') . ' WHERE ' . $columnName . ' = ?',
|
||||
[ $columnValue ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if ($userData === null) {
|
||||
@@ -396,7 +474,7 @@ final class Administration extends UserManager {
|
||||
|
||||
try {
|
||||
$this->db->exec(
|
||||
'UPDATE ' . $this->dbTablePrefix . 'users SET roles_mask = ? WHERE id = ?',
|
||||
'UPDATE ' . $this->makeTableName('users') . ' SET roles_mask = ? WHERE id = ?',
|
||||
[
|
||||
$newRolesBitmask,
|
||||
(int) $userData['id']
|
||||
@@ -406,7 +484,7 @@ final class Administration extends UserManager {
|
||||
return true;
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -472,21 +550,21 @@ final class Administration extends UserManager {
|
||||
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',
|
||||
'SELECT verified, id, email, username, status, roles_mask FROM ' . $this->makeTableName('users') . ' WHERE ' . $columnName . ' = ? LIMIT 2 OFFSET 0',
|
||||
[ $columnValue ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
$numberOfMatchingUsers = \count($users);
|
||||
$numberOfMatchingUsers = ($users !== null) ? \count($users) : 0;
|
||||
|
||||
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);
|
||||
$this->onLoginSuccessful($user['id'], $user['email'], $user['username'], $user['status'], $user['roles_mask'], \PHP_INT_MAX, false);
|
||||
}
|
||||
else {
|
||||
throw new EmailNotVerifiedException();
|
||||
|
533
src/Auth.php
533
src/Auth.php
@@ -28,30 +28,37 @@ final class Auth extends UserManager {
|
||||
private $ipAddress;
|
||||
/** @var bool whether throttling should be enabled (e.g. in production) or disabled (e.g. during development) */
|
||||
private $throttling;
|
||||
/** @var int the interval in seconds after which to resynchronize the session data with its authoritative source in the database */
|
||||
private $sessionResyncInterval;
|
||||
/** @var string the name of the cookie used for the 'remember me' feature */
|
||||
private $rememberCookieName;
|
||||
|
||||
/**
|
||||
* @param PdoDatabase|PdoDsn|\PDO $databaseConnection the database connection to operate on
|
||||
* @param string $ipAddress the IP address that should be used instead of the default setting (if any), e.g. when behind a proxy
|
||||
* @param string|null $ipAddress (optional) the IP address that should be used instead of the default setting (if any), e.g. when behind a proxy
|
||||
* @param string|null $dbTablePrefix (optional) the prefix for the names of all database tables used by this component
|
||||
* @param bool|null $throttling (optional) whether throttling should be enabled (e.g. in production) or disabled (e.g. during development)
|
||||
* @param int|null $sessionResyncInterval (optional) the interval in seconds after which to resynchronize the session data with its authoritative source in the database
|
||||
* @param string|null $dbSchema (optional) the schema name for all database tables used by this component
|
||||
*/
|
||||
public function __construct($databaseConnection, $ipAddress = null, $dbTablePrefix = null, $throttling = null) {
|
||||
parent::__construct($databaseConnection, $dbTablePrefix);
|
||||
public function __construct($databaseConnection, $ipAddress = null, $dbTablePrefix = null, $throttling = null, $sessionResyncInterval = null, $dbSchema = null) {
|
||||
parent::__construct($databaseConnection, $dbTablePrefix, $dbSchema);
|
||||
|
||||
$this->ipAddress = !empty($ipAddress) ? $ipAddress : (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null);
|
||||
$this->throttling = isset($throttling) ? (bool) $throttling : true;
|
||||
$this->sessionResyncInterval = isset($sessionResyncInterval) ? ((int) $sessionResyncInterval) : (60 * 5);
|
||||
$this->rememberCookieName = self::createRememberCookieName();
|
||||
|
||||
$this->initSession();
|
||||
$this->initSessionIfNecessary();
|
||||
$this->enhanceHttpSecurity();
|
||||
|
||||
$this->processRememberDirective();
|
||||
$this->resyncSessionIfNecessary();
|
||||
}
|
||||
|
||||
/** Initializes the session and sets the correct configuration */
|
||||
private function initSession() {
|
||||
private function initSessionIfNecessary() {
|
||||
if (\session_status() === \PHP_SESSION_NONE) {
|
||||
// use cookies to store session IDs
|
||||
\ini_set('session.use_cookies', 1);
|
||||
// use cookies only (do not send session IDs in URLs)
|
||||
@@ -62,6 +69,7 @@ final class Auth extends UserManager {
|
||||
// start the session (requests a cookie to be written on the client)
|
||||
@Session::start();
|
||||
}
|
||||
}
|
||||
|
||||
/** Improves the application's security over HTTP(S) by setting specific headers */
|
||||
private function enhanceHttpSecurity() {
|
||||
@@ -107,12 +115,12 @@ final class Auth extends UserManager {
|
||||
if (!empty($parts[0]) && !empty($parts[1])) {
|
||||
try {
|
||||
$rememberData = $this->db->selectRow(
|
||||
'SELECT a.user, a.token, a.expires, b.email, b.username, b.status, b.roles_mask FROM ' . $this->dbTablePrefix . 'users_remembered AS a JOIN ' . $this->dbTablePrefix . 'users AS b ON a.user = b.id WHERE a.selector = ?',
|
||||
'SELECT a.user, a.token, a.expires, b.email, b.username, b.status, b.roles_mask, b.force_logout FROM ' . $this->makeTableName('users_remembered') . ' AS a JOIN ' . $this->makeTableName('users') . ' AS b ON a.user = b.id WHERE a.selector = ?',
|
||||
[ $parts[0] ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if (!empty($rememberData)) {
|
||||
@@ -121,7 +129,7 @@ final class Auth extends UserManager {
|
||||
// the cookie and its contents have now been proven to be valid
|
||||
$valid = true;
|
||||
|
||||
$this->onLoginSuccessful($rememberData['user'], $rememberData['email'], $rememberData['username'], $rememberData['status'], $rememberData['roles_mask'], true);
|
||||
$this->onLoginSuccessful($rememberData['user'], $rememberData['email'], $rememberData['username'], $rememberData['status'], $rememberData['roles_mask'], $rememberData['force_logout'], true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -136,6 +144,60 @@ final class Auth extends UserManager {
|
||||
}
|
||||
}
|
||||
|
||||
private function resyncSessionIfNecessary() {
|
||||
// if the user is signed in
|
||||
if ($this->isLoggedIn()) {
|
||||
// the following session field may not have been initialized for sessions that had already existed before the introduction of this feature
|
||||
if (!isset($_SESSION[self::SESSION_FIELD_LAST_RESYNC])) {
|
||||
$_SESSION[self::SESSION_FIELD_LAST_RESYNC] = 0;
|
||||
}
|
||||
|
||||
// if it's time for resynchronization
|
||||
if (($_SESSION[self::SESSION_FIELD_LAST_RESYNC] + $this->sessionResyncInterval) <= \time()) {
|
||||
// fetch the authoritative data from the database again
|
||||
try {
|
||||
$authoritativeData = $this->db->selectRow(
|
||||
'SELECT email, username, status, roles_mask, force_logout FROM ' . $this->makeTableName('users') . ' WHERE id = ?',
|
||||
[ $this->getUserId() ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
// if the user's data has been found
|
||||
if (!empty($authoritativeData)) {
|
||||
// the following session field may not have been initialized for sessions that had already existed before the introduction of this feature
|
||||
if (!isset($_SESSION[self::SESSION_FIELD_FORCE_LOGOUT])) {
|
||||
$_SESSION[self::SESSION_FIELD_FORCE_LOGOUT] = 0;
|
||||
}
|
||||
|
||||
// if the counter that keeps track of forced logouts has been incremented
|
||||
if ($authoritativeData['force_logout'] > $_SESSION[self::SESSION_FIELD_FORCE_LOGOUT]) {
|
||||
// the user must be signed out
|
||||
$this->logOut();
|
||||
}
|
||||
// if the counter that keeps track of forced logouts has remained unchanged
|
||||
else {
|
||||
// the session data needs to be updated
|
||||
$_SESSION[self::SESSION_FIELD_EMAIL] = $authoritativeData['email'];
|
||||
$_SESSION[self::SESSION_FIELD_USERNAME] = $authoritativeData['username'];
|
||||
$_SESSION[self::SESSION_FIELD_STATUS] = (int) $authoritativeData['status'];
|
||||
$_SESSION[self::SESSION_FIELD_ROLES] = (int) $authoritativeData['roles_mask'];
|
||||
|
||||
// remember that we've just performed the required resynchronization
|
||||
$_SESSION[self::SESSION_FIELD_LAST_RESYNC] = \time();
|
||||
}
|
||||
}
|
||||
// if no data has been found for the user
|
||||
else {
|
||||
// their account may have been deleted so they should be signed out
|
||||
$this->logOut();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to sign up a user
|
||||
*
|
||||
@@ -292,12 +354,12 @@ final class Auth extends UserManager {
|
||||
|
||||
try {
|
||||
$expectedHash = $this->db->selectValue(
|
||||
'SELECT password FROM ' . $this->dbTablePrefix . 'users WHERE id = ?',
|
||||
'SELECT password FROM ' . $this->makeTableName('users') . ' WHERE id = ?',
|
||||
[ $this->getUserId() ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if (!empty($expectedHash)) {
|
||||
@@ -326,13 +388,16 @@ final class Auth extends UserManager {
|
||||
public function logOut() {
|
||||
// if the user has been signed in
|
||||
if ($this->isLoggedIn()) {
|
||||
// get the user's ID
|
||||
$userId = $this->getUserId();
|
||||
// retrieve any locally existing remember directive
|
||||
$rememberDirectiveSelector = $this->getRememberDirectiveSelector();
|
||||
|
||||
// if a user ID was set
|
||||
if (isset($userId)) {
|
||||
// delete any existing remember directives
|
||||
$this->deleteRememberDirective($userId);
|
||||
// if such a remember directive exists
|
||||
if (isset($rememberDirectiveSelector)) {
|
||||
// delete the local remember directive
|
||||
$this->deleteRememberDirectiveForUserById(
|
||||
$this->getUserId(),
|
||||
$rememberDirectiveSelector
|
||||
);
|
||||
}
|
||||
|
||||
// remove all session variables maintained by this library
|
||||
@@ -343,9 +408,66 @@ final class Auth extends UserManager {
|
||||
unset($_SESSION[self::SESSION_FIELD_STATUS]);
|
||||
unset($_SESSION[self::SESSION_FIELD_ROLES]);
|
||||
unset($_SESSION[self::SESSION_FIELD_REMEMBERED]);
|
||||
unset($_SESSION[self::SESSION_FIELD_LAST_RESYNC]);
|
||||
unset($_SESSION[self::SESSION_FIELD_FORCE_LOGOUT]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs the user out in all other sessions (except for the current one)
|
||||
*
|
||||
* @throws NotLoggedInException if the user is not currently signed in
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function logOutEverywhereElse() {
|
||||
if (!$this->isLoggedIn()) {
|
||||
throw new NotLoggedInException();
|
||||
}
|
||||
|
||||
// determine the expiry date of any locally existing remember directive
|
||||
$previousRememberDirectiveExpiry = $this->getRememberDirectiveExpiry();
|
||||
|
||||
// schedule a forced logout in all sessions
|
||||
$this->forceLogoutForUserById($this->getUserId());
|
||||
|
||||
// the following session field may not have been initialized for sessions that had already existed before the introduction of this feature
|
||||
if (!isset($_SESSION[self::SESSION_FIELD_FORCE_LOGOUT])) {
|
||||
$_SESSION[self::SESSION_FIELD_FORCE_LOGOUT] = 0;
|
||||
}
|
||||
|
||||
// ensure that we will simply skip or ignore the next forced logout (which we have just caused) in the current session
|
||||
$_SESSION[self::SESSION_FIELD_FORCE_LOGOUT]++;
|
||||
|
||||
// re-generate the session ID to prevent session fixation attacks (requests a cookie to be written on the client)
|
||||
Session::regenerate(true);
|
||||
|
||||
// if there had been an existing remember directive previously
|
||||
if (isset($previousRememberDirectiveExpiry)) {
|
||||
// restore the directive with the old expiry date but new credentials
|
||||
$this->createRememberDirective(
|
||||
$this->getUserId(),
|
||||
$previousRememberDirectiveExpiry - \time()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs the user out in all sessions
|
||||
*
|
||||
* @throws NotLoggedInException if the user is not currently signed in
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function logOutEverywhere() {
|
||||
if (!$this->isLoggedIn()) {
|
||||
throw new NotLoggedInException();
|
||||
}
|
||||
|
||||
// schedule a forced logout in all sessions
|
||||
$this->forceLogoutForUserById($this->getUserId());
|
||||
// and immediately apply the logout locally
|
||||
$this->logOut();
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys all session data
|
||||
*
|
||||
@@ -375,7 +497,7 @@ final class Auth extends UserManager {
|
||||
|
||||
try {
|
||||
$this->db->insert(
|
||||
$this->dbTablePrefix . 'users_remembered',
|
||||
$this->makeTableNameComponents('users_remembered'),
|
||||
[
|
||||
'user' => $userId,
|
||||
'selector' => $selector,
|
||||
@@ -385,28 +507,14 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
$this->setRememberCookie($selector, $token, $expires);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears an existing directive that keeps the user logged in ("remember me")
|
||||
*
|
||||
* @param int $userId the user ID that shouldn't be kept signed in anymore
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
private function deleteRememberDirective($userId) {
|
||||
try {
|
||||
$this->db->delete(
|
||||
$this->dbTablePrefix . 'users_remembered',
|
||||
[ 'user' => $userId ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
}
|
||||
protected function deleteRememberDirectiveForUserById($userId, $selector = null) {
|
||||
parent::deleteRememberDirectiveForUserById($userId, $selector);
|
||||
|
||||
$this->setRememberCookie(null, null, \time() - 3600);
|
||||
}
|
||||
@@ -455,30 +563,20 @@ final class Auth extends UserManager {
|
||||
}
|
||||
}
|
||||
|
||||
protected function onLoginSuccessful($userId, $email, $username, $status, $roles, $remembered) {
|
||||
protected function onLoginSuccessful($userId, $email, $username, $status, $roles, $forceLogout, $remembered) {
|
||||
// update the timestamp of the user's last login
|
||||
try {
|
||||
$this->db->update(
|
||||
$this->dbTablePrefix . 'users',
|
||||
$this->makeTableNameComponents('users'),
|
||||
[ 'last_login' => \time() ],
|
||||
[ 'id' => $userId ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
parent::onLoginSuccessful($userId, $email, $username, $status, $roles, $remembered);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs the user out and destroys all session data
|
||||
*
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function logOutAndDestroySession() {
|
||||
$this->logOut();
|
||||
$this->destroySession();
|
||||
parent::onLoginSuccessful($userId, $email, $username, $status, $roles, $forceLogout, $remembered);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -509,7 +607,7 @@ final class Auth extends UserManager {
|
||||
*
|
||||
* @param string $selector the selector from the selector/token pair
|
||||
* @param string $token the token from the selector/token pair
|
||||
* @return string the email address that has successfully been verified
|
||||
* @return string[] an array with the old email address (if any) at index zero and the new email address (which has just been verified) at index one
|
||||
* @throws InvalidSelectorTokenPairException if either the selector or the token was not correct
|
||||
* @throws TokenExpiredException if the token has already expired
|
||||
* @throws UserAlreadyExistsException if an attempt has been made to change the email address to a (now) occupied address
|
||||
@@ -523,12 +621,12 @@ final class Auth extends UserManager {
|
||||
|
||||
try {
|
||||
$confirmationData = $this->db->selectRow(
|
||||
'SELECT id, user_id, email, token, expires FROM ' . $this->dbTablePrefix . 'users_confirmations WHERE selector = ?',
|
||||
'SELECT a.id, a.user_id, a.email AS new_email, a.token, a.expires, b.email AS old_email FROM ' . $this->makeTableName('users_confirmations') . ' AS a JOIN ' . $this->makeTableName('users') . ' AS b ON b.id = a.user_id WHERE a.selector = ?',
|
||||
[ $selector ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if (!empty($confirmationData)) {
|
||||
@@ -537,20 +635,20 @@ final class Auth extends UserManager {
|
||||
// invalidate any potential outstanding password reset requests
|
||||
try {
|
||||
$this->db->delete(
|
||||
$this->dbTablePrefix . 'users_resets',
|
||||
$this->makeTableNameComponents('users_resets'),
|
||||
[ 'user' => $confirmationData['user_id'] ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
// mark the email address as verified (and possibly update it to the new address given)
|
||||
try {
|
||||
$this->db->update(
|
||||
$this->dbTablePrefix . 'users',
|
||||
$this->makeTableNameComponents('users'),
|
||||
[
|
||||
'email' => $confirmationData['email'],
|
||||
'email' => $confirmationData['new_email'],
|
||||
'verified' => 1
|
||||
],
|
||||
[ 'id' => $confirmationData['user_id'] ]
|
||||
@@ -560,7 +658,7 @@ final class Auth extends UserManager {
|
||||
throw new UserAlreadyExistsException();
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
// if the user is currently signed in
|
||||
@@ -568,22 +666,31 @@ final class Auth extends UserManager {
|
||||
// if the user has just confirmed an email address for their own account
|
||||
if ($this->getUserId() === $confirmationData['user_id']) {
|
||||
// immediately update the email address in the current session as well
|
||||
$_SESSION[self::SESSION_FIELD_EMAIL] = $confirmationData['email'];
|
||||
$_SESSION[self::SESSION_FIELD_EMAIL] = $confirmationData['new_email'];
|
||||
}
|
||||
}
|
||||
|
||||
// consume the token just being used for confirmation
|
||||
try {
|
||||
$this->db->delete(
|
||||
$this->dbTablePrefix . 'users_confirmations',
|
||||
$this->makeTableNameComponents('users_confirmations'),
|
||||
[ 'id' => $confirmationData['id'] ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
return $confirmationData['email'];
|
||||
// if the email address has not been changed but simply been verified
|
||||
if ($confirmationData['old_email'] === $confirmationData['new_email']) {
|
||||
// the output should not contain any previous email address
|
||||
$confirmationData['old_email'] = null;
|
||||
}
|
||||
|
||||
return [
|
||||
$confirmationData['old_email'],
|
||||
$confirmationData['new_email']
|
||||
];
|
||||
}
|
||||
else {
|
||||
throw new TokenExpiredException();
|
||||
@@ -608,7 +715,7 @@ final class Auth extends UserManager {
|
||||
* @param string $selector the selector from the selector/token pair
|
||||
* @param string $token the token from the selector/token pair
|
||||
* @param int|null $rememberDuration (optional) the duration in seconds to keep the user logged in ("remember me"), e.g. `60 * 60 * 24 * 365.25` for one year
|
||||
* @return string the email address that has successfully been verified
|
||||
* @return string[] an array with the old email address (if any) at index zero and the new email address (which has just been verified) at index one
|
||||
* @throws InvalidSelectorTokenPairException if either the selector or the token was not correct
|
||||
* @throws TokenExpiredException if the token has already expired
|
||||
* @throws UserAlreadyExistsException if an attempt has been made to change the email address to a (now) occupied address
|
||||
@@ -616,18 +723,18 @@ final class Auth extends UserManager {
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function confirmEmailAndSignIn($selector, $token, $rememberDuration = null) {
|
||||
$verifiedEmail = $this->confirmEmail($selector, $token);
|
||||
$emailBeforeAndAfter = $this->confirmEmail($selector, $token);
|
||||
|
||||
if (!$this->isLoggedIn()) {
|
||||
if ($verifiedEmail !== null) {
|
||||
$verifiedEmail = self::validateEmailAddress($verifiedEmail);
|
||||
if ($emailBeforeAndAfter[1] !== null) {
|
||||
$emailBeforeAndAfter[1] = self::validateEmailAddress($emailBeforeAndAfter[1]);
|
||||
|
||||
$userData = $this->getUserDataByEmailAddress(
|
||||
$verifiedEmail,
|
||||
[ 'id', 'email', 'username', 'status', 'roles_mask' ]
|
||||
$emailBeforeAndAfter[1],
|
||||
[ 'id', 'email', 'username', 'status', 'roles_mask', 'force_logout' ]
|
||||
);
|
||||
|
||||
$this->onLoginSuccessful($userData['id'], $userData['email'], $userData['username'], $userData['status'], $userData['roles_mask'], true);
|
||||
$this->onLoginSuccessful($userData['id'], $userData['email'], $userData['username'], $userData['status'], $userData['roles_mask'], $userData['force_logout'], true);
|
||||
|
||||
if ($rememberDuration !== null) {
|
||||
$this->createRememberDirective($userData['id'], $rememberDuration);
|
||||
@@ -635,7 +742,7 @@ final class Auth extends UserManager {
|
||||
}
|
||||
}
|
||||
|
||||
return $verifiedEmail;
|
||||
return $emailBeforeAndAfter;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -668,37 +775,18 @@ final class Auth extends UserManager {
|
||||
public function changePasswordWithoutOldPassword($newPassword) {
|
||||
if ($this->isLoggedIn()) {
|
||||
$newPassword = self::validatePassword($newPassword);
|
||||
$userId = $this->getUserId();
|
||||
$this->updatePassword($userId, $newPassword);
|
||||
$this->deleteRememberDirective($userId);
|
||||
$this->updatePasswordInternal($this->getUserId(), $newPassword);
|
||||
|
||||
try {
|
||||
$this->logOutEverywhereElse();
|
||||
}
|
||||
catch (NotLoggedInException $ignored) {}
|
||||
}
|
||||
else {
|
||||
throw new NotLoggedInException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the given user's password by setting it to the new specified password
|
||||
*
|
||||
* @param int $userId the ID of the user whose password should be updated
|
||||
* @param string $newPassword the new password
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
private function updatePassword($userId, $newPassword) {
|
||||
$newPassword = \password_hash($newPassword, \PASSWORD_DEFAULT);
|
||||
|
||||
try {
|
||||
$this->db->update(
|
||||
$this->dbTablePrefix . 'users',
|
||||
[ 'password' => $newPassword ],
|
||||
[ 'id' => $userId ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to change the email address of the currently signed-in user (which requires confirmation)
|
||||
*
|
||||
@@ -730,12 +818,12 @@ final class Auth extends UserManager {
|
||||
|
||||
try {
|
||||
$existingUsersWithNewEmail = $this->db->selectValue(
|
||||
'SELECT COUNT(*) FROM ' . $this->dbTablePrefix . 'users WHERE email = ?',
|
||||
'SELECT COUNT(*) FROM ' . $this->makeTableName('users') . ' WHERE email = ?',
|
||||
[ $newEmail ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if ((int) $existingUsersWithNewEmail !== 0) {
|
||||
@@ -744,12 +832,12 @@ final class Auth extends UserManager {
|
||||
|
||||
try {
|
||||
$verified = $this->db->selectValue(
|
||||
'SELECT verified FROM ' . $this->dbTablePrefix . 'users WHERE id = ?',
|
||||
'SELECT verified FROM ' . $this->makeTableName('users') . ' WHERE id = ?',
|
||||
[ $this->getUserId() ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
// ensure that at least the current (old) email address has been verified before proceeding
|
||||
@@ -832,12 +920,12 @@ final class Auth extends UserManager {
|
||||
private function resendConfirmationForColumnValue($columnName, $columnValue, callable $callback) {
|
||||
try {
|
||||
$latestAttempt = $this->db->selectRow(
|
||||
'SELECT user_id, email FROM ' . $this->dbTablePrefix . 'users_confirmations WHERE ' . $columnName . ' = ? ORDER BY id DESC LIMIT 1 OFFSET 0',
|
||||
'SELECT user_id, email FROM ' . $this->makeTableName('users_confirmations') . ' WHERE ' . $columnName . ' = ? ORDER BY id DESC LIMIT 1 OFFSET 0',
|
||||
[ $columnValue ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if ($latestAttempt === null) {
|
||||
@@ -874,6 +962,11 @@ final class Auth extends UserManager {
|
||||
* @throws ResetDisabledException if the user has explicitly disabled password resets for their account
|
||||
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*
|
||||
* @see canResetPasswordOrThrow
|
||||
* @see canResetPassword
|
||||
* @see resetPassword
|
||||
* @see resetPasswordAndSignIn
|
||||
*/
|
||||
public function forgotPassword($email, callable $callback, $requestExpiresAfter = null, $maxOpenRequests = null) {
|
||||
$email = self::validateEmailAddress($email);
|
||||
@@ -911,7 +1004,7 @@ final class Auth extends UserManager {
|
||||
throw new ResetDisabledException();
|
||||
}
|
||||
|
||||
$openRequests = (int) $this->getOpenPasswordResetRequests($userData['id']);
|
||||
$openRequests = $this->throttling ? (int) $this->getOpenPasswordResetRequests($userData['id']) : 0;
|
||||
|
||||
if ($openRequests < $maxOpenRequests) {
|
||||
$this->throttle([ 'requestPasswordReset', $this->getIpAddress() ], 4, (60 * 60 * 24 * 7), 2);
|
||||
@@ -945,7 +1038,7 @@ final class Auth extends UserManager {
|
||||
$this->throttle([ 'enumerateUsers', $this->getIpAddress() ], 1, (60 * 60), 75);
|
||||
$this->throttle([ 'attemptToLogin', $this->getIpAddress() ], 4, (60 * 60), 5, true);
|
||||
|
||||
$columnsToFetch = [ 'id', 'email', 'password', 'verified', 'username', 'status', 'roles_mask' ];
|
||||
$columnsToFetch = [ 'id', 'email', 'password', 'verified', 'username', 'status', 'roles_mask', 'force_logout' ];
|
||||
|
||||
if ($email !== null) {
|
||||
$email = self::validateEmailAddress($email);
|
||||
@@ -977,12 +1070,12 @@ final class Auth extends UserManager {
|
||||
// if the password needs to be re-hashed to keep up with improving password cracking techniques
|
||||
if (\password_needs_rehash($userData['password'], \PASSWORD_DEFAULT)) {
|
||||
// create a new hash from the password and update it in the database
|
||||
$this->updatePassword($userData['id'], $password);
|
||||
$this->updatePasswordInternal($userData['id'], $password);
|
||||
}
|
||||
|
||||
if ((int) $userData['verified'] === 1) {
|
||||
if (!isset($onBeforeSuccess) || (\is_callable($onBeforeSuccess) && $onBeforeSuccess($userData['id']) === true)) {
|
||||
$this->onLoginSuccessful($userData['id'], $userData['email'], $userData['username'], $userData['status'], $userData['roles_mask'], false);
|
||||
$this->onLoginSuccessful($userData['id'], $userData['email'], $userData['username'], $userData['status'], $userData['roles_mask'], $userData['force_logout'], false);
|
||||
|
||||
// continue to support the old parameter format
|
||||
if ($rememberDuration === true) {
|
||||
@@ -1045,12 +1138,12 @@ final class Auth extends UserManager {
|
||||
try {
|
||||
$projection = \implode(', ', $requestedColumns);
|
||||
$userData = $this->db->selectRow(
|
||||
'SELECT ' . $projection . ' FROM ' . $this->dbTablePrefix . 'users WHERE email = ?',
|
||||
'SELECT ' . $projection . ' FROM ' . $this->makeTableName('users') . ' WHERE email = ?',
|
||||
[ $email ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if (!empty($userData)) {
|
||||
@@ -1071,7 +1164,7 @@ final class Auth extends UserManager {
|
||||
private function getOpenPasswordResetRequests($userId) {
|
||||
try {
|
||||
$requests = $this->db->selectValue(
|
||||
'SELECT COUNT(*) FROM ' . $this->dbTablePrefix . 'users_resets WHERE user = ? AND expires > ?',
|
||||
'SELECT COUNT(*) FROM ' . $this->makeTableName('users_resets') . ' WHERE user = ? AND expires > ?',
|
||||
[
|
||||
$userId,
|
||||
\time()
|
||||
@@ -1086,7 +1179,7 @@ final class Auth extends UserManager {
|
||||
}
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1114,7 +1207,7 @@ final class Auth extends UserManager {
|
||||
|
||||
try {
|
||||
$this->db->insert(
|
||||
$this->dbTablePrefix . 'users_resets',
|
||||
$this->makeTableNameComponents('users_resets'),
|
||||
[
|
||||
'user' => $userId,
|
||||
'selector' => $selector,
|
||||
@@ -1124,7 +1217,7 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if (\is_callable($callback)) {
|
||||
@@ -1138,17 +1231,23 @@ final class Auth extends UserManager {
|
||||
/**
|
||||
* Resets the password for a particular account by supplying the correct selector/token pair
|
||||
*
|
||||
* The selector/token pair must have been generated previously by calling `Auth#forgotPassword(...)`
|
||||
* The selector/token pair must have been generated previously by calling {@see forgotPassword}
|
||||
*
|
||||
* @param string $selector the selector from the selector/token pair
|
||||
* @param string $token the token from the selector/token pair
|
||||
* @param string $newPassword the new password to set for the account
|
||||
* @return string[] an array with the user's ID at index `id` and the user's email address at index `email`
|
||||
* @throws InvalidSelectorTokenPairException if either the selector or the token was not correct
|
||||
* @throws TokenExpiredException if the token has already expired
|
||||
* @throws ResetDisabledException if the user has explicitly disabled password resets for their account
|
||||
* @throws InvalidPasswordException if the new password was invalid
|
||||
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*
|
||||
* @see forgotPassword
|
||||
* @see canResetPasswordOrThrow
|
||||
* @see canResetPassword
|
||||
* @see resetPasswordAndSignIn
|
||||
*/
|
||||
public function resetPassword($selector, $token, $newPassword) {
|
||||
$this->throttle([ 'resetPassword', $this->getIpAddress() ], 5, (60 * 60), 10);
|
||||
@@ -1157,12 +1256,12 @@ final class Auth extends UserManager {
|
||||
|
||||
try {
|
||||
$resetData = $this->db->selectRow(
|
||||
'SELECT a.id, a.user, a.token, a.expires, b.resettable FROM ' . $this->dbTablePrefix . 'users_resets AS a JOIN ' . $this->dbTablePrefix . 'users AS b ON b.id = a.user WHERE a.selector = ?',
|
||||
'SELECT a.id, a.user, a.token, a.expires, b.email, b.resettable FROM ' . $this->makeTableName('users_resets') . ' AS a JOIN ' . $this->makeTableName('users') . ' AS b ON b.id = a.user WHERE a.selector = ?',
|
||||
[ $selector ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if (!empty($resetData)) {
|
||||
@@ -1170,22 +1269,23 @@ final class Auth extends UserManager {
|
||||
if (\password_verify($token, $resetData['token'])) {
|
||||
if ($resetData['expires'] >= \time()) {
|
||||
$newPassword = self::validatePassword($newPassword);
|
||||
|
||||
// update the password in the database
|
||||
$this->updatePassword($resetData['user'], $newPassword);
|
||||
|
||||
// delete any remaining remember directives
|
||||
$this->deleteRememberDirective($resetData['user']);
|
||||
$this->updatePasswordInternal($resetData['user'], $newPassword);
|
||||
$this->forceLogoutForUserById($resetData['user']);
|
||||
|
||||
try {
|
||||
$this->db->delete(
|
||||
$this->dbTablePrefix . 'users_resets',
|
||||
$this->makeTableNameComponents('users_resets'),
|
||||
[ 'id' => $resetData['id'] ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => $resetData['user'],
|
||||
'email' => $resetData['email']
|
||||
];
|
||||
}
|
||||
else {
|
||||
throw new TokenExpiredException();
|
||||
@@ -1204,30 +1304,111 @@ final class Auth extends UserManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the password for a particular account by supplying the correct selector/token pair
|
||||
*
|
||||
* The selector/token pair must have been generated previously by calling {@see forgotPassword}
|
||||
*
|
||||
* The user will be automatically signed in if this operation is successful
|
||||
*
|
||||
* @param string $selector the selector from the selector/token pair
|
||||
* @param string $token the token from the selector/token pair
|
||||
* @param string $newPassword the new password to set for the account
|
||||
* @param int|null $rememberDuration (optional) the duration in seconds to keep the user logged in ("remember me"), e.g. `60 * 60 * 24 * 365.25` for one year
|
||||
* @return string[] an array with the user's ID at index `id` and the user's email address at index `email`
|
||||
* @throws InvalidSelectorTokenPairException if either the selector or the token was not correct
|
||||
* @throws TokenExpiredException if the token has already expired
|
||||
* @throws ResetDisabledException if the user has explicitly disabled password resets for their account
|
||||
* @throws InvalidPasswordException if the new password was invalid
|
||||
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*
|
||||
* @see forgotPassword
|
||||
* @see canResetPasswordOrThrow
|
||||
* @see canResetPassword
|
||||
* @see resetPassword
|
||||
*/
|
||||
public function resetPasswordAndSignIn($selector, $token, $newPassword, $rememberDuration = null) {
|
||||
$idAndEmail = $this->resetPassword($selector, $token, $newPassword);
|
||||
|
||||
if (!$this->isLoggedIn()) {
|
||||
$idAndEmail['email'] = self::validateEmailAddress($idAndEmail['email']);
|
||||
|
||||
$userData = $this->getUserDataByEmailAddress(
|
||||
$idAndEmail['email'],
|
||||
[ 'username', 'status', 'roles_mask', 'force_logout' ]
|
||||
);
|
||||
|
||||
$this->onLoginSuccessful($idAndEmail['id'], $idAndEmail['email'], $userData['username'], $userData['status'], $userData['roles_mask'], $userData['force_logout'], true);
|
||||
|
||||
if ($rememberDuration !== null) {
|
||||
$this->createRememberDirective($idAndEmail['id'], $rememberDuration);
|
||||
}
|
||||
}
|
||||
|
||||
return $idAndEmail;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the supplied selector/token pair can be used to reset a password
|
||||
*
|
||||
* The selector/token pair must have been generated previously by calling `Auth#forgotPassword(...)`
|
||||
* The password can be reset using the supplied information if this method does *not* throw any exception
|
||||
*
|
||||
* The selector/token pair must have been generated previously by calling {@see forgotPassword}
|
||||
*
|
||||
* @param string $selector the selector from the selector/token pair
|
||||
* @param string $token the token from the selector/token pair
|
||||
* @throws InvalidSelectorTokenPairException if either the selector or the token was not correct
|
||||
* @throws TokenExpiredException if the token has already expired
|
||||
* @throws ResetDisabledException if the user has explicitly disabled password resets for their account
|
||||
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*
|
||||
* @see forgotPassword
|
||||
* @see canResetPassword
|
||||
* @see resetPassword
|
||||
* @see resetPasswordAndSignIn
|
||||
*/
|
||||
public function canResetPasswordOrThrow($selector, $token) {
|
||||
try {
|
||||
// pass an invalid password intentionally to force an expected error
|
||||
$this->resetPassword($selector, $token, null);
|
||||
|
||||
// we should already be in one of the `catch` blocks now so this is not expected
|
||||
throw new AuthError();
|
||||
}
|
||||
// if the password is the only thing that's invalid
|
||||
catch (InvalidPasswordException $ignored) {
|
||||
// the password can be reset
|
||||
}
|
||||
// if some other things failed (as well)
|
||||
catch (AuthException $e) {
|
||||
// re-throw the exception
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the supplied selector/token pair can be used to reset a password
|
||||
*
|
||||
* The selector/token pair must have been generated previously by calling {@see forgotPassword}
|
||||
*
|
||||
* @param string $selector the selector from the selector/token pair
|
||||
* @param string $token the token from the selector/token pair
|
||||
* @return bool whether the password can be reset using the supplied information
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*
|
||||
* @see forgotPassword
|
||||
* @see canResetPasswordOrThrow
|
||||
* @see resetPassword
|
||||
* @see resetPasswordAndSignIn
|
||||
*/
|
||||
public function canResetPassword($selector, $token) {
|
||||
try {
|
||||
// pass an invalid password intentionally to force an expected error
|
||||
$this->resetPassword($selector, $token, null);
|
||||
$this->canResetPasswordOrThrow($selector, $token);
|
||||
|
||||
// we should already be in the `catch` block now so this is not expected
|
||||
throw new AuthError();
|
||||
}
|
||||
// if the password is the only thing that's invalid
|
||||
catch (InvalidPasswordException $e) {
|
||||
// the password can be reset
|
||||
return true;
|
||||
}
|
||||
// if some other things failed (as well)
|
||||
catch (AuthException $e) {
|
||||
return false;
|
||||
}
|
||||
@@ -1246,7 +1427,7 @@ final class Auth extends UserManager {
|
||||
if ($this->isLoggedIn()) {
|
||||
try {
|
||||
$this->db->update(
|
||||
$this->dbTablePrefix . 'users',
|
||||
$this->makeTableNameComponents('users'),
|
||||
[
|
||||
'resettable' => $enabled ? 1 : 0
|
||||
],
|
||||
@@ -1256,7 +1437,7 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -1275,14 +1456,14 @@ final class Auth extends UserManager {
|
||||
if ($this->isLoggedIn()) {
|
||||
try {
|
||||
$enabled = $this->db->selectValue(
|
||||
'SELECT resettable FROM ' . $this->dbTablePrefix . 'users WHERE id = ?',
|
||||
'SELECT resettable FROM ' . $this->makeTableName('users') . ' WHERE id = ?',
|
||||
[ $this->getUserId() ]
|
||||
);
|
||||
|
||||
return (int) $enabled === 1;
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -1323,7 +1504,7 @@ final class Auth extends UserManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Shorthand/alias for `getUserId()`
|
||||
* Shorthand/alias for {@see getUserId}
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
@@ -1454,9 +1635,13 @@ final class Auth extends UserManager {
|
||||
* @see Role
|
||||
*/
|
||||
public function hasRole($role) {
|
||||
$role = (int) $role;
|
||||
if (empty($role) || !\is_numeric($role)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_ROLES])) {
|
||||
$role = (int) $role;
|
||||
|
||||
return (((int) $_SESSION[self::SESSION_FIELD_ROLES]) & $role) === $role;
|
||||
}
|
||||
else {
|
||||
@@ -1500,6 +1685,19 @@ final class Auth extends UserManager {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of the user's roles, mapping the numerical values to their descriptive names
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getRoles() {
|
||||
return \array_filter(
|
||||
Role::getMap(),
|
||||
[ $this, 'hasRole' ],
|
||||
\ARRAY_FILTER_USE_KEY
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the currently signed-in user has been remembered by a long-lived cookie
|
||||
*
|
||||
@@ -1565,12 +1763,12 @@ final class Auth extends UserManager {
|
||||
|
||||
try {
|
||||
$bucket = $this->db->selectRow(
|
||||
'SELECT tokens, replenished_at FROM ' . $this->dbTablePrefix . 'users_throttling WHERE bucket = ?',
|
||||
'SELECT tokens, replenished_at FROM ' . $this->makeTableName('users_throttling') . ' WHERE bucket = ?',
|
||||
[ $key ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if ($bucket === null) {
|
||||
@@ -1602,13 +1800,13 @@ final class Auth extends UserManager {
|
||||
// merge the updated bucket into the database
|
||||
try {
|
||||
$affected = $this->db->update(
|
||||
$this->dbTablePrefix . 'users_throttling',
|
||||
$this->makeTableNameComponents('users_throttling'),
|
||||
$bucket,
|
||||
[ 'bucket' => $key ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if ($affected === 0) {
|
||||
@@ -1616,13 +1814,13 @@ final class Auth extends UserManager {
|
||||
|
||||
try {
|
||||
$this->db->insert(
|
||||
$this->dbTablePrefix . 'users_throttling',
|
||||
$this->makeTableNameComponents('users_throttling'),
|
||||
$bucket
|
||||
);
|
||||
}
|
||||
catch (IntegrityConstraintViolationException $ignored) {}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1646,7 +1844,7 @@ final class Auth extends UserManager {
|
||||
* @return Administration
|
||||
*/
|
||||
public function admin() {
|
||||
return new Administration($this->db, $this->dbTablePrefix);
|
||||
return new Administration($this->db, $this->dbTablePrefix, $this->dbSchema);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1711,4 +1909,53 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the selector of a potential locally existing remember directive
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
private function getRememberDirectiveSelector() {
|
||||
if (isset($_COOKIE[$this->rememberCookieName])) {
|
||||
$selectorAndToken = \explode(self::COOKIE_CONTENT_SEPARATOR, $_COOKIE[$this->rememberCookieName], 2);
|
||||
|
||||
return $selectorAndToken[0];
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the expiry date of a potential locally existing remember directive
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
private function getRememberDirectiveExpiry() {
|
||||
// if the user is currently signed in
|
||||
if ($this->isLoggedIn()) {
|
||||
// determine the selector of any currently existing remember directive
|
||||
$existingSelector = $this->getRememberDirectiveSelector();
|
||||
|
||||
// if there is currently a remember directive whose selector we have just retrieved
|
||||
if (isset($existingSelector)) {
|
||||
// fetch the expiry date for the given selector
|
||||
$existingExpiry = $this->db->selectValue(
|
||||
'SELECT expires FROM ' . $this->makeTableName('users_remembered') . ' WHERE selector = ? AND user = ?',
|
||||
[
|
||||
$existingSelector,
|
||||
$this->getUserId()
|
||||
]
|
||||
);
|
||||
|
||||
// if an expiration date has been found
|
||||
if (isset($existingExpiry)) {
|
||||
// return the date
|
||||
return (int) $existingExpiry;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -44,8 +44,6 @@ class AuthError extends \Exception {}
|
||||
|
||||
class DatabaseError extends AuthError {}
|
||||
|
||||
class DatabaseDriverError extends DatabaseError {}
|
||||
|
||||
class MissingCallbackError extends AuthError {}
|
||||
|
||||
class HeadersAlreadySentError extends AuthError {}
|
||||
|
49
src/Role.php
49
src/Role.php
@@ -32,14 +32,47 @@ final class Role {
|
||||
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;
|
||||
// const XYZ = 4194304;
|
||||
// const XYZ = 8388608;
|
||||
// const XYZ = 16777216;
|
||||
// const XYZ = 33554432;
|
||||
// const XYZ = 67108864;
|
||||
// const XYZ = 134217728;
|
||||
// const XYZ = 268435456;
|
||||
// const XYZ = 536870912;
|
||||
|
||||
/**
|
||||
* Returns an array mapping the numerical role values to their descriptive names
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function getMap() {
|
||||
$reflectionClass = new \ReflectionClass(static::class);
|
||||
|
||||
return \array_flip($reflectionClass->getConstants());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the descriptive role names
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function getNames() {
|
||||
$reflectionClass = new \ReflectionClass(static::class);
|
||||
|
||||
return \array_keys($reflectionClass->getConstants());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the numerical role values
|
||||
*
|
||||
* @return int[]
|
||||
*/
|
||||
public static function getValues() {
|
||||
$reflectionClass = new \ReflectionClass(static::class);
|
||||
|
||||
return \array_values($reflectionClass->getConstants());
|
||||
}
|
||||
|
||||
private function __construct() {}
|
||||
|
||||
|
@@ -38,9 +38,15 @@ abstract class UserManager {
|
||||
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';
|
||||
/** @var string session field for the UNIX timestamp in seconds of the session data's last resynchronization with its authoritative source in the database */
|
||||
const SESSION_FIELD_LAST_RESYNC = 'auth_last_resync';
|
||||
/** @var string session field for the counter that keeps track of forced logouts that need to be performed in the current session */
|
||||
const SESSION_FIELD_FORCE_LOGOUT = 'auth_force_logout';
|
||||
|
||||
/** @var PdoDatabase the database connection to operate on */
|
||||
protected $db;
|
||||
/** @var string|null the schema name for all database tables used by this component */
|
||||
protected $dbSchema;
|
||||
/** @var string the prefix for the names of all database tables used by this component */
|
||||
protected $dbTablePrefix;
|
||||
|
||||
@@ -66,8 +72,9 @@ abstract class UserManager {
|
||||
/**
|
||||
* @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
|
||||
* @param string|null $dbSchema (optional) the schema name for all database tables used by this component
|
||||
*/
|
||||
protected function __construct($databaseConnection, $dbTablePrefix = null) {
|
||||
protected function __construct($databaseConnection, $dbTablePrefix = null, $dbSchema = null) {
|
||||
if ($databaseConnection instanceof PdoDatabase) {
|
||||
$this->db = $databaseConnection;
|
||||
}
|
||||
@@ -83,6 +90,7 @@ abstract class UserManager {
|
||||
throw new \InvalidArgumentException('The database connection must be an instance of either `PdoDatabase`, `PdoDsn` or `PDO`');
|
||||
}
|
||||
|
||||
$this->dbSchema = $dbSchema !== null ? (string) $dbSchema : null;
|
||||
$this->dbTablePrefix = (string) $dbTablePrefix;
|
||||
}
|
||||
|
||||
@@ -136,7 +144,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 ' . $this->dbTablePrefix . 'users WHERE username = ?',
|
||||
'SELECT COUNT(*) FROM ' . $this->makeTableName('users') . ' WHERE username = ?',
|
||||
[ $username ]
|
||||
);
|
||||
|
||||
@@ -153,7 +161,7 @@ abstract class UserManager {
|
||||
|
||||
try {
|
||||
$this->db->insert(
|
||||
$this->dbTablePrefix . 'users',
|
||||
$this->makeTableNameComponents('users'),
|
||||
[
|
||||
'email' => $email,
|
||||
'password' => $password,
|
||||
@@ -168,7 +176,7 @@ abstract class UserManager {
|
||||
throw new UserAlreadyExistsException();
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
$newUserId = (int) $this->db->getLastInsertId();
|
||||
@@ -180,6 +188,33 @@ abstract class UserManager {
|
||||
return $newUserId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the given user's password by setting it to the new specified password
|
||||
*
|
||||
* @param int $userId the ID of the user whose password should be updated
|
||||
* @param string $newPassword the new password
|
||||
* @throws UnknownIdException if no user with the specified ID has been found
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
protected function updatePasswordInternal($userId, $newPassword) {
|
||||
$newPassword = \password_hash($newPassword, \PASSWORD_DEFAULT);
|
||||
|
||||
try {
|
||||
$affected = $this->db->update(
|
||||
$this->makeTableNameComponents('users'),
|
||||
[ 'password' => $newPassword ],
|
||||
[ 'id' => $userId ]
|
||||
);
|
||||
|
||||
if ($affected === 0) {
|
||||
throw new UnknownIdException();
|
||||
}
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when a user has successfully logged in
|
||||
*
|
||||
@@ -190,10 +225,11 @@ abstract class UserManager {
|
||||
* @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 int $forceLogout the counter that keeps track of forced logouts that need to be performed in the current session
|
||||
* @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) {
|
||||
protected function onLoginSuccessful($userId, $email, $username, $status, $roles, $forceLogout, $remembered) {
|
||||
// re-generate the session ID to prevent session fixation attacks (requests a cookie to be written on the client)
|
||||
Session::regenerate(true);
|
||||
|
||||
@@ -204,7 +240,9 @@ abstract class UserManager {
|
||||
$_SESSION[self::SESSION_FIELD_USERNAME] = $username;
|
||||
$_SESSION[self::SESSION_FIELD_STATUS] = (int) $status;
|
||||
$_SESSION[self::SESSION_FIELD_ROLES] = (int) $roles;
|
||||
$_SESSION[self::SESSION_FIELD_FORCE_LOGOUT] = (int) $forceLogout;
|
||||
$_SESSION[self::SESSION_FIELD_REMEMBERED] = $remembered;
|
||||
$_SESSION[self::SESSION_FIELD_LAST_RESYNC] = \time();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -224,12 +262,12 @@ abstract class UserManager {
|
||||
$projection = \implode(', ', $requestedColumns);
|
||||
|
||||
$users = $this->db->select(
|
||||
'SELECT ' . $projection . ' FROM ' . $this->dbTablePrefix . 'users WHERE username = ? LIMIT 2 OFFSET 0',
|
||||
'SELECT ' . $projection . ' FROM ' . $this->makeTableName('users') . ' WHERE username = ? LIMIT 2 OFFSET 0',
|
||||
[ $username ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if (empty($users)) {
|
||||
@@ -311,7 +349,7 @@ abstract class UserManager {
|
||||
|
||||
try {
|
||||
$this->db->insert(
|
||||
$this->dbTablePrefix . 'users_confirmations',
|
||||
$this->makeTableNameComponents('users_confirmations'),
|
||||
[
|
||||
'user_id' => (int) $userId,
|
||||
'email' => $email,
|
||||
@@ -322,7 +360,7 @@ abstract class UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if (\is_callable($callback)) {
|
||||
@@ -333,4 +371,86 @@ abstract class UserManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears an existing directive that keeps the user logged in ("remember me")
|
||||
*
|
||||
* @param int $userId the ID of the user who shouldn't be kept signed in anymore
|
||||
* @param string $selector (optional) the selector which the deletion should be restricted to
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
protected function deleteRememberDirectiveForUserById($userId, $selector = null) {
|
||||
$whereMappings = [];
|
||||
|
||||
if (isset($selector)) {
|
||||
$whereMappings['selector'] = (string) $selector;
|
||||
}
|
||||
|
||||
$whereMappings['user'] = (int) $userId;
|
||||
|
||||
try {
|
||||
$this->db->delete(
|
||||
$this->makeTableNameComponents('users_remembered'),
|
||||
$whereMappings
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Triggers a forced logout in all sessions that belong to the specified user
|
||||
*
|
||||
* @param int $userId the ID of the user to sign out
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
protected function forceLogoutForUserById($userId) {
|
||||
$this->deleteRememberDirectiveForUserById($userId);
|
||||
$this->db->exec(
|
||||
'UPDATE ' . $this->makeTableName('users') . ' SET force_logout = force_logout + 1 WHERE id = ?',
|
||||
[ $userId ]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a (qualified) full table name from an optional qualifier, an optional prefix, and the table name itself
|
||||
*
|
||||
* The optional qualifier may be a database name or a schema name, for example
|
||||
*
|
||||
* @param string $name the name of the table
|
||||
* @return string[] the components of the (qualified) full name of the table
|
||||
*/
|
||||
protected function makeTableNameComponents($name) {
|
||||
$components = [];
|
||||
|
||||
if (!empty($this->dbSchema)) {
|
||||
$components[] = $this->dbSchema;
|
||||
}
|
||||
|
||||
if (!empty($name)) {
|
||||
if (!empty($this->dbTablePrefix)) {
|
||||
$components[] = $this->dbTablePrefix . $name;
|
||||
}
|
||||
else {
|
||||
$components[] = $name;
|
||||
}
|
||||
}
|
||||
|
||||
return $components;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a (qualified) full table name from an optional qualifier, an optional prefix, and the table name itself
|
||||
*
|
||||
* The optional qualifier may be a database name or a schema name, for example
|
||||
*
|
||||
* @param string $name the name of the table
|
||||
* @return string the (qualified) full name of the table
|
||||
*/
|
||||
protected function makeTableName($name) {
|
||||
$components = $this->makeTableNameComponents($name);
|
||||
|
||||
return \implode('.', $components);
|
||||
}
|
||||
|
||||
}
|
||||
|
181
tests/index.php
181
tests/index.php
@@ -29,6 +29,8 @@ require __DIR__.'/../vendor/autoload.php';
|
||||
|
||||
$db = new \PDO('mysql:dbname=php_auth;host=127.0.0.1;charset=utf8mb4', 'root', 'monkey');
|
||||
// or
|
||||
// $db = new \PDO('pgsql:dbname=php_auth;host=127.0.0.1;port=5432', 'postgres', 'monkey');
|
||||
// or
|
||||
// $db = new \PDO('sqlite:../Databases/php_auth.sqlite');
|
||||
|
||||
$auth = new \Delight\Auth\Auth($db);
|
||||
@@ -149,13 +151,12 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
// do not keep logged in after session ends
|
||||
$rememberDuration = null;
|
||||
}
|
||||
$auth->confirmEmailAndSignIn($_POST['selector'], $_POST['token'], $rememberDuration);
|
||||
|
||||
return $auth->confirmEmailAndSignIn($_POST['selector'], $_POST['token'], $rememberDuration);
|
||||
}
|
||||
else {
|
||||
$auth->confirmEmail($_POST['selector'], $_POST['token']);
|
||||
return $auth->confirmEmail($_POST['selector'], $_POST['token']);
|
||||
}
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
|
||||
return 'invalid token';
|
||||
@@ -245,7 +246,7 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
return 'email address not verified';
|
||||
}
|
||||
catch (\Delight\Auth\ResetDisabledException $e) {
|
||||
return 'password reset disabled';
|
||||
return 'password reset is disabled';
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
return 'too many requests';
|
||||
@@ -253,9 +254,21 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
}
|
||||
else if ($_POST['action'] === 'resetPassword') {
|
||||
try {
|
||||
$auth->resetPassword($_POST['selector'], $_POST['token'], $_POST['password']);
|
||||
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;
|
||||
}
|
||||
|
||||
return 'ok';
|
||||
return $auth->resetPasswordAndSignIn($_POST['selector'], $_POST['token'], $_POST['password'], $rememberDuration);
|
||||
}
|
||||
else {
|
||||
return $auth->resetPassword($_POST['selector'], $_POST['token'], $_POST['password']);
|
||||
}
|
||||
}
|
||||
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
|
||||
return 'invalid token';
|
||||
@@ -264,7 +277,7 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
return 'token expired';
|
||||
}
|
||||
catch (\Delight\Auth\ResetDisabledException $e) {
|
||||
return 'password reset disabled';
|
||||
return 'password reset is disabled';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
return 'invalid password';
|
||||
@@ -273,6 +286,25 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
return 'too many requests';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'canResetPassword') {
|
||||
try {
|
||||
$auth->canResetPasswordOrThrow($_POST['selector'], $_POST['token']);
|
||||
|
||||
return 'yes';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
|
||||
return 'invalid token';
|
||||
}
|
||||
catch (\Delight\Auth\TokenExpiredException $e) {
|
||||
return 'token expired';
|
||||
}
|
||||
catch (\Delight\Auth\ResetDisabledException $e) {
|
||||
return 'password reset is disabled';
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
return 'too many requests';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'reconfirmPassword') {
|
||||
try {
|
||||
return $auth->reconfirmPassword($_POST['password']) ? 'correct' : 'wrong';
|
||||
@@ -362,8 +394,28 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
else if ($_POST['action'] === 'logOutAndDestroySession') {
|
||||
$auth->logOutAndDestroySession();
|
||||
else if ($_POST['action'] === 'logOutEverywhereElse') {
|
||||
try {
|
||||
$auth->logOutEverywhereElse();
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
return 'not logged in';
|
||||
}
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
else if ($_POST['action'] === 'logOutEverywhere') {
|
||||
try {
|
||||
$auth->logOutEverywhere();
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
return 'not logged in';
|
||||
}
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
else if ($_POST['action'] === 'destroySession') {
|
||||
$auth->destroySession();
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
@@ -523,6 +575,19 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
return 'ID required';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'admin.getRoles') {
|
||||
if (isset($_POST['id'])) {
|
||||
try {
|
||||
return $auth->admin()->getRolesForUserById($_POST['id']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
return 'unknown ID';
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'ID required';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'admin.logInAsUserById') {
|
||||
if (isset($_POST['id'])) {
|
||||
try {
|
||||
@@ -580,6 +645,43 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
return 'Username required';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'admin.changePasswordForUser') {
|
||||
if (isset($_POST['newPassword'])) {
|
||||
if (isset($_POST['id'])) {
|
||||
try {
|
||||
$auth->admin()->changePasswordForUserById($_POST['id'], $_POST['newPassword']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
return 'unknown ID';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
return 'invalid password';
|
||||
}
|
||||
}
|
||||
elseif (isset($_POST['username'])) {
|
||||
try {
|
||||
$auth->admin()->changePasswordForUserByUsername($_POST['username'], $_POST['newPassword']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
return 'unknown username';
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
return 'ambiguous username';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
return 'invalid password';
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'either ID or username required';
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'new password required';
|
||||
}
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
else {
|
||||
throw new Exception('Unexpected action: ' . $_POST['action']);
|
||||
}
|
||||
@@ -631,6 +733,9 @@ function showDebugData(\Delight\Auth\Auth $auth, $result) {
|
||||
echo 'Roles (developer *and* manager)' . "\t\t";
|
||||
\var_dump($auth->hasAllRoles(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER));
|
||||
|
||||
echo 'Roles' . "\t\t\t\t\t";
|
||||
echo \json_encode($auth->getRoles()) . "\n";
|
||||
|
||||
echo "\n";
|
||||
|
||||
echo '$auth->isRemembered()' . "\t\t\t";
|
||||
@@ -734,9 +839,16 @@ function showAuthenticatedUserForm(\Delight\Auth\Auth $auth) {
|
||||
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 '<input type="hidden" name="action" value="logOutEverywhereElse" />';
|
||||
echo '<button type="submit">Log out everywhere else</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="logOutEverywhere" />';
|
||||
echo '<button type="submit">Log out everywhere</button>';
|
||||
echo '</form>';
|
||||
|
||||
\showDestroySessionForm();
|
||||
}
|
||||
|
||||
function showGuestUserForm() {
|
||||
@@ -793,9 +905,23 @@ function showGuestUserForm() {
|
||||
echo '<input type="text" name="selector" placeholder="Selector" /> ';
|
||||
echo '<input type="text" name="token" placeholder="Token" /> ';
|
||||
echo '<input type="text" name="password" placeholder="New password" /> ';
|
||||
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">Reset password</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="canResetPassword" />';
|
||||
echo '<input type="text" name="selector" placeholder="Selector" /> ';
|
||||
echo '<input type="text" name="token" placeholder="Token" /> ';
|
||||
echo '<button type="submit">Can reset password?</button>';
|
||||
echo '</form>';
|
||||
|
||||
\showDestroySessionForm();
|
||||
|
||||
echo '<h1>Administration</h1>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
@@ -877,6 +1003,12 @@ function showGuestUserForm() {
|
||||
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.getRoles" />';
|
||||
echo '<input type="text" name="id" placeholder="ID" /> ';
|
||||
echo '<button type="submit">Get user\'s roles</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" /> ';
|
||||
@@ -894,6 +1026,20 @@ function showGuestUserForm() {
|
||||
echo '<input type="text" name="username" placeholder="Username" /> ';
|
||||
echo '<button type="submit">Log in as user by username</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.changePasswordForUser" />';
|
||||
echo '<input type="text" name="id" placeholder="ID" /> ';
|
||||
echo '<input type="text" name="newPassword" placeholder="New password" /> ';
|
||||
echo '<button type="submit">Change password for user by ID</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.changePasswordForUser" />';
|
||||
echo '<input type="text" name="username" placeholder="Username" /> ';
|
||||
echo '<input type="text" name="newPassword" placeholder="New password" /> ';
|
||||
echo '<button type="submit">Change password for user by username</button>';
|
||||
echo '</form>';
|
||||
}
|
||||
|
||||
function showConfirmEmailForm() {
|
||||
@@ -922,12 +1068,17 @@ function showConfirmEmailForm() {
|
||||
echo '</form>';
|
||||
}
|
||||
|
||||
function createRolesOptions() {
|
||||
$roleReflection = new ReflectionClass(\Delight\Auth\Role::class);
|
||||
function showDestroySessionForm() {
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="destroySession" />';
|
||||
echo '<button type="submit">Destroy session</button>';
|
||||
echo '</form>';
|
||||
}
|
||||
|
||||
function createRolesOptions() {
|
||||
$out = '';
|
||||
|
||||
foreach ($roleReflection->getConstants() as $roleName => $roleValue) {
|
||||
foreach (\Delight\Auth\Role::getMap() as $roleValue => $roleName) {
|
||||
$out .= '<option value="' . $roleValue . '">' . $roleName . '</option>';
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user