mirror of
https://github.com/delight-im/PHP-Auth.git
synced 2025-08-07 16:46:29 +02:00
Compare commits
51 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
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 |
@@ -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;
|
||||
|
@@ -14,7 +14,8 @@ CREATE TABLE IF NOT EXISTS "users" (
|
||||
"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)
|
||||
"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" (
|
||||
@@ -25,9 +26,7 @@ CREATE TABLE IF NOT EXISTS "users_confirmations" (
|
||||
"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" (
|
||||
@@ -37,7 +36,6 @@ CREATE TABLE IF NOT EXISTS "users_remembered" (
|
||||
"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" (
|
||||
@@ -47,7 +45,6 @@ CREATE TABLE IF NOT EXISTS "users_resets" (
|
||||
"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" (
|
||||
@@ -56,7 +53,6 @@ CREATE TABLE IF NOT EXISTS "users_throttling" (
|
||||
"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")
|
||||
);
|
||||
|
||||
|
30
Migration.md
30
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)
|
||||
@@ -12,6 +13,35 @@
|
||||
|
||||
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 `v7.x.x` to `v8.x.x`
|
||||
|
||||
* The database schema has changed.
|
||||
|
||||
* 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`.
|
||||
|
58
README.md
58
README.md
@@ -82,6 +82,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)
|
||||
@@ -113,7 +114,7 @@ Migrating from an earlier version of this project? See our [upgrade guide](Migra
|
||||
$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.
|
||||
|
||||
@@ -450,10 +451,30 @@ $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) {
|
||||
// not logged in
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
try {
|
||||
$auth->logOutEverywhere();
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
// 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();
|
||||
```
|
||||
|
||||
### Accessing user information
|
||||
@@ -1001,6 +1022,35 @@ catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
}
|
||||
```
|
||||
|
||||
#### Changing a user’s password
|
||||
|
||||
```php
|
||||
try {
|
||||
$auth->admin()->changePasswordForUserById($_POST['id'], $_POST['newPassword']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown ID
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
// invalid password
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
try {
|
||||
$auth->admin()->changePasswordForUserByUsername($_POST['username'], $_POST['newPassword']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
// unknown username
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
// ambiguous username
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
// invalid password
|
||||
}
|
||||
```
|
||||
|
||||
### Cookies
|
||||
|
||||
This library uses two cookies to keep state on the client: The first, whose name you can retrieve using
|
||||
|
@@ -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,12 +18,10 @@ 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
|
||||
*/
|
||||
public function __construct(PdoDatabase $databaseConnection, $dbTablePrefix = null) {
|
||||
public function __construct($databaseConnection, $dbTablePrefix = null) {
|
||||
parent::__construct($databaseConnection, $dbTablePrefix);
|
||||
}
|
||||
|
||||
@@ -370,6 +369,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
|
||||
*
|
||||
@@ -390,7 +432,7 @@ final class Administration extends UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -415,7 +457,7 @@ final class Administration extends UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if ($userData === null) {
|
||||
@@ -436,7 +478,7 @@ final class Administration extends UserManager {
|
||||
return true;
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -507,16 +549,16 @@ final class Administration extends UserManager {
|
||||
);
|
||||
}
|
||||
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();
|
||||
|
334
src/Auth.php
334
src/Auth.php
@@ -48,7 +48,7 @@ final class Auth extends UserManager {
|
||||
$this->sessionResyncInterval = isset($sessionResyncInterval) ? ((int) $sessionResyncInterval) : (60 * 5);
|
||||
$this->rememberCookieName = self::createRememberCookieName();
|
||||
|
||||
$this->initSession();
|
||||
$this->initSessionIfNecessary();
|
||||
$this->enhanceHttpSecurity();
|
||||
|
||||
$this->processRememberDirective();
|
||||
@@ -56,16 +56,18 @@ final class Auth extends UserManager {
|
||||
}
|
||||
|
||||
/** 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 */
|
||||
@@ -112,12 +114,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->dbTablePrefix . 'users_remembered AS a JOIN ' . $this->dbTablePrefix . '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)) {
|
||||
@@ -126,7 +128,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -144,6 +146,7 @@ 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;
|
||||
}
|
||||
@@ -153,30 +156,43 @@ final class Auth extends UserManager {
|
||||
// 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 = ?',
|
||||
'SELECT email, username, status, roles_mask, force_logout FROM ' . $this->dbTablePrefix . 'users WHERE id = ?',
|
||||
[ $this->getUserId() ]
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
// 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'];
|
||||
// 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();
|
||||
}
|
||||
|
||||
// remember that we've just performed resynchronization
|
||||
$_SESSION[self::SESSION_FIELD_LAST_RESYNC] = \time();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -342,7 +358,7 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if (!empty($expectedHash)) {
|
||||
@@ -371,13 +387,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
|
||||
@@ -389,9 +408,65 @@ final class Auth extends UserManager {
|
||||
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
|
||||
*
|
||||
@@ -431,28 +506,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);
|
||||
}
|
||||
@@ -501,7 +562,7 @@ 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(
|
||||
@@ -511,20 +572,10 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -555,7 +606,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
|
||||
@@ -569,12 +620,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->dbTablePrefix . 'users_confirmations AS a JOIN ' . $this->dbTablePrefix . '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)) {
|
||||
@@ -588,7 +639,7 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
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)
|
||||
@@ -596,7 +647,7 @@ final class Auth extends UserManager {
|
||||
$this->db->update(
|
||||
$this->dbTablePrefix . 'users',
|
||||
[
|
||||
'email' => $confirmationData['email'],
|
||||
'email' => $confirmationData['new_email'],
|
||||
'verified' => 1
|
||||
],
|
||||
[ 'id' => $confirmationData['user_id'] ]
|
||||
@@ -606,7 +657,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
|
||||
@@ -614,7 +665,7 @@ 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'];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -626,10 +677,19 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
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();
|
||||
@@ -654,7 +714,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
|
||||
@@ -662,18 +722,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);
|
||||
@@ -681,7 +741,7 @@ final class Auth extends UserManager {
|
||||
}
|
||||
}
|
||||
|
||||
return $verifiedEmail;
|
||||
return $emailBeforeAndAfter;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -714,37 +774,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)
|
||||
*
|
||||
@@ -781,7 +822,7 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if ((int) $existingUsersWithNewEmail !== 0) {
|
||||
@@ -795,7 +836,7 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
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
|
||||
@@ -883,7 +924,7 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if ($latestAttempt === null) {
|
||||
@@ -991,7 +1032,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);
|
||||
@@ -1023,12 +1064,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) {
|
||||
@@ -1096,7 +1137,7 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if (!empty($userData)) {
|
||||
@@ -1132,7 +1173,7 @@ final class Auth extends UserManager {
|
||||
}
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1170,7 +1211,7 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if (\is_callable($callback)) {
|
||||
@@ -1208,7 +1249,7 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if (!empty($resetData)) {
|
||||
@@ -1216,12 +1257,8 @@ 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(
|
||||
@@ -1230,7 +1267,7 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -1328,7 +1365,7 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -1354,7 +1391,7 @@ final class Auth extends UserManager {
|
||||
return (int) $enabled === 1;
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -1655,7 +1692,7 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if ($bucket === null) {
|
||||
@@ -1693,7 +1730,7 @@ final class Auth extends UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if ($affected === 0) {
|
||||
@@ -1707,7 +1744,7 @@ final class Auth extends UserManager {
|
||||
}
|
||||
catch (IntegrityConstraintViolationException $ignored) {}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1796,4 +1833,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->dbTablePrefix . '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;
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -40,6 +40,8 @@ abstract class UserManager {
|
||||
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;
|
||||
@@ -170,7 +172,7 @@ abstract class UserManager {
|
||||
throw new UserAlreadyExistsException();
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
$newUserId = (int) $this->db->getLastInsertId();
|
||||
@@ -182,6 +184,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->dbTablePrefix . '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
|
||||
*
|
||||
@@ -192,10 +221,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);
|
||||
|
||||
@@ -206,6 +236,7 @@ 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();
|
||||
}
|
||||
@@ -232,7 +263,7 @@ abstract class UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if (empty($users)) {
|
||||
@@ -325,7 +356,7 @@ abstract class UserManager {
|
||||
);
|
||||
}
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError();
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
if (\is_callable($callback)) {
|
||||
@@ -336,4 +367,45 @@ 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->dbTablePrefix . '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->dbTablePrefix . 'users SET force_logout = force_logout + 1 WHERE id = ?',
|
||||
[ $userId ]
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
102
tests/index.php
102
tests/index.php
@@ -151,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';
|
||||
@@ -383,8 +382,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';
|
||||
}
|
||||
@@ -614,6 +633,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']);
|
||||
}
|
||||
@@ -771,9 +827,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() {
|
||||
@@ -840,6 +903,8 @@ function showGuestUserForm() {
|
||||
echo '<button type="submit">Can reset password?</button>';
|
||||
echo '</form>';
|
||||
|
||||
\showDestroySessionForm();
|
||||
|
||||
echo '<h1>Administration</h1>';
|
||||
|
||||
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||
@@ -944,6 +1009,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() {
|
||||
@@ -972,6 +1051,13 @@ function showConfirmEmailForm() {
|
||||
echo '</form>';
|
||||
}
|
||||
|
||||
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 = '';
|
||||
|
||||
|
Reference in New Issue
Block a user