mirror of
https://github.com/delight-im/PHP-Auth.git
synced 2025-08-07 16:46:29 +02:00
Compare commits
45 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
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 | ||
|
7bcf201972 | ||
|
09247e7203 | ||
|
ab1c54fae2 | ||
|
23acb66cc7 | ||
|
a7a9d45302 | ||
|
ba4dc29ca5 | ||
|
0a97f67515 | ||
|
7a94c6acef | ||
|
dbbbf1b193 | ||
|
9637dfa60d | ||
|
aec738a9db | ||
|
382ee5bf93 | ||
|
47d1e303aa | ||
|
67443c122a | ||
|
24056e89a4 | ||
|
c06bc7da1a | ||
|
aedd2125fc | ||
|
425cf9b6f6 |
62
Database/PostgreSQL.sql
Normal file
62
Database/PostgreSQL.sql
Normal file
@@ -0,0 +1,62 @@
|
||||
-- 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)
|
||||
);
|
||||
|
||||
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;
|
14
Migration.md
14
Migration.md
@@ -10,21 +10,11 @@
|
||||
|
||||
## General
|
||||
|
||||
Update your version of this library via Composer [[?]](https://github.com/delight-im/Knowledge/blob/master/Composer%20(PHP).md):
|
||||
|
||||
```
|
||||
$ composer update delight-im/auth
|
||||
```
|
||||
|
||||
If you want to perform a major version upgrade (e.g. from version `1.x.x` to version `2.x.x`), the version constraints defined in your `composer.json` [[?]](https://github.com/delight-im/Knowledge/blob/master/Composer%20(PHP).md) may not allow this. In that case, just add the dependency again to overwrite it with the latest version (or optionally with a specified version):
|
||||
|
||||
```
|
||||
$ composer require delight-im/auth
|
||||
```
|
||||
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).
|
||||
|
||||
## 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`.
|
||||
|
||||
|
113
README.md
113
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
|
||||
@@ -79,6 +81,7 @@ Migrating from an earlier version of this project? See our [upgrade guide](Migra
|
||||
* [Assigning roles to users](#assigning-roles-to-users)
|
||||
* [Taking roles away from users](#taking-roles-away-from-users)
|
||||
* [Checking roles](#checking-roles-1)
|
||||
* [Impersonating users (logging in as user)](#impersonating-users-logging-in-as-user)
|
||||
* [Cookies](#cookies)
|
||||
* [Renaming the library’s cookies](#renaming-the-librarys-cookies)
|
||||
* [Defining the domain scope for cookies](#defining-the-domain-scope-for-cookies)
|
||||
@@ -95,12 +98,16 @@ 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);
|
||||
@@ -108,10 +115,14 @@ $auth = new \Delight\Auth\Auth($db);
|
||||
|
||||
If you have an open `PDO` connection already, just re-use it.
|
||||
|
||||
If your web server is behind a proxy server and `$_SERVER['REMOTE_ADDR']` only contains the proxy’s IP address, you must pass the user’s real IP address to the constructor in the second argument, which is named `$ipAddress`. The default is `null`.
|
||||
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.
|
||||
|
||||
Should your database tables for this library need a common prefix, e.g. `my_users` instead of `users` (and likewise for the other tables), pass the prefix (e.g. `my_`) as the third parameter to the constructor, which is named `$dbTablePrefix`. This is optional and the prefix is empty by default.
|
||||
|
||||
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`.
|
||||
|
||||
### Registration (sign up)
|
||||
|
||||
```php
|
||||
@@ -225,6 +236,8 @@ 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) {
|
||||
@@ -253,12 +266,39 @@ You should build an URL with the selector and token and send it to the user, e.g
|
||||
$url = 'https://www.example.com/reset_password?selector=' . \urlencode($selector) . '&token=' . \urlencode($token);
|
||||
```
|
||||
|
||||
#### 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'])) {
|
||||
try {
|
||||
$auth->canResetPasswordOrThrow($_GET['selector'], $_GET['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)
|
||||
|
||||
// ask the user for their new password
|
||||
}
|
||||
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
|
||||
// invalid token
|
||||
}
|
||||
catch (\Delight\Auth\TokenExpiredException $e) {
|
||||
// token expired
|
||||
}
|
||||
catch (\Delight\Auth\ResetDisabledException $e) {
|
||||
// password reset is disabled
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// 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'])) {
|
||||
// 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)
|
||||
|
||||
@@ -266,6 +306,8 @@ if ($auth->canResetPassword($_POST['selector'], $_POST['token'])) {
|
||||
}
|
||||
```
|
||||
|
||||
#### 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
|
||||
@@ -580,6 +622,12 @@ if ($auth->hasAllRoles(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGE
|
||||
|
||||
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
|
||||
@@ -607,7 +655,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)
|
||||
|
||||
@@ -898,6 +954,53 @@ catch (\Delight\Auth\UnknownIdException $e) {
|
||||
}
|
||||
```
|
||||
|
||||
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
|
||||
try {
|
||||
$auth->admin()->logInAsUserById($_POST['id']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown ID
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email address not verified
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
try {
|
||||
$auth->admin()->logInAsUserByEmail($_POST['email']);
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// unknown email address
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email address not verified
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
try {
|
||||
$auth->admin()->logInAsUserByUsername($_POST['username']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
// unknown username
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
// ambiguous username
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email address not verified
|
||||
}
|
||||
```
|
||||
|
||||
### Cookies
|
||||
|
||||
This library uses two cookies to keep state on the client: The first, whose name you can retrieve using
|
||||
|
@@ -286,6 +286,90 @@ final class Administration extends UserManager {
|
||||
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->dbTablePrefix . '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
|
||||
*
|
||||
* @param int $id the ID of the user to sign in as
|
||||
* @throws UnknownIdException if no user with the specified ID has been found
|
||||
* @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function logInAsUserById($id) {
|
||||
$numberOfMatchedUsers = $this->logInAsUserByColumnValue('id', (int) $id);
|
||||
|
||||
if ($numberOfMatchedUsers === 0) {
|
||||
throw new UnknownIdException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs in as the user with the specified email address
|
||||
*
|
||||
* @param string $email the email address of the user to sign in as
|
||||
* @throws InvalidEmailException if no user with the specified email address has been found
|
||||
* @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function logInAsUserByEmail($email) {
|
||||
$email = self::validateEmailAddress($email);
|
||||
|
||||
$numberOfMatchedUsers = $this->logInAsUserByColumnValue('email', $email);
|
||||
|
||||
if ($numberOfMatchedUsers === 0) {
|
||||
throw new InvalidEmailException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs in as the user with the specified display name
|
||||
*
|
||||
* @param string $username the display name of the user to sign in as
|
||||
* @throws UnknownUsernameException if no user with the specified username has been found
|
||||
* @throws AmbiguousUsernameException if multiple users with the specified username have been found
|
||||
* @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function logInAsUserByUsername($username) {
|
||||
$numberOfMatchedUsers = $this->logInAsUserByColumnValue('username', \trim($username));
|
||||
|
||||
if ($numberOfMatchedUsers === 0) {
|
||||
throw new UnknownUsernameException();
|
||||
}
|
||||
elseif ($numberOfMatchedUsers > 1) {
|
||||
throw new AmbiguousUsernameException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all existing users where the column with the specified name has the given value
|
||||
*
|
||||
@@ -404,4 +488,42 @@ final class Administration extends UserManager {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs in as the user for which the column with the specified name has the given value
|
||||
*
|
||||
* You must never pass untrusted input to the parameter that takes the column name
|
||||
*
|
||||
* @param string $columnName the name of the column to filter by
|
||||
* @param mixed $columnValue the value to look for in the selected column
|
||||
* @return int the number of matched users (where only a value of one means that the login may have been successful)
|
||||
* @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
private function logInAsUserByColumnValue($columnName, $columnValue) {
|
||||
try {
|
||||
$users = $this->db->select(
|
||||
'SELECT verified, id, email, username, status, roles_mask FROM ' . $this->dbTablePrefix . 'users WHERE ' . $columnName . ' = ? LIMIT 2 OFFSET 0',
|
||||
[ $columnValue ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
}
|
||||
|
||||
$numberOfMatchingUsers = \count($users);
|
||||
|
||||
if ($numberOfMatchingUsers === 1) {
|
||||
$user = $users[0];
|
||||
|
||||
if ((int) $user['verified'] === 1) {
|
||||
$this->onLoginSuccessful($user['id'], $user['email'], $user['username'], $user['status'], $user['roles_mask'], false);
|
||||
}
|
||||
else {
|
||||
throw new EmailNotVerifiedException();
|
||||
}
|
||||
}
|
||||
|
||||
return $numberOfMatchingUsers;
|
||||
}
|
||||
|
||||
}
|
||||
|
214
src/Auth.php
214
src/Auth.php
@@ -21,18 +21,15 @@ require_once __DIR__ . '/Exceptions.php';
|
||||
/** Component that provides all features and utilities for secure authentication of individual users */
|
||||
final class Auth extends UserManager {
|
||||
|
||||
const SESSION_FIELD_LOGGED_IN = 'auth_logged_in';
|
||||
const SESSION_FIELD_USER_ID = 'auth_user_id';
|
||||
const SESSION_FIELD_EMAIL = 'auth_email';
|
||||
const SESSION_FIELD_USERNAME = 'auth_username';
|
||||
const SESSION_FIELD_STATUS = 'auth_status';
|
||||
const SESSION_FIELD_ROLES = 'auth_roles';
|
||||
const SESSION_FIELD_REMEMBERED = 'auth_remembered';
|
||||
const COOKIE_PREFIXES = [ Cookie::PREFIX_SECURE, Cookie::PREFIX_HOST ];
|
||||
const COOKIE_CONTENT_SEPARATOR = '~';
|
||||
|
||||
/** @var string the user's current IP address */
|
||||
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;
|
||||
|
||||
@@ -40,17 +37,22 @@ final class Auth extends UserManager {
|
||||
* @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 $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
|
||||
*/
|
||||
public function __construct($databaseConnection, $ipAddress = null, $dbTablePrefix = null) {
|
||||
public function __construct($databaseConnection, $ipAddress = null, $dbTablePrefix = null, $throttling = null, $sessionResyncInterval = null) {
|
||||
parent::__construct($databaseConnection, $dbTablePrefix);
|
||||
|
||||
$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->enhanceHttpSecurity();
|
||||
|
||||
$this->processRememberDirective();
|
||||
$this->resyncSessionIfNecessary();
|
||||
}
|
||||
|
||||
/** Initializes the session and sets the correct configuration */
|
||||
@@ -139,6 +141,46 @@ final class Auth extends UserManager {
|
||||
}
|
||||
}
|
||||
|
||||
private function resyncSessionIfNecessary() {
|
||||
// if the user is signed in
|
||||
if ($this->isLoggedIn()) {
|
||||
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 FROM ' . $this->dbTablePrefix . 'users WHERE id = ?',
|
||||
[ $this->getUserId() ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
}
|
||||
|
||||
// if the user's data has been found
|
||||
if (!empty($authoritativeData)) {
|
||||
// update the session data
|
||||
$_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'];
|
||||
}
|
||||
// if no data has been found for the user
|
||||
else {
|
||||
// their account may have been deleted so they should be signed out
|
||||
$this->logOut();
|
||||
}
|
||||
|
||||
// remember that we've just performed resynchronization
|
||||
$_SESSION[self::SESSION_FIELD_LAST_RESYNC] = \time();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to sign up a user
|
||||
*
|
||||
@@ -346,6 +388,7 @@ 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]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -458,18 +501,8 @@ final class Auth extends UserManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the user has successfully logged in (via standard login or "remember me")
|
||||
*
|
||||
* @param int $userId the ID of the user who has just logged in
|
||||
* @param string $email the email address of the user who has just logged in
|
||||
* @param string $username the username (if any)
|
||||
* @param int $status the status as one of the constants from the {@see Status} class
|
||||
* @param int $roles the bitmask containing the roles of the user
|
||||
* @param bool $remembered whether the user was remembered ("remember me") or logged in actively
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
private function onLoginSuccessful($userId, $email, $username, $status, $roles, $remembered) {
|
||||
protected function onLoginSuccessful($userId, $email, $username, $status, $roles, $remembered) {
|
||||
// update the timestamp of the user's last login
|
||||
try {
|
||||
$this->db->update(
|
||||
$this->dbTablePrefix . 'users',
|
||||
@@ -481,17 +514,7 @@ final class Auth extends UserManager {
|
||||
throw new DatabaseError();
|
||||
}
|
||||
|
||||
// re-generate the session ID to prevent session fixation attacks (requests a cookie to be written on the client)
|
||||
Session::regenerate(true);
|
||||
|
||||
// save the user data in the session
|
||||
$this->setLoggedIn(true);
|
||||
$this->setUserId($userId);
|
||||
$this->setEmail($email);
|
||||
$this->setUsername($username);
|
||||
$this->setStatus($status);
|
||||
$this->setRoles($roles);
|
||||
$this->setRemembered($remembered);
|
||||
parent::onLoginSuccessful($userId, $email, $username, $status, $roles, $remembered);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -591,10 +614,11 @@ 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
|
||||
$this->setEmail($confirmationData['email']);
|
||||
$_SESSION[self::SESSION_FIELD_EMAIL] = $confirmationData['email'];
|
||||
}
|
||||
}
|
||||
|
||||
// consume the token just being used for confirmation
|
||||
try {
|
||||
$this->db->delete(
|
||||
$this->dbTablePrefix . 'users_confirmations',
|
||||
@@ -779,8 +803,8 @@ final class Auth extends UserManager {
|
||||
throw new EmailNotVerifiedException();
|
||||
}
|
||||
|
||||
$this->throttle([ 'requestEmailChange', 'userId', $this->getUserId() ], 1, (60 * 60 * 24));
|
||||
$this->throttle([ 'requestEmailChange', $this->getIpAddress() ], 1, (60 * 60 * 24), 3);
|
||||
$this->throttle([ 'requestEmailChange', 'user', $this->getUserId() ], 1, (60 * 60 * 24), 3);
|
||||
|
||||
$this->createConfirmationRequest($this->getUserId(), $newEmail, $callback);
|
||||
}
|
||||
@@ -854,7 +878,7 @@ final class Auth extends UserManager {
|
||||
private function resendConfirmationForColumnValue($columnName, $columnValue, callable $callback) {
|
||||
try {
|
||||
$latestAttempt = $this->db->selectRow(
|
||||
'SELECT user_id, email, expires FROM ' . $this->dbTablePrefix . 'users_confirmations WHERE ' . $columnName . ' = ? ORDER BY id DESC LIMIT 1 OFFSET 0',
|
||||
'SELECT user_id, email FROM ' . $this->dbTablePrefix . 'users_confirmations WHERE ' . $columnName . ' = ? ORDER BY id DESC LIMIT 1 OFFSET 0',
|
||||
[ $columnValue ]
|
||||
);
|
||||
}
|
||||
@@ -866,14 +890,8 @@ final class Auth extends UserManager {
|
||||
throw new ConfirmationRequestNotFound();
|
||||
}
|
||||
|
||||
$retryAt = $latestAttempt['expires'] - 0.75 * self::CONFIRMATION_REQUESTS_TTL_IN_SECONDS;
|
||||
|
||||
if ($retryAt > \time()) {
|
||||
throw new TooManyRequestsException('', $retryAt - \time());
|
||||
}
|
||||
|
||||
$this->throttle([ 'resendConfirmation', 'userId', $latestAttempt['user_id'] ], 1, (60 * 60 * 6));
|
||||
$this->throttle([ 'resendConfirmation', $this->getIpAddress() ], 4, (60 * 60 * 24 * 7), 2);
|
||||
$this->throttle([ 'resendConfirmation', 'user', $latestAttempt['user_id'] ], 4, (60 * 60 * 24 * 7), 2);
|
||||
|
||||
$this->createConfirmationRequest(
|
||||
$latestAttempt['user_id'],
|
||||
@@ -1232,6 +1250,40 @@ final class Auth extends UserManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the supplied selector/token pair can be used to reset a password
|
||||
*
|
||||
* 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 `Auth#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)
|
||||
*/
|
||||
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
|
||||
*
|
||||
@@ -1244,18 +1296,10 @@ final class Auth extends UserManager {
|
||||
*/
|
||||
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;
|
||||
}
|
||||
@@ -1318,15 +1362,6 @@ final class Auth extends UserManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets whether the user is currently logged in and updates the session
|
||||
*
|
||||
* @param bool $loggedIn whether the user is logged in or not
|
||||
*/
|
||||
private function setLoggedIn($loggedIn) {
|
||||
$_SESSION[self::SESSION_FIELD_LOGGED_IN] = $loggedIn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the user is currently logged in by reading from the session
|
||||
*
|
||||
@@ -1345,15 +1380,6 @@ final class Auth extends UserManager {
|
||||
return $this->isLoggedIn();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the currently signed-in user's ID and updates the session
|
||||
*
|
||||
* @param int $userId the user's ID
|
||||
*/
|
||||
private function setUserId($userId) {
|
||||
$_SESSION[self::SESSION_FIELD_USER_ID] = (int) $userId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the currently signed-in user's ID by reading from the session
|
||||
*
|
||||
@@ -1377,15 +1403,6 @@ final class Auth extends UserManager {
|
||||
return $this->getUserId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the currently signed-in user's email address and updates the session
|
||||
*
|
||||
* @param string $email the email address
|
||||
*/
|
||||
private function setEmail($email) {
|
||||
$_SESSION[self::SESSION_FIELD_EMAIL] = $email;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the currently signed-in user's email address by reading from the session
|
||||
*
|
||||
@@ -1400,15 +1417,6 @@ final class Auth extends UserManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the currently signed-in user's display name and updates the session
|
||||
*
|
||||
* @param string $username the display name
|
||||
*/
|
||||
private function setUsername($username) {
|
||||
$_SESSION[self::SESSION_FIELD_USERNAME] = $username;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the currently signed-in user's display name by reading from the session
|
||||
*
|
||||
@@ -1423,24 +1431,6 @@ final class Auth extends UserManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the currently signed-in user's status and updates the session
|
||||
*
|
||||
* @param int $status the status as one of the constants from the {@see Status} class
|
||||
*/
|
||||
private function setStatus($status) {
|
||||
$_SESSION[self::SESSION_FIELD_STATUS] = (int) $status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the currently signed-in user's roles and updates the session
|
||||
*
|
||||
* @param int $roles the bitmask containing the roles
|
||||
*/
|
||||
private function setRoles($roles) {
|
||||
$_SESSION[self::SESSION_FIELD_ROLES] = (int) $roles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the currently signed-in user's status by reading from the session
|
||||
*
|
||||
@@ -1583,12 +1573,16 @@ final class Auth extends UserManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets whether the currently signed-in user has been remembered by a long-lived cookie
|
||||
* Returns an array of the user's roles, mapping the numerical values to their descriptive names
|
||||
*
|
||||
* @param bool $remembered whether the user was remembered
|
||||
* @return array
|
||||
*/
|
||||
private function setRemembered($remembered) {
|
||||
$_SESSION[self::SESSION_FIELD_REMEMBERED] = $remembered;
|
||||
public function getRoles() {
|
||||
return \array_filter(
|
||||
Role::getMap(),
|
||||
[ $this, 'hasRole' ],
|
||||
\ARRAY_FILTER_USE_KEY
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1628,6 +1622,10 @@ final class Auth extends UserManager {
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function throttle(array $criteria, $supply, $interval, $burstiness = null, $simulated = null, $cost = null) {
|
||||
if (!$this->throttling) {
|
||||
return $supply;
|
||||
}
|
||||
|
||||
// generate a unique key for the bucket (consisting of 44 or fewer ASCII characters)
|
||||
$key = Base64::encodeUrlSafeWithoutPadding(
|
||||
\hash(
|
||||
|
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() {}
|
||||
|
||||
|
@@ -9,6 +9,7 @@
|
||||
namespace Delight\Auth;
|
||||
|
||||
use Delight\Base64\Base64;
|
||||
use Delight\Cookie\Session;
|
||||
use Delight\Db\PdoDatabase;
|
||||
use Delight\Db\PdoDsn;
|
||||
use Delight\Db\Throwable\Error;
|
||||
@@ -23,7 +24,22 @@ require_once __DIR__ . '/Exceptions.php';
|
||||
*/
|
||||
abstract class UserManager {
|
||||
|
||||
const CONFIRMATION_REQUESTS_TTL_IN_SECONDS = 60 * 60 * 24;
|
||||
/** @var string session field for whether the client is currently signed in */
|
||||
const SESSION_FIELD_LOGGED_IN = 'auth_logged_in';
|
||||
/** @var string session field for the ID of the user who is currently signed in (if any) */
|
||||
const SESSION_FIELD_USER_ID = 'auth_user_id';
|
||||
/** @var string session field for the email address of the user who is currently signed in (if any) */
|
||||
const SESSION_FIELD_EMAIL = 'auth_email';
|
||||
/** @var string session field for the display name (if any) of the user who is currently signed in (if any) */
|
||||
const SESSION_FIELD_USERNAME = 'auth_username';
|
||||
/** @var string session field for the status of the user who is currently signed in (if any) as one of the constants from the {@see Status} class */
|
||||
const SESSION_FIELD_STATUS = 'auth_status';
|
||||
/** @var string session field for the roles of the user who is currently signed in (if any) as a bitmask using constants from the {@see Role} class */
|
||||
const SESSION_FIELD_ROLES = 'auth_roles';
|
||||
/** @var string session field for whether the user who is currently signed in (if any) has been remembered (instead of them having authenticated actively) */
|
||||
const SESSION_FIELD_REMEMBERED = 'auth_remembered';
|
||||
/** @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 PdoDatabase the database connection to operate on */
|
||||
protected $db;
|
||||
@@ -166,6 +182,34 @@ abstract class UserManager {
|
||||
return $newUserId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when a user has successfully logged in
|
||||
*
|
||||
* This may happen via the standard login, via the "remember me" feature, or due to impersonation by administrators
|
||||
*
|
||||
* @param int $userId the ID of the user
|
||||
* @param string $email the email address of the user
|
||||
* @param string $username the display name (if any) of the user
|
||||
* @param int $status the status of the user as one of the constants from the {@see Status} class
|
||||
* @param int $roles the roles of the user as a bitmask using constants from the {@see Role} class
|
||||
* @param bool $remembered whether the user has been remembered (instead of them having authenticated actively)
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
protected function onLoginSuccessful($userId, $email, $username, $status, $roles, $remembered) {
|
||||
// re-generate the session ID to prevent session fixation attacks (requests a cookie to be written on the client)
|
||||
Session::regenerate(true);
|
||||
|
||||
// save the user data in the session variables maintained by this library
|
||||
$_SESSION[self::SESSION_FIELD_LOGGED_IN] = true;
|
||||
$_SESSION[self::SESSION_FIELD_USER_ID] = (int) $userId;
|
||||
$_SESSION[self::SESSION_FIELD_EMAIL] = $email;
|
||||
$_SESSION[self::SESSION_FIELD_USERNAME] = $username;
|
||||
$_SESSION[self::SESSION_FIELD_STATUS] = (int) $status;
|
||||
$_SESSION[self::SESSION_FIELD_ROLES] = (int) $roles;
|
||||
$_SESSION[self::SESSION_FIELD_REMEMBERED] = $remembered;
|
||||
$_SESSION[self::SESSION_FIELD_LAST_RESYNC] = \time();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the requested user data for the account with the specified username (if any)
|
||||
*
|
||||
@@ -266,9 +310,7 @@ abstract class UserManager {
|
||||
$selector = self::createRandomString(16);
|
||||
$token = self::createRandomString(16);
|
||||
$tokenHashed = \password_hash($token, \PASSWORD_DEFAULT);
|
||||
|
||||
// the request shall be valid for one day
|
||||
$expires = \time() + self::CONFIRMATION_REQUESTS_TTL_IN_SECONDS;
|
||||
$expires = \time() + 60 * 60 * 24;
|
||||
|
||||
try {
|
||||
$this->db->insert(
|
||||
|
159
tests/index.php
159
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);
|
||||
@@ -84,7 +86,7 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
return 'wrong password';
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
return 'email not verified';
|
||||
return 'email address not verified';
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
return 'too many requests';
|
||||
@@ -242,10 +244,10 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
return 'invalid email address';
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
return 'email not verified';
|
||||
return 'email address not verified';
|
||||
}
|
||||
catch (\Delight\Auth\ResetDisabledException $e) {
|
||||
return 'password reset disabled';
|
||||
return 'password reset is disabled';
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
return 'too many requests';
|
||||
@@ -264,7 +266,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 +275,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';
|
||||
@@ -422,7 +443,7 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'either ID, email or username required';
|
||||
return 'either ID, email address or username required';
|
||||
}
|
||||
|
||||
return 'ok';
|
||||
@@ -457,7 +478,7 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'either ID, email or username required';
|
||||
return 'either ID, email address or username required';
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -496,7 +517,7 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'either ID, email or username required';
|
||||
return 'either ID, email address or username required';
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -523,6 +544,76 @@ 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 {
|
||||
$auth->admin()->logInAsUserById($_POST['id']);
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
return 'unknown ID';
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
return 'email address not verified';
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'ID required';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'admin.logInAsUserByEmail') {
|
||||
if (isset($_POST['email'])) {
|
||||
try {
|
||||
$auth->admin()->logInAsUserByEmail($_POST['email']);
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
return 'unknown email address';
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
return 'email address not verified';
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'Email address required';
|
||||
}
|
||||
}
|
||||
else if ($_POST['action'] === 'admin.logInAsUserByUsername') {
|
||||
if (isset($_POST['username'])) {
|
||||
try {
|
||||
$auth->admin()->logInAsUserByUsername($_POST['username']);
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
return 'unknown username';
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
return 'ambiguous username';
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
return 'email address not verified';
|
||||
}
|
||||
}
|
||||
else {
|
||||
return 'Username required';
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw new Exception('Unexpected action: ' . $_POST['action']);
|
||||
}
|
||||
@@ -574,6 +665,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";
|
||||
@@ -687,7 +781,7 @@ function showGuestUserForm() {
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="login" />';
|
||||
echo '<input type="text" name="email" placeholder="Email" /> ';
|
||||
echo '<input type="text" name="email" placeholder="Email address" /> ';
|
||||
echo '<input type="text" name="password" placeholder="Password" /> ';
|
||||
echo '<select name="remember" size="1">';
|
||||
echo '<option value="0">Remember (keep logged in)? — No</option>';
|
||||
@@ -709,7 +803,7 @@ function showGuestUserForm() {
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="register" />';
|
||||
echo '<input type="text" name="email" placeholder="Email" /> ';
|
||||
echo '<input type="text" name="email" placeholder="Email address" /> ';
|
||||
echo '<input type="text" name="password" placeholder="Password" /> ';
|
||||
echo '<input type="text" name="username" placeholder="Username (optional)" /> ';
|
||||
echo '<select name="require_verification" size="1">';
|
||||
@@ -727,7 +821,7 @@ function showGuestUserForm() {
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="forgotPassword" />';
|
||||
echo '<input type="text" name="email" placeholder="Email" /> ';
|
||||
echo '<input type="text" name="email" placeholder="Email address" /> ';
|
||||
echo '<button type="submit">Forgot password</button>';
|
||||
echo '</form>';
|
||||
|
||||
@@ -739,11 +833,18 @@ function showGuestUserForm() {
|
||||
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>';
|
||||
|
||||
echo '<h1>Administration</h1>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.createUser" />';
|
||||
echo '<input type="text" name="email" placeholder="Email" /> ';
|
||||
echo '<input type="text" name="email" placeholder="Email address" /> ';
|
||||
echo '<input type="text" name="password" placeholder="Password" /> ';
|
||||
echo '<input type="text" name="username" placeholder="Username (optional)" /> ';
|
||||
echo '<select name="require_unique_username" size="1">';
|
||||
@@ -761,7 +862,7 @@ function showGuestUserForm() {
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.deleteUser" />';
|
||||
echo '<input type="text" name="email" placeholder="Email" /> ';
|
||||
echo '<input type="text" name="email" placeholder="Email address" /> ';
|
||||
echo '<button type="submit">Delete user by email</button>';
|
||||
echo '</form>';
|
||||
|
||||
@@ -780,7 +881,7 @@ function showGuestUserForm() {
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.addRole" />';
|
||||
echo '<input type="text" name="email" placeholder="Email" /> ';
|
||||
echo '<input type="text" name="email" placeholder="Email address" /> ';
|
||||
echo '<select name="role">' . \createRolesOptions() . '</select>';
|
||||
echo '<button type="submit">Add role for user by email</button>';
|
||||
echo '</form>';
|
||||
@@ -801,7 +902,7 @@ function showGuestUserForm() {
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.removeRole" />';
|
||||
echo '<input type="text" name="email" placeholder="Email" /> ';
|
||||
echo '<input type="text" name="email" placeholder="Email address" /> ';
|
||||
echo '<select name="role">' . \createRolesOptions() . '</select>';
|
||||
echo '<button type="submit">Remove role for user by email</button>';
|
||||
echo '</form>';
|
||||
@@ -819,6 +920,30 @@ function showGuestUserForm() {
|
||||
echo '<select name="role">' . \createRolesOptions() . '</select>';
|
||||
echo '<button type="submit">Does user have role?</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.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" /> ';
|
||||
echo '<button type="submit">Log in as user by ID</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.logInAsUserByEmail" />';
|
||||
echo '<input type="text" name="email" placeholder="Email address" /> ';
|
||||
echo '<button type="submit">Log in as user by email address</button>';
|
||||
echo '</form>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="admin.logInAsUserByUsername" />';
|
||||
echo '<input type="text" name="username" placeholder="Username" /> ';
|
||||
echo '<button type="submit">Log in as user by username</button>';
|
||||
echo '</form>';
|
||||
}
|
||||
|
||||
function showConfirmEmailForm() {
|
||||
@@ -836,7 +961,7 @@ function showConfirmEmailForm() {
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
echo '<input type="hidden" name="action" value="resendConfirmationForEmail" />';
|
||||
echo '<input type="text" name="email" placeholder="Email" /> ';
|
||||
echo '<input type="text" name="email" placeholder="Email address" /> ';
|
||||
echo '<button type="submit">Re-send confirmation</button>';
|
||||
echo '</form>';
|
||||
|
||||
@@ -848,11 +973,9 @@ function showConfirmEmailForm() {
|
||||
}
|
||||
|
||||
function createRolesOptions() {
|
||||
$roleReflection = new ReflectionClass(\Delight\Auth\Role::class);
|
||||
|
||||
$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