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

29 Commits

Author SHA1 Message Date
Marco
e7e174b05d Only configure and start session if not already started 2018-03-12 22:29:56 +01:00
Marco
8f35cc9965 Optimize spacing in PostgreSQL schema 2018-03-12 18:44:32 +01:00
Marco
142ccc362f Shorten line of text in README for better overview 2018-03-12 02:18:44 +01:00
Marco
bce31f9cfc Link to MariaDB schema separately from MySQL in README 2018-03-12 02:15:35 +01:00
Marco
3ddc7af1b4 Document support for PostgreSQL 2018-03-12 02:11:54 +01:00
Marco
62d9e44aa4 Add check constraints for unsigned integers in PostgreSQL schema 2018-03-12 01:51:33 +01:00
Marco
1121685cef Improve database schema for PostgreSQL 2018-03-12 01:51:15 +01:00
Tiberiu Chibici
2f9bab4779 Add database schema for PostgreSQL 2018-03-12 00:32:53 +01:00
Marco
89e99d727d Document resynchronization of session data with authoritative database 2018-03-10 20:54:24 +01:00
Marco
21341d3c18 Regularly resynchronize session data with authoritative source in DB 2018-03-10 20:53:13 +01:00
Marco
a1ae66374b Improve documentation on password reset by dividing it into steps 2018-03-10 17:47:03 +01:00
Marco
477164e8ec Rename identifiers in comments to prevent highlighting in IDE 2018-03-10 17:46:05 +01:00
Marco
9478a43e9b Re-implement method 'canResetPassword' using 'canResetPasswordOrThrow' 2018-03-10 04:13:14 +01:00
Marco
1ba8e1ff21 Document method 'canResetPasswordOrThrow' from class 'Auth' 2018-03-10 04:10:22 +01:00
Marco
1657102f75 Add tests for method 'canResetPasswordOrThrow' from class 'Auth' 2018-03-10 04:06:45 +01:00
Marco
d246248ab5 Implement method 'canResetPasswordOrThrow' in class 'Auth' 2018-03-10 03:54:42 +01:00
Marco
94531f24d3 Improve language 2018-03-10 03:50:12 +01:00
Marco
2f29830ed9 Improve documentation to use more suitable data source for token 2018-03-10 03:47:55 +01:00
Marco
42a8c1616c Document method 'getRolesForUserById' from class 'Administration' 2018-03-10 03:10:17 +01:00
Marco
a2be4c61ee Add tests for method 'getRolesForUserById' from class 'Administration' 2018-03-10 03:05:41 +01:00
Marco
d9f9198b45 Implement method 'getRolesForUserById' in class 'Administration' 2018-03-10 03:03:57 +01:00
Marco
13b58abebc Document method 'getRoles' from class 'Auth' 2018-03-10 03:01:23 +01:00
Marco
b0bf7647ce Add tests for method 'getRoles' from class 'Auth' 2018-03-10 02:56:32 +01:00
Marco
012577227a Implement method 'getRoles' in class 'Auth' 2018-03-10 02:54:57 +01:00
Marco
d834623954 Document methods 'getMap', 'getNames' and 'getValues' of class 'Role' 2018-03-10 02:51:27 +01:00
Marco
d3594898cc Make use of new method 'getMap' from class 'Role' in 'tests' 2018-03-10 02:03:25 +01:00
Marco
7d44158c32 Implement methods 'getMap', 'getNames' and 'getValues' in class 'Role' 2018-03-10 01:58:54 +01:00
Marco
04edd9f88f Simplify migration guide using that method names are case-insensitive 2018-03-09 15:22:55 +01:00
Marco
cd2ac47912 Simplify general notes for any update or upgrade in migration guide 2018-01-25 00:01:50 +01:00
8 changed files with 356 additions and 49 deletions

57
Database/PostgreSQL.sql Normal file
View File

@@ -0,0 +1,57 @@
-- 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;

View File

@@ -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`.

View File

@@ -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
@@ -96,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);
@@ -115,6 +121,8 @@ 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`.
### Registration (sign up)
```php
@@ -228,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) {
@@ -256,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 dont 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)
@@ -269,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
@@ -583,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
@@ -610,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 dont need.
You can use any of these roles and ignore those that you dont 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)
@@ -901,6 +954,12 @@ 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

View File

@@ -286,6 +286,36 @@ 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
*

View File

@@ -28,6 +28,8 @@ 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;
@@ -36,31 +38,36 @@ final class Auth extends UserManager {
* @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, $throttling = 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->initSessionIfNecessary();
$this->enhanceHttpSecurity();
$this->processRememberDirective();
$this->resyncSessionIfNecessary();
}
/** Initializes the session and sets the correct configuration */
private function initSession() {
// use cookies to store session IDs
\ini_set('session.use_cookies', 1);
// use cookies only (do not send session IDs in URLs)
\ini_set('session.use_only_cookies', 1);
// do not send session IDs in URLs
\ini_set('session.use_trans_sid', 0);
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)
\ini_set('session.use_only_cookies', 1);
// do not send session IDs in URLs
\ini_set('session.use_trans_sid', 0);
// start the session (requests a cookie to be written on the client)
@Session::start();
// 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 */
@@ -136,6 +143,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
*
@@ -343,6 +390,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]);
}
}
@@ -1204,6 +1252,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
*
@@ -1216,18 +1298,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;
}
@@ -1500,6 +1574,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
*

View File

@@ -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() {}

View File

@@ -38,6 +38,8 @@ 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 PdoDatabase the database connection to operate on */
protected $db;
@@ -205,6 +207,7 @@ abstract class UserManager {
$_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();
}
/**

View File

@@ -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);
@@ -245,7 +247,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';
@@ -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';
@@ -523,6 +544,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 {
@@ -631,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";
@@ -796,6 +833,13 @@ 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">';
@@ -877,6 +921,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" /> ';
@@ -923,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>';
}