mirror of
https://github.com/delight-im/PHP-Auth.git
synced 2025-08-11 18:43:59 +02:00
Compare commits
29 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
36b590eb81 | ||
|
5c6a71d921 | ||
|
d94243f19d | ||
|
2a2d93f534 | ||
|
989c7940e5 | ||
|
51a5735295 | ||
|
e5e465782b | ||
|
83caa3e785 | ||
|
f2a1aedf7a | ||
|
5c87e877db | ||
|
70842b4320 | ||
|
d527a82bfa | ||
|
31ae135740 | ||
|
c5e3bd191d | ||
|
53e1a5c1fc | ||
|
f3ca69010f | ||
|
da8d22c599 | ||
|
c993657f20 | ||
|
cce172442d | ||
|
aef2672942 | ||
|
e0b69ee33c | ||
|
40a5518ba7 | ||
|
2441ea2dc1 | ||
|
07f60d6610 | ||
|
35cc941f20 | ||
|
f4b464a6f8 | ||
|
bfa5b5e6b1 | ||
|
9d2d764ced | ||
|
f45e0f1cb4 |
@@ -1,3 +1,12 @@
|
|||||||
|
-- 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)
|
||||||
|
|
||||||
|
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
|
||||||
|
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
|
||||||
|
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
|
||||||
|
/*!40101 SET NAMES utf8mb4 */;
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `users` (
|
CREATE TABLE IF NOT EXISTS `users` (
|
||||||
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
|
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
|
||||||
`email` varchar(249) COLLATE utf8mb4_unicode_ci NOT NULL,
|
`email` varchar(249) COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||||
@@ -35,12 +44,12 @@ CREATE TABLE IF NOT EXISTS `users_remembered` (
|
|||||||
CREATE TABLE IF NOT EXISTS `users_resets` (
|
CREATE TABLE IF NOT EXISTS `users_resets` (
|
||||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
|
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
|
||||||
`user` int(10) unsigned NOT NULL,
|
`user` int(10) unsigned NOT NULL,
|
||||||
`selector` varchar(24) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
|
`selector` varchar(20) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
|
||||||
`token` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
|
`token` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
|
||||||
`expires` int(10) unsigned NOT NULL,
|
`expires` int(10) unsigned NOT NULL,
|
||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`),
|
||||||
UNIQUE KEY `selector` (`selector`),
|
UNIQUE KEY `selector` (`selector`),
|
||||||
KEY `user` (`user`)
|
KEY `user_expires` (`user`,`expires`)
|
||||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `users_throttling` (
|
CREATE TABLE IF NOT EXISTS `users_throttling` (
|
||||||
@@ -52,3 +61,7 @@ CREATE TABLE IF NOT EXISTS `users_throttling` (
|
|||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`),
|
||||||
UNIQUE KEY `action_type_selector_time_bucket` (`action_type`,`selector`,`time_bucket`)
|
UNIQUE KEY `action_type_selector_time_bucket` (`action_type`,`selector`,`time_bucket`)
|
||||||
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
|
||||||
|
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
|
||||||
|
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
||||||
|
@@ -38,3 +38,7 @@
|
|||||||
## From `v2.x.x` to `v3.x.x`
|
## From `v2.x.x` to `v3.x.x`
|
||||||
|
|
||||||
* The license has been changed from the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) to the [MIT License](https://opensource.org/licenses/MIT).
|
* The license has been changed from the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) to the [MIT License](https://opensource.org/licenses/MIT).
|
||||||
|
|
||||||
|
## From `v3.x.x` to `v4.x.x`
|
||||||
|
|
||||||
|
* PHP 5.6.0 or higher is now required.
|
||||||
|
76
README.md
76
README.md
@@ -16,8 +16,8 @@ Completely framework-agnostic and database-agnostic.
|
|||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
* PHP 5.5.0+
|
* PHP 5.6.0+
|
||||||
* OpenSSL extension
|
* OpenSSL extension (`openssl`)
|
||||||
* MySQL 5.5.3+ **or** MariaDB 5.5.23+
|
* MySQL 5.5.3+ **or** MariaDB 5.5.23+
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
@@ -43,8 +43,9 @@ Completely framework-agnostic and database-agnostic.
|
|||||||
### Create a new instance
|
### Create a new instance
|
||||||
|
|
||||||
```php
|
```php
|
||||||
// $db = new PDO('mysql:dbname=database;host=localhost;charset=utf8mb4', 'username', 'password');
|
// $db = new PDO('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
|
||||||
// $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
// or
|
||||||
|
// $db = new \Delight\Db\PdoDsn('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
|
||||||
|
|
||||||
$auth = new \Delight\Auth\Auth($db);
|
$auth = new \Delight\Auth\Auth($db);
|
||||||
```
|
```
|
||||||
@@ -113,7 +114,11 @@ catch (\Delight\Auth\TooManyRequestsException $e) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The third parameter controls whether the login is persistent with a long-lived cookie. This is known as the "remember me" feature. Set this to `false` to disable the feature. Otherwise, ask the user if they want to enable "remember me". This is usually done with a checkbox in your user interface. Then use their input to decide between `false` and `true` here. This is optional and the default is `false`.
|
The third parameter controls whether the login is persistent with a long-lived cookie. With such a persistent login, users may stay authenticated for a long time, even when the browser session has already been closed and the session cookies have expired. Typically, you'll want to keep the user logged in for weeks or months with this feature, which is known as "remember me" or "keep me logged in". Many users will find this more convenient, but it may be less secure if they leave their devices unattended.
|
||||||
|
|
||||||
|
*Without* the persistent login, which is the *default* behavior, a user will only stay logged in until they close their browser, or as long as configured via `session.cookie_lifetime` and `session.gc_maxlifetime` in PHP.
|
||||||
|
|
||||||
|
Set the third parameter to `false` to disable the feature. Otherwise, ask the user if they want to enable "remember me". This is usually done with a checkbox in your user interface. Use the input from that checkbox to decide between `false` and `true` here. This is optional and the default is `false`.
|
||||||
|
|
||||||
### Perform email verification
|
### Perform email verification
|
||||||
|
|
||||||
@@ -136,6 +141,65 @@ catch (\Delight\Auth\TooManyRequestsException $e) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Reset a password ("forgot password")
|
||||||
|
|
||||||
|
```php
|
||||||
|
try {
|
||||||
|
$auth->forgotPassword($_POST['email'], function ($selector, $token) {
|
||||||
|
// send `$selector` and `$token` to the user (e.g. via email)
|
||||||
|
});
|
||||||
|
|
||||||
|
// request has been generated
|
||||||
|
}
|
||||||
|
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||||
|
// invalid email address
|
||||||
|
}
|
||||||
|
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||||
|
// too many requests
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
You should build an URL with the selector and token and send it to the user, e.g.:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$url = 'https://www.example.com/reset_password?selector='.urlencode($selector).'&token='.urlencode($token);
|
||||||
|
```
|
||||||
|
|
||||||
|
As the next step, users will click on the link that they received. Extract the selector and token from the URL.
|
||||||
|
|
||||||
|
If the selector/token pair is valid, let the user choose a new password:
|
||||||
|
|
||||||
|
```php
|
||||||
|
if ($auth->canResetPassword($_POST['selector'], $_POST['token'])) {
|
||||||
|
// put the selector into a `hidden` field (or keep it in the URL)
|
||||||
|
// put the token into a `hidden` field (or keep it in the URL)
|
||||||
|
|
||||||
|
// ask the user for their new password
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Now when you have the new password for the user (and still have the other two pieces of information), you can reset the password:
|
||||||
|
|
||||||
|
```php
|
||||||
|
try {
|
||||||
|
$auth->resetPassword($_POST['selector'], $_POST['token'], $_POST['password']);
|
||||||
|
|
||||||
|
// password has been reset
|
||||||
|
}
|
||||||
|
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
|
||||||
|
// invalid token
|
||||||
|
}
|
||||||
|
catch (\Delight\Auth\TokenExpiredException $e) {
|
||||||
|
// token expired
|
||||||
|
}
|
||||||
|
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||||
|
// invalid password
|
||||||
|
}
|
||||||
|
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||||
|
// too many requests
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Change the current user's password
|
### Change the current user's password
|
||||||
|
|
||||||
If a user is currently logged in, they may change their password.
|
If a user is currently logged in, they may change their password.
|
||||||
@@ -250,7 +314,7 @@ $uuid = \Delight\Auth\Auth::createUuid();
|
|||||||
* customizable password requirements and enforcement
|
* customizable password requirements and enforcement
|
||||||
* optional usernames with customizable restrictions
|
* optional usernames with customizable restrictions
|
||||||
* login
|
* login
|
||||||
* keeping the user logged in for a long time via secure long-lived token ("remember me")
|
* keeping the user logged in for a long time (beyond expiration of browser session) via secure long-lived token ("remember me")
|
||||||
* account management
|
* account management
|
||||||
* change password
|
* change password
|
||||||
* tracking the time of sign up and last login
|
* tracking the time of sign up and last login
|
||||||
|
@@ -2,9 +2,10 @@
|
|||||||
"name": "delight-im/auth",
|
"name": "delight-im/auth",
|
||||||
"description": "Authentication for PHP. Simple, lightweight and secure.",
|
"description": "Authentication for PHP. Simple, lightweight and secure.",
|
||||||
"require": {
|
"require": {
|
||||||
"php": ">=5.5.0",
|
"php": ">=5.6.0",
|
||||||
"ext-openssl": "*",
|
"ext-openssl": "*",
|
||||||
"delight-im/cookie": "^2.0"
|
"delight-im/cookie": "^2.1",
|
||||||
|
"delight-im/db": "^1.0"
|
||||||
},
|
},
|
||||||
"type": "library",
|
"type": "library",
|
||||||
"keywords": [ "auth", "authentication", "login", "security" ],
|
"keywords": [ "auth", "authentication", "login", "security" ],
|
||||||
|
57
composer.lock
generated
57
composer.lock
generated
@@ -4,21 +4,21 @@
|
|||||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
|
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
|
||||||
"This file is @generated automatically"
|
"This file is @generated automatically"
|
||||||
],
|
],
|
||||||
"hash": "22e56875c7a1386807d5cf6ae01f50fa",
|
"hash": "bd80e3e52b8bd8a4a0c74c7cf9f5bf5e",
|
||||||
"content-hash": "b914ccd7ac15e1519d7a04b55dbe725e",
|
"content-hash": "3f836c43e0ff2293051f2ccb739d23cf",
|
||||||
"packages": [
|
"packages": [
|
||||||
{
|
{
|
||||||
"name": "delight-im/cookie",
|
"name": "delight-im/cookie",
|
||||||
"version": "v2.0.0",
|
"version": "v2.1.0",
|
||||||
"source": {
|
"source": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://github.com/delight-im/PHP-Cookie.git",
|
"url": "https://github.com/delight-im/PHP-Cookie.git",
|
||||||
"reference": "a746f4096885b6715a640a2122b1c21324624f8f"
|
"reference": "3e41e0d44959b59de98722b5b1b1fb83f9f528f3"
|
||||||
},
|
},
|
||||||
"dist": {
|
"dist": {
|
||||||
"type": "zip",
|
"type": "zip",
|
||||||
"url": "https://api.github.com/repos/delight-im/PHP-Cookie/zipball/a746f4096885b6715a640a2122b1c21324624f8f",
|
"url": "https://api.github.com/repos/delight-im/PHP-Cookie/zipball/3e41e0d44959b59de98722b5b1b1fb83f9f528f3",
|
||||||
"reference": "a746f4096885b6715a640a2122b1c21324624f8f",
|
"reference": "3e41e0d44959b59de98722b5b1b1fb83f9f528f3",
|
||||||
"shasum": ""
|
"shasum": ""
|
||||||
},
|
},
|
||||||
"require": {
|
"require": {
|
||||||
@@ -46,7 +46,48 @@
|
|||||||
"samesite",
|
"samesite",
|
||||||
"xss"
|
"xss"
|
||||||
],
|
],
|
||||||
"time": "2016-07-21 15:20:20"
|
"time": "2016-11-23 20:09:42"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "delight-im/db",
|
||||||
|
"version": "v1.0.2",
|
||||||
|
"source": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://github.com/delight-im/PHP-DB.git",
|
||||||
|
"reference": "c8d1eba6583007471d55bf7d88eb3c9d87ea849d"
|
||||||
|
},
|
||||||
|
"dist": {
|
||||||
|
"type": "zip",
|
||||||
|
"url": "https://api.github.com/repos/delight-im/PHP-DB/zipball/c8d1eba6583007471d55bf7d88eb3c9d87ea849d",
|
||||||
|
"reference": "c8d1eba6583007471d55bf7d88eb3c9d87ea849d",
|
||||||
|
"shasum": ""
|
||||||
|
},
|
||||||
|
"require": {
|
||||||
|
"ext-pdo": "*",
|
||||||
|
"php": ">=5.6.0"
|
||||||
|
},
|
||||||
|
"type": "library",
|
||||||
|
"autoload": {
|
||||||
|
"psr-4": {
|
||||||
|
"Delight\\Db\\": "src/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"notification-url": "https://packagist.org/downloads/",
|
||||||
|
"license": [
|
||||||
|
"MIT"
|
||||||
|
],
|
||||||
|
"description": "Safe and convenient SQL database access in a driver-agnostic way",
|
||||||
|
"homepage": "https://github.com/delight-im/PHP-DB",
|
||||||
|
"keywords": [
|
||||||
|
"database",
|
||||||
|
"mysql",
|
||||||
|
"pdo",
|
||||||
|
"pgsql",
|
||||||
|
"postgresql",
|
||||||
|
"sql",
|
||||||
|
"sqlite"
|
||||||
|
],
|
||||||
|
"time": "2016-12-01 12:40:36"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "delight-im/http",
|
"name": "delight-im/http",
|
||||||
@@ -92,7 +133,7 @@
|
|||||||
"prefer-stable": false,
|
"prefer-stable": false,
|
||||||
"prefer-lowest": false,
|
"prefer-lowest": false,
|
||||||
"platform": {
|
"platform": {
|
||||||
"php": ">=5.5.0",
|
"php": ">=5.6.0",
|
||||||
"ext-openssl": "*"
|
"ext-openssl": "*"
|
||||||
},
|
},
|
||||||
"platform-dev": []
|
"platform-dev": []
|
||||||
|
742
src/Auth.php
742
src/Auth.php
@@ -8,6 +8,13 @@
|
|||||||
|
|
||||||
namespace Delight\Auth;
|
namespace Delight\Auth;
|
||||||
|
|
||||||
|
use Delight\Cookie\Cookie;
|
||||||
|
use Delight\Cookie\Session;
|
||||||
|
use Delight\Db\PdoDatabase;
|
||||||
|
use Delight\Db\PdoDsn;
|
||||||
|
use Delight\Db\Throwable\Error;
|
||||||
|
use Delight\Db\Throwable\IntegrityConstraintViolationException;
|
||||||
|
|
||||||
require __DIR__.'/Base64.php';
|
require __DIR__.'/Base64.php';
|
||||||
require __DIR__.'/Exceptions.php';
|
require __DIR__.'/Exceptions.php';
|
||||||
|
|
||||||
@@ -24,10 +31,10 @@ class Auth {
|
|||||||
const IP_ADDRESS_HASH_ALGORITHM = 'sha256';
|
const IP_ADDRESS_HASH_ALGORITHM = 'sha256';
|
||||||
const THROTTLE_ACTION_LOGIN = 'login';
|
const THROTTLE_ACTION_LOGIN = 'login';
|
||||||
const THROTTLE_ACTION_REGISTER = 'register';
|
const THROTTLE_ACTION_REGISTER = 'register';
|
||||||
const THROTTLE_ACTION_CONFIRM_EMAIL = 'confirm_email';
|
const THROTTLE_ACTION_CONSUME_TOKEN = 'confirm_email';
|
||||||
const THROTTLE_HTTP_RESPONSE_CODE = 429;
|
const HTTP_STATUS_CODE_TOO_MANY_REQUESTS = 429;
|
||||||
|
|
||||||
/** @var \PDO the database connection that will be used */
|
/** @var PdoDatabase the database connection that will be used */
|
||||||
private $db;
|
private $db;
|
||||||
/** @var boolean whether HTTPS (TLS/SSL) will be used (recommended) */
|
/** @var boolean whether HTTPS (TLS/SSL) will be used (recommended) */
|
||||||
private $useHttps;
|
private $useHttps;
|
||||||
@@ -41,13 +48,25 @@ class Auth {
|
|||||||
private $throttlingTimeBucketSize;
|
private $throttlingTimeBucketSize;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param \PDO $databaseConnection the database connection that will be used
|
* @param PdoDatabase|PdoDsn|\PDO $databaseConnection the database connection that will be used
|
||||||
* @param bool $useHttps whether HTTPS (TLS/SSL) will be used (recommended)
|
* @param bool $useHttps whether HTTPS (TLS/SSL) will be used (recommended)
|
||||||
* @param bool $allowCookiesScriptAccess whether cookies should be accessible via client-side scripts (*not* recommended)
|
* @param bool $allowCookiesScriptAccess whether cookies should be accessible via client-side scripts (*not* recommended)
|
||||||
* @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 $ipAddress the IP address that should be used instead of the default setting (if any), e.g. when behind a proxy
|
||||||
*/
|
*/
|
||||||
public function __construct(\PDO $databaseConnection, $useHttps = false, $allowCookiesScriptAccess = false, $ipAddress = null) {
|
public function __construct($databaseConnection, $useHttps = false, $allowCookiesScriptAccess = false, $ipAddress = null) {
|
||||||
|
if ($databaseConnection instanceof PdoDatabase) {
|
||||||
$this->db = $databaseConnection;
|
$this->db = $databaseConnection;
|
||||||
|
}
|
||||||
|
elseif ($databaseConnection instanceof PdoDsn) {
|
||||||
|
$this->db = PdoDatabase::fromDsn($databaseConnection);
|
||||||
|
}
|
||||||
|
elseif ($databaseConnection instanceof \PDO) {
|
||||||
|
$this->db = PdoDatabase::fromPdo($databaseConnection, true);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
throw new \InvalidArgumentException('The database connection must be an instance of either `PdoDatabase`, `PdoDsn` or `PDO`');
|
||||||
|
}
|
||||||
|
|
||||||
$this->useHttps = $useHttps;
|
$this->useHttps = $useHttps;
|
||||||
$this->allowCookiesScriptAccess = $allowCookiesScriptAccess;
|
$this->allowCookiesScriptAccess = $allowCookiesScriptAccess;
|
||||||
$this->ipAddress = empty($ipAddress) ? $_SERVER['REMOTE_ADDR'] : $ipAddress;
|
$this->ipAddress = empty($ipAddress) ? $_SERVER['REMOTE_ADDR'] : $ipAddress;
|
||||||
@@ -75,7 +94,7 @@ class Auth {
|
|||||||
session_set_cookie_params($params['lifetime'], $params['path'], $params['domain'], $params['secure'], $params['httponly']);
|
session_set_cookie_params($params['lifetime'], $params['path'], $params['domain'], $params['secure'], $params['httponly']);
|
||||||
|
|
||||||
// start the session
|
// start the session
|
||||||
@\Delight\Cookie\Session::start();
|
@Session::start();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Improves the application's security over HTTP(S) by setting specific headers */
|
/** Improves the application's security over HTTP(S) by setting specific headers */
|
||||||
@@ -107,11 +126,17 @@ class Auth {
|
|||||||
$parts = explode(self::COOKIE_CONTENT_SEPARATOR, $_COOKIE[self::COOKIE_NAME_REMEMBER], 2);
|
$parts = explode(self::COOKIE_CONTENT_SEPARATOR, $_COOKIE[self::COOKIE_NAME_REMEMBER], 2);
|
||||||
// if both selector and token were found
|
// if both selector and token were found
|
||||||
if (isset($parts[0]) && isset($parts[1])) {
|
if (isset($parts[0]) && isset($parts[1])) {
|
||||||
$stmt = $this->db->prepare("SELECT a.user, a.token, a.expires, b.email, b.username FROM users_remembered AS a JOIN users AS b ON a.user = b.id WHERE a.selector = :selector");
|
try {
|
||||||
$stmt->bindValue(':selector', $parts[0], \PDO::PARAM_STR);
|
$rememberData = $this->db->selectRow(
|
||||||
if ($stmt->execute()) {
|
'SELECT a.user, a.token, a.expires, b.email, b.username FROM users_remembered AS a JOIN users AS b ON a.user = b.id WHERE a.selector = ?',
|
||||||
$rememberData = $stmt->fetch(\PDO::FETCH_ASSOC);
|
[ $parts[0] ]
|
||||||
if ($rememberData !== false) {
|
);
|
||||||
|
}
|
||||||
|
catch (Error $e) {
|
||||||
|
throw new DatabaseError();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($rememberData)) {
|
||||||
if ($rememberData['expires'] >= time()) {
|
if ($rememberData['expires'] >= time()) {
|
||||||
if (password_verify($parts[1], $rememberData['token'])) {
|
if (password_verify($parts[1], $rememberData['token'])) {
|
||||||
$this->onLoginSuccessful($rememberData['user'], $rememberData['email'], $rememberData['username'], true);
|
$this->onLoginSuccessful($rememberData['user'], $rememberData['email'], $rememberData['username'], true);
|
||||||
@@ -122,126 +147,113 @@ class Auth {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Attempts to sign up a user
|
* Attempts to sign up a user
|
||||||
*
|
*
|
||||||
* If you want accounts to be activated by default, pass `null` as the fourth argument
|
* If you want accounts to be activated by default, pass `null` as the callback
|
||||||
*
|
*
|
||||||
* If you want to perform email verification, pass `function ($selector, $token) {}` as the fourth argument
|
* If you want to perform email verification, pass an anonymous function as the callback
|
||||||
|
*
|
||||||
|
* The callback function must have the following signature:
|
||||||
|
*
|
||||||
|
* `function ($selector, $token)`
|
||||||
|
*
|
||||||
|
* Both pieces of information must be sent to the user, usually embedded in a link
|
||||||
|
*
|
||||||
|
* When the user wants to verify their email address as a next step, both pieces will be required again
|
||||||
*
|
*
|
||||||
* @param string $email the email address to register
|
* @param string $email the email address to register
|
||||||
* @param string $password the password for the new account
|
* @param string $password the password for the new account
|
||||||
* @param string|null $username (optional) the username that will be displayed
|
* @param string|null $username (optional) the username that will be displayed
|
||||||
* @param callable|null $emailConfirmationCallback (optional) the function that sends the confirmation email
|
* @param callable|null $callback (optional) the function that sends the confirmation email to the user
|
||||||
* @return int the ID of the user that has been created (if any)
|
* @return int the ID of the user that has been created (if any)
|
||||||
* @throws InvalidEmailException if the email address was invalid
|
* @throws InvalidEmailException if the email address was invalid
|
||||||
* @throws InvalidPasswordException if the password was invalid
|
* @throws InvalidPasswordException if the password was invalid
|
||||||
* @throws UserAlreadyExistsException if a user with the specified email address already exists
|
* @throws UserAlreadyExistsException if a user with the specified email address already exists
|
||||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||||
*/
|
*/
|
||||||
public function register($email, $password, $username = null, callable $emailConfirmationCallback = null) {
|
public function register($email, $password, $username = null, callable $callback = null) {
|
||||||
$this->throttle(self::THROTTLE_ACTION_REGISTER);
|
$this->throttle(self::THROTTLE_ACTION_REGISTER);
|
||||||
|
|
||||||
$email = isset($email) ? trim($email) : null;
|
$email = self::validateEmailAddress($email);
|
||||||
if (empty($email)) {
|
$password = self::validatePassword($password);
|
||||||
throw new InvalidEmailException();
|
|
||||||
}
|
|
||||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
|
||||||
throw new InvalidEmailException();
|
|
||||||
}
|
|
||||||
|
|
||||||
$password = isset($password) ? trim($password) : null;
|
|
||||||
if (empty($password)) {
|
|
||||||
throw new InvalidPasswordException();
|
|
||||||
}
|
|
||||||
|
|
||||||
$username = isset($username) ? trim($username) : null;
|
$username = isset($username) ? trim($username) : null;
|
||||||
$password = password_hash($password, PASSWORD_DEFAULT);
|
$password = password_hash($password, PASSWORD_DEFAULT);
|
||||||
$verified = isset($emailConfirmationCallback) && is_callable($emailConfirmationCallback) ? 0 : 1;
|
$verified = isset($callback) && is_callable($callback) ? 0 : 1;
|
||||||
|
|
||||||
$stmt = $this->db->prepare("INSERT INTO users (email, password, username, verified, registered) VALUES (:email, :password, :username, :verified, :registered)");
|
|
||||||
$stmt->bindValue(':email', $email, \PDO::PARAM_STR);
|
|
||||||
$stmt->bindValue(':password', $password, \PDO::PARAM_STR);
|
|
||||||
$stmt->bindValue(':username', $username, \PDO::PARAM_STR);
|
|
||||||
$stmt->bindValue(':verified', $verified, \PDO::PARAM_INT);
|
|
||||||
$stmt->bindValue(':registered', time(), \PDO::PARAM_INT);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$result = $stmt->execute();
|
$this->db->insert(
|
||||||
|
'users',
|
||||||
|
[
|
||||||
|
'email' => $email,
|
||||||
|
'password' => $password,
|
||||||
|
'username' => $username,
|
||||||
|
'verified' => $verified,
|
||||||
|
'registered' => time()
|
||||||
|
]
|
||||||
|
);
|
||||||
}
|
}
|
||||||
catch (\PDOException $e) {
|
catch (IntegrityConstraintViolationException $e) {
|
||||||
// if we have a duplicate entry
|
// if we have a duplicate entry
|
||||||
if ($e->getCode() == '23000') {
|
|
||||||
throw new UserAlreadyExistsException();
|
throw new UserAlreadyExistsException();
|
||||||
}
|
}
|
||||||
// if we have another error
|
catch (Error $e) {
|
||||||
else {
|
|
||||||
// throw an exception
|
|
||||||
throw new DatabaseError(null, null, $e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// if creating the new user was successful
|
|
||||||
if ($result) {
|
|
||||||
// get the ID of the user that we've just created
|
|
||||||
$stmt = $this->db->prepare("SELECT id FROM users WHERE email = :email");
|
|
||||||
$stmt->bindValue(':email', $email, \PDO::PARAM_STR);
|
|
||||||
|
|
||||||
if ($result = $stmt->execute()) {
|
|
||||||
$newUserId = $stmt->fetchColumn();
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
$newUserId = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($verified === 1) {
|
|
||||||
return $newUserId;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
$this->createConfirmationRequest($email, $emailConfirmationCallback);
|
|
||||||
|
|
||||||
return $newUserId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
throw new DatabaseError();
|
throw new DatabaseError();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$newUserId = (int) $this->db->getLastInsertId();
|
||||||
|
|
||||||
|
if ($verified === 0) {
|
||||||
|
$this->createConfirmationRequest($email, $callback);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $newUserId;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a request for email confirmation
|
* Creates a request for email confirmation
|
||||||
*
|
*
|
||||||
|
* The callback function must have the following signature:
|
||||||
|
*
|
||||||
|
* `function ($selector, $token)`
|
||||||
|
*
|
||||||
|
* Both pieces of information must be sent to the user, usually embedded in a link
|
||||||
|
*
|
||||||
|
* When the user wants to verify their email address as a next step, both pieces will be required again
|
||||||
|
*
|
||||||
* @param string $email the email address to verify
|
* @param string $email the email address to verify
|
||||||
* @param callable $emailConfirmationCallback the function that sends the confirmation email
|
* @param callable $callback the function that sends the confirmation email to the user
|
||||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||||
*/
|
*/
|
||||||
private function createConfirmationRequest($email, callable $emailConfirmationCallback) {
|
private function createConfirmationRequest($email, callable $callback) {
|
||||||
$selector = self::createRandomString(16);
|
$selector = self::createRandomString(16);
|
||||||
$token = self::createRandomString(16);
|
$token = self::createRandomString(16);
|
||||||
$tokenHashed = password_hash($token, PASSWORD_DEFAULT);
|
$tokenHashed = password_hash($token, PASSWORD_DEFAULT);
|
||||||
$expires = time() + 3600 * 24;
|
$expires = time() + 3600 * 24;
|
||||||
|
|
||||||
$stmt = $this->db->prepare("INSERT INTO users_confirmations (email, selector, token, expires) VALUES (:email, :selector, :token, :expires)");
|
try {
|
||||||
$stmt->bindValue(':email', $email, \PDO::PARAM_STR);
|
$this->db->insert(
|
||||||
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
|
'users_confirmations',
|
||||||
$stmt->bindValue(':token', $tokenHashed, \PDO::PARAM_STR);
|
[
|
||||||
$stmt->bindValue(':expires', $expires, \PDO::PARAM_INT);
|
'email' => $email,
|
||||||
|
'selector' => $selector,
|
||||||
|
'token' => $tokenHashed,
|
||||||
|
'expires' => $expires
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (Error $e) {
|
||||||
|
throw new DatabaseError();
|
||||||
|
}
|
||||||
|
|
||||||
if ($stmt->execute()) {
|
if (isset($callback) && is_callable($callback)) {
|
||||||
if (isset($emailConfirmationCallback) && is_callable($emailConfirmationCallback)) {
|
$callback($selector, $token);
|
||||||
$emailConfirmationCallback($selector, $token);
|
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
throw new MissingCallbackError();
|
throw new MissingCallbackError();
|
||||||
}
|
}
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
throw new DatabaseError();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -251,29 +263,25 @@ class Auth {
|
|||||||
* @param string $password the user's password
|
* @param string $password the user's password
|
||||||
* @param bool $remember whether to keep the user logged in ("remember me") or not
|
* @param bool $remember whether to keep the user logged in ("remember me") or not
|
||||||
* @throws InvalidEmailException if the email address was invalid or could not be found
|
* @throws InvalidEmailException if the email address was invalid or could not be found
|
||||||
* @throws InvalidPasswordException if the password was invalid or didn't match the email address
|
* @throws InvalidPasswordException if the password was invalid
|
||||||
* @throws EmailNotVerifiedException if the email address has not been verified yet via confirmation email
|
* @throws EmailNotVerifiedException if the email address has not been verified yet via confirmation email
|
||||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||||
*/
|
*/
|
||||||
public function login($email, $password, $remember = false) {
|
public function login($email, $password, $remember = false) {
|
||||||
$email = isset($email) ? trim($email) : null;
|
$email = self::validateEmailAddress($email);
|
||||||
if (empty($email)) {
|
$password = self::validatePassword($password);
|
||||||
throw new InvalidEmailException();
|
|
||||||
|
try {
|
||||||
|
$userData = $this->db->selectRow(
|
||||||
|
'SELECT id, password, verified, username FROM users WHERE email = ?',
|
||||||
|
[ $email ]
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
catch (Error $e) {
|
||||||
throw new InvalidEmailException();
|
throw new DatabaseError();
|
||||||
}
|
}
|
||||||
|
|
||||||
$password = isset($password) ? trim($password) : null;
|
if (!empty($userData)) {
|
||||||
if (empty($password)) {
|
|
||||||
throw new InvalidPasswordException();
|
|
||||||
}
|
|
||||||
|
|
||||||
$stmt = $this->db->prepare("SELECT id, password, verified, username FROM users WHERE email = :email");
|
|
||||||
$stmt->bindValue(':email', $email, \PDO::PARAM_STR);
|
|
||||||
if ($stmt->execute()) {
|
|
||||||
$userData = $stmt->fetch(\PDO::FETCH_ASSOC);
|
|
||||||
if ($userData !== false) {
|
|
||||||
if (password_verify($password, $userData['password'])) {
|
if (password_verify($password, $userData['password'])) {
|
||||||
// if the password needs to be re-hashed to keep up with improving password cracking techniques
|
// if the password needs to be re-hashed to keep up with improving password cracking techniques
|
||||||
if (password_needs_rehash($userData['password'], PASSWORD_DEFAULT)) {
|
if (password_needs_rehash($userData['password'], PASSWORD_DEFAULT)) {
|
||||||
@@ -281,7 +289,7 @@ class Auth {
|
|||||||
$this->updatePassword($userData['id'], $password);
|
$this->updatePassword($userData['id'], $password);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($userData['verified'] == 1) {
|
if ($userData['verified'] === 1) {
|
||||||
$this->onLoginSuccessful($userData['id'], $email, $userData['username'], false);
|
$this->onLoginSuccessful($userData['id'], $email, $userData['username'], false);
|
||||||
|
|
||||||
if ($remember) {
|
if ($remember) {
|
||||||
@@ -308,9 +316,47 @@ class Auth {
|
|||||||
throw new InvalidEmailException();
|
throw new InvalidEmailException();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
|
||||||
throw new DatabaseError();
|
/**
|
||||||
|
* Validates an email address
|
||||||
|
*
|
||||||
|
* @param string $email the email address to validate
|
||||||
|
* @return string the email address if it's valid
|
||||||
|
* @throws InvalidEmailException if the email address was invalid
|
||||||
|
*/
|
||||||
|
private static function validateEmailAddress($email) {
|
||||||
|
if (empty($email)) {
|
||||||
|
throw new InvalidEmailException();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$email = trim($email);
|
||||||
|
|
||||||
|
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||||
|
throw new InvalidEmailException();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $email;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates a password
|
||||||
|
*
|
||||||
|
* @param string $password the password to validate
|
||||||
|
* @return string the password if it's valid
|
||||||
|
* @throws InvalidPasswordException if the password was invalid
|
||||||
|
*/
|
||||||
|
private static function validatePassword($password) {
|
||||||
|
if (empty($password)) {
|
||||||
|
throw new InvalidPasswordException();
|
||||||
|
}
|
||||||
|
|
||||||
|
$password = trim($password);
|
||||||
|
|
||||||
|
if (strlen($password) < 1) {
|
||||||
|
throw new InvalidPasswordException();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $password;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -325,20 +371,22 @@ class Auth {
|
|||||||
$tokenHashed = password_hash($token, PASSWORD_DEFAULT);
|
$tokenHashed = password_hash($token, PASSWORD_DEFAULT);
|
||||||
$expires = time() + 3600 * 24 * 28;
|
$expires = time() + 3600 * 24 * 28;
|
||||||
|
|
||||||
$stmt = $this->db->prepare("INSERT INTO users_remembered (user, selector, token, expires) VALUES (:user, :selector, :token, :expires)");
|
try {
|
||||||
$stmt->bindValue(':user', $userId, \PDO::PARAM_INT);
|
$this->db->insert(
|
||||||
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
|
'users_remembered',
|
||||||
$stmt->bindValue(':token', $tokenHashed, \PDO::PARAM_STR);
|
[
|
||||||
$stmt->bindValue(':expires', $expires, \PDO::PARAM_INT);
|
'user' => $userId,
|
||||||
|
'selector' => $selector,
|
||||||
if ($stmt->execute()) {
|
'token' => $tokenHashed,
|
||||||
$this->setRememberCookie($selector, $token, $expires);
|
'expires' => $expires
|
||||||
|
]
|
||||||
return;
|
);
|
||||||
}
|
}
|
||||||
else {
|
catch (Error $e) {
|
||||||
throw new DatabaseError();
|
throw new DatabaseError();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$this->setRememberCookie($selector, $token, $expires);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -348,17 +396,17 @@ class Auth {
|
|||||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||||
*/
|
*/
|
||||||
private function deleteRememberDirective($userId) {
|
private function deleteRememberDirective($userId) {
|
||||||
$stmt = $this->db->prepare("DELETE FROM users_remembered WHERE user = :user");
|
try {
|
||||||
$stmt->bindValue(':user', $userId, \PDO::PARAM_INT);
|
$this->db->delete(
|
||||||
|
'users_remembered',
|
||||||
if ($stmt->execute()) {
|
[ 'user' => $userId ]
|
||||||
$this->setRememberCookie(null, null, time() - 3600);
|
);
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
else {
|
catch (Error $e) {
|
||||||
throw new DatabaseError();
|
throw new DatabaseError();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$this->setRememberCookie(null, null, time() - 3600);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -366,7 +414,7 @@ class Auth {
|
|||||||
*
|
*
|
||||||
* @param string $selector the selector from the selector/token pair
|
* @param string $selector the selector from the selector/token pair
|
||||||
* @param string $token the token from the selector/token pair
|
* @param string $token the token from the selector/token pair
|
||||||
* @param int $expires timestamp (in seconds) when the token expires
|
* @param int $expires the interval in seconds after which the token should expire
|
||||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||||
*/
|
*/
|
||||||
private function setRememberCookie($selector, $token, $expires) {
|
private function setRememberCookie($selector, $token, $expires) {
|
||||||
@@ -381,7 +429,7 @@ class Auth {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// set the cookie with the selector and token
|
// set the cookie with the selector and token
|
||||||
$cookie = new \Delight\Cookie\Cookie(self::COOKIE_NAME_REMEMBER);
|
$cookie = new Cookie(self::COOKIE_NAME_REMEMBER);
|
||||||
$cookie->setValue($content);
|
$cookie->setValue($content);
|
||||||
$cookie->setExpiryTime($expires);
|
$cookie->setExpiryTime($expires);
|
||||||
if (!empty($params['path'])) {
|
if (!empty($params['path'])) {
|
||||||
@@ -406,15 +454,22 @@ class Auth {
|
|||||||
* @param string $email the email address 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 string $username the username (if any)
|
||||||
* @param bool $remembered whether the user was remembered ("remember me") or logged in actively
|
* @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, $remembered) {
|
private function onLoginSuccessful($userId, $email, $username, $remembered) {
|
||||||
$stmt = $this->db->prepare("UPDATE users SET last_login = :lastLogin WHERE id = :id");
|
try {
|
||||||
$stmt->bindValue(':lastLogin', time(), \PDO::PARAM_INT);
|
$this->db->update(
|
||||||
$stmt->bindValue(':id', $userId, \PDO::PARAM_INT);
|
'users',
|
||||||
$stmt->execute();
|
[ 'last_login' => time() ],
|
||||||
|
[ 'id' => $userId ]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (Error $e) {
|
||||||
|
throw new DatabaseError();
|
||||||
|
}
|
||||||
|
|
||||||
// re-generate the session ID to prevent session fixation attacks
|
// re-generate the session ID to prevent session fixation attacks
|
||||||
\Delight\Cookie\Session::regenerate(true);
|
Session::regenerate(true);
|
||||||
|
|
||||||
// save the user data in the session
|
// save the user data in the session
|
||||||
$this->setLoggedIn(true);
|
$this->setLoggedIn(true);
|
||||||
@@ -461,7 +516,7 @@ class Auth {
|
|||||||
$params = $this->createCookieSettings();
|
$params = $this->createCookieSettings();
|
||||||
|
|
||||||
// cause the session cookie to be deleted
|
// cause the session cookie to be deleted
|
||||||
$cookie = new \Delight\Cookie\Cookie(session_name());
|
$cookie = new Cookie(session_name());
|
||||||
if (!empty($params['path'])) {
|
if (!empty($params['path'])) {
|
||||||
$cookie->setPath($params['path']);
|
$cookie->setPath($params['path']);
|
||||||
}
|
}
|
||||||
@@ -489,30 +544,40 @@ class Auth {
|
|||||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||||
*/
|
*/
|
||||||
public function confirmEmail($selector, $token) {
|
public function confirmEmail($selector, $token) {
|
||||||
$this->throttle(self::THROTTLE_ACTION_CONFIRM_EMAIL);
|
$this->throttle(self::THROTTLE_ACTION_CONSUME_TOKEN);
|
||||||
$this->throttle(self::THROTTLE_ACTION_CONFIRM_EMAIL, $selector);
|
$this->throttle(self::THROTTLE_ACTION_CONSUME_TOKEN, $selector);
|
||||||
|
|
||||||
$stmt = $this->db->prepare("SELECT id, email, token, expires FROM users_confirmations WHERE selector = :selector");
|
try {
|
||||||
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
|
$confirmationData = $this->db->selectRow(
|
||||||
if ($stmt->execute()) {
|
'SELECT id, email, token, expires FROM users_confirmations WHERE selector = ?',
|
||||||
$confirmationData = $stmt->fetch(\PDO::FETCH_ASSOC);
|
[ $selector ]
|
||||||
if ($confirmationData !== false) {
|
);
|
||||||
if (password_verify($token, $confirmationData['token'])) {
|
|
||||||
if ($confirmationData['expires'] >= time()) {
|
|
||||||
$stmt = $this->db->prepare("UPDATE users SET verified = :verified WHERE email = :email");
|
|
||||||
$stmt->bindValue(':verified', 1, \PDO::PARAM_INT);
|
|
||||||
$stmt->bindValue(':email', $confirmationData['email'], \PDO::PARAM_STR);
|
|
||||||
if ($stmt->execute()) {
|
|
||||||
$stmt = $this->db->prepare("DELETE FROM users_confirmations WHERE id = :id");
|
|
||||||
$stmt->bindValue(':id', $confirmationData['id'], \PDO::PARAM_INT);
|
|
||||||
if ($stmt->execute()) {
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
else {
|
catch (Error $e) {
|
||||||
throw new DatabaseError();
|
throw new DatabaseError();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!empty($confirmationData)) {
|
||||||
|
if (password_verify($token, $confirmationData['token'])) {
|
||||||
|
if ($confirmationData['expires'] >= time()) {
|
||||||
|
try {
|
||||||
|
$this->db->update(
|
||||||
|
'users',
|
||||||
|
[ 'verified' => 1 ],
|
||||||
|
[ 'email' => $confirmationData['email'] ]
|
||||||
|
);
|
||||||
}
|
}
|
||||||
else {
|
catch (Error $e) {
|
||||||
|
throw new DatabaseError();
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$this->db->delete(
|
||||||
|
'users_confirmations',
|
||||||
|
[ 'id' => $confirmationData['id'] ]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (Error $e) {
|
||||||
throw new DatabaseError();
|
throw new DatabaseError();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -528,10 +593,6 @@ class Auth {
|
|||||||
throw new InvalidSelectorTokenPairException();
|
throw new InvalidSelectorTokenPairException();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
|
||||||
throw new DatabaseError();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Changes the (currently logged-in) user's password
|
* Changes the (currently logged-in) user's password
|
||||||
@@ -544,33 +605,31 @@ class Auth {
|
|||||||
*/
|
*/
|
||||||
public function changePassword($oldPassword, $newPassword) {
|
public function changePassword($oldPassword, $newPassword) {
|
||||||
if ($this->isLoggedIn()) {
|
if ($this->isLoggedIn()) {
|
||||||
$oldPassword = isset($oldPassword) ? trim($oldPassword) : null;
|
$oldPassword = self::validatePassword($oldPassword);
|
||||||
if (empty($oldPassword)) {
|
$newPassword = self::validatePassword($newPassword);
|
||||||
throw new InvalidPasswordException();
|
|
||||||
}
|
|
||||||
|
|
||||||
$newPassword = isset($newPassword) ? trim($newPassword) : null;
|
|
||||||
if (empty($newPassword)) {
|
|
||||||
throw new InvalidPasswordException();
|
|
||||||
}
|
|
||||||
|
|
||||||
$userId = $this->getUserId();
|
$userId = $this->getUserId();
|
||||||
|
|
||||||
$stmt = $this->db->prepare("SELECT password FROM users WHERE id = :userId");
|
try {
|
||||||
$stmt->bindValue(':userId', $userId, \PDO::PARAM_INT);
|
$passwordInDatabase = $this->db->selectValue(
|
||||||
if ($stmt->execute()) {
|
'SELECT password FROM users WHERE id = ?',
|
||||||
$passwordInDatabase = $stmt->fetchColumn();
|
[ $userId ]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (Error $e) {
|
||||||
|
throw new DatabaseError();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($passwordInDatabase)) {
|
||||||
if (password_verify($oldPassword, $passwordInDatabase)) {
|
if (password_verify($oldPassword, $passwordInDatabase)) {
|
||||||
$this->updatePassword($userId, $newPassword);
|
$this->updatePassword($userId, $newPassword);
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
throw new InvalidPasswordException();
|
throw new InvalidPasswordException();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
throw new DatabaseError();
|
throw new NotLoggedInException();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@@ -583,14 +642,258 @@ class Auth {
|
|||||||
*
|
*
|
||||||
* @param int $userId the ID of the user whose password should be updated
|
* @param int $userId the ID of the user whose password should be updated
|
||||||
* @param string $newPassword the new password
|
* @param string $newPassword the new password
|
||||||
|
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||||
*/
|
*/
|
||||||
private function updatePassword($userId, $newPassword) {
|
private function updatePassword($userId, $newPassword) {
|
||||||
$newPassword = password_hash($newPassword, PASSWORD_DEFAULT);
|
$newPassword = password_hash($newPassword, PASSWORD_DEFAULT);
|
||||||
|
|
||||||
$stmt = $this->db->prepare("UPDATE users SET password = :password WHERE id = :userId");
|
try {
|
||||||
$stmt->bindValue(':password', $newPassword, \PDO::PARAM_STR);
|
$this->db->update(
|
||||||
$stmt->bindValue(':userId', $userId, \PDO::PARAM_INT);
|
'users',
|
||||||
$stmt->execute();
|
[ 'password' => $newPassword ],
|
||||||
|
[ 'id' => $userId ]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (Error $e) {
|
||||||
|
throw new DatabaseError();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initiates a password reset request for the user with the specified email address
|
||||||
|
*
|
||||||
|
* The callback function must have the following signature:
|
||||||
|
*
|
||||||
|
* `function ($selector, $token)`
|
||||||
|
*
|
||||||
|
* Both pieces of information must be sent to the user, usually embedded in a link
|
||||||
|
*
|
||||||
|
* When the user wants to proceed to the second step of the password reset, both pieces will be required again
|
||||||
|
*
|
||||||
|
* @param string $email the email address of the user who wants to request the password reset
|
||||||
|
* @param callable $callback the function that sends the password reset information to the user
|
||||||
|
* @param int|null $requestExpiresAfter (optional) the interval in seconds after which the request should expire
|
||||||
|
* @param int|null $maxOpenRequests (optional) the maximum number of unexpired and unused requests per user
|
||||||
|
* @throws InvalidEmailException if the email address was invalid or could not be found
|
||||||
|
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
|
||||||
|
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||||
|
*/
|
||||||
|
public function forgotPassword($email, callable $callback, $requestExpiresAfter = null, $maxOpenRequests = null) {
|
||||||
|
$email = self::validateEmailAddress($email);
|
||||||
|
|
||||||
|
if ($requestExpiresAfter === null) {
|
||||||
|
// use six hours as the default
|
||||||
|
$requestExpiresAfter = 60 * 60 * 6;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
$requestExpiresAfter = (int) $requestExpiresAfter;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($maxOpenRequests === null) {
|
||||||
|
// use two requests per user as the default
|
||||||
|
$maxOpenRequests = 2;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
$maxOpenRequests = (int) $maxOpenRequests;
|
||||||
|
}
|
||||||
|
|
||||||
|
$userId = $this->getUserIdByEmailAddress($email);
|
||||||
|
$openRequests = (int) $this->getOpenPasswordResetRequests($userId);
|
||||||
|
|
||||||
|
if ($openRequests < $maxOpenRequests) {
|
||||||
|
$this->createPasswordResetRequest($userId, $requestExpiresAfter, $callback);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
self::onTooManyRequests($requestExpiresAfter);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the user ID for the account with the specified email address (if any)
|
||||||
|
*
|
||||||
|
* @param string $email the email address to look for
|
||||||
|
* @return string the user ID (if an account was found)
|
||||||
|
* @throws InvalidEmailException if the email address could not be found
|
||||||
|
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||||
|
*/
|
||||||
|
private function getUserIdByEmailAddress($email) {
|
||||||
|
try {
|
||||||
|
$userId = $this->db->selectValue(
|
||||||
|
'SELECT id FROM users WHERE email = ?',
|
||||||
|
[ $email ]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (Error $e) {
|
||||||
|
throw new DatabaseError();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($userId)) {
|
||||||
|
return $userId;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
throw new InvalidEmailException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the number of open requests for a password reset by the specified user
|
||||||
|
*
|
||||||
|
* @param int $userId the ID of the user to check the requests for
|
||||||
|
* @return int the number of open requests for a password reset
|
||||||
|
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||||
|
*/
|
||||||
|
private function getOpenPasswordResetRequests($userId) {
|
||||||
|
try {
|
||||||
|
$requests = $this->db->selectValue(
|
||||||
|
'SELECT COUNT(*) FROM users_resets WHERE user = ? AND expires > ?',
|
||||||
|
[
|
||||||
|
$userId,
|
||||||
|
time()
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!empty($requests)) {
|
||||||
|
return $requests;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Error $e) {
|
||||||
|
throw new DatabaseError();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new password reset request
|
||||||
|
*
|
||||||
|
* The callback function must have the following signature:
|
||||||
|
*
|
||||||
|
* `function ($selector, $token)`
|
||||||
|
*
|
||||||
|
* Both pieces of information must be sent to the user, usually embedded in a link
|
||||||
|
*
|
||||||
|
* When the user wants to proceed to the second step of the password reset, both pieces will be required again
|
||||||
|
*
|
||||||
|
* @param int $userId the ID of the user who requested the reset
|
||||||
|
* @param int $expiresAfter the interval in seconds after which the request should expire
|
||||||
|
* @param callable $callback the function that sends the password reset information to the user
|
||||||
|
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||||
|
*/
|
||||||
|
private function createPasswordResetRequest($userId, $expiresAfter, callable $callback) {
|
||||||
|
$selector = self::createRandomString(20);
|
||||||
|
$token = self::createRandomString(20);
|
||||||
|
$tokenHashed = password_hash($token, PASSWORD_DEFAULT);
|
||||||
|
$expiresAt = time() + $expiresAfter;
|
||||||
|
|
||||||
|
try {
|
||||||
|
$this->db->insert(
|
||||||
|
'users_resets',
|
||||||
|
[
|
||||||
|
'user' => $userId,
|
||||||
|
'selector' => $selector,
|
||||||
|
'token' => $tokenHashed,
|
||||||
|
'expires' => $expiresAt
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (Error $e) {
|
||||||
|
throw new DatabaseError();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($callback) && is_callable($callback)) {
|
||||||
|
$callback($selector, $token);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
throw new MissingCallbackError();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resets the password for a particular account by supplying the correct selector/token pair
|
||||||
|
*
|
||||||
|
* The selector/token pair must have been generated previously by calling `Auth#forgotPassword(...)`
|
||||||
|
*
|
||||||
|
* @param string $selector the selector from the selector/token pair
|
||||||
|
* @param string $token the token from the selector/token pair
|
||||||
|
* @param string $newPassword the new password to set for the account
|
||||||
|
* @throws InvalidSelectorTokenPairException if either the selector or the token was not correct
|
||||||
|
* @throws TokenExpiredException if the token has already expired
|
||||||
|
* @throws InvalidPasswordException if the new password was invalid
|
||||||
|
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
|
||||||
|
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||||
|
*/
|
||||||
|
public function resetPassword($selector, $token, $newPassword) {
|
||||||
|
$this->throttle(self::THROTTLE_ACTION_CONSUME_TOKEN);
|
||||||
|
$this->throttle(self::THROTTLE_ACTION_CONSUME_TOKEN, $selector);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$resetData = $this->db->selectRow(
|
||||||
|
'SELECT id, user, token, expires FROM users_resets WHERE selector = ?',
|
||||||
|
[ $selector ]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (Error $e) {
|
||||||
|
throw new DatabaseError();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($resetData)) {
|
||||||
|
if (password_verify($token, $resetData['token'])) {
|
||||||
|
if ($resetData['expires'] >= time()) {
|
||||||
|
$newPassword = self::validatePassword($newPassword);
|
||||||
|
|
||||||
|
$this->updatePassword($resetData['user'], $newPassword);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$this->db->delete(
|
||||||
|
'users_resets',
|
||||||
|
[ 'id' => $resetData['id'] ]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (Error $e) {
|
||||||
|
throw new DatabaseError();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
throw new TokenExpiredException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
throw new InvalidSelectorTokenPairException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
throw new InvalidSelectorTokenPairException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the supplied selector/token pair can be used to reset a password
|
||||||
|
*
|
||||||
|
* The selector/token pair must have been generated previously by calling `Auth#forgotPassword(...)`
|
||||||
|
*
|
||||||
|
* @param string $selector the selector from the selector/token pair
|
||||||
|
* @param string $token the token from the selector/token pair
|
||||||
|
* @return bool whether the password can be reset using the supplied information
|
||||||
|
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||||
|
*/
|
||||||
|
public function canResetPassword($selector, $token) {
|
||||||
|
try {
|
||||||
|
// pass an invalid password intentionally to force an expected error
|
||||||
|
$this->resetPassword($selector, $token, null);
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -774,50 +1077,79 @@ class Auth {
|
|||||||
// get the time bucket that we do the throttling for
|
// get the time bucket that we do the throttling for
|
||||||
$timeBucket = self::getTimeBucket();
|
$timeBucket = self::getTimeBucket();
|
||||||
|
|
||||||
$stmt = $this->db->prepare('INSERT INTO users_throttling (action_type, selector, time_bucket, attempts) VALUES (:actionType, :selector, :timeBucket, 1)');
|
|
||||||
$stmt->bindValue(':actionType', $actionType, \PDO::PARAM_STR);
|
|
||||||
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
|
|
||||||
$stmt->bindValue(':timeBucket', $timeBucket, \PDO::PARAM_INT);
|
|
||||||
try {
|
try {
|
||||||
$stmt->execute();
|
$this->db->insert(
|
||||||
|
'users_throttling',
|
||||||
|
[
|
||||||
|
'action_type' => $actionType,
|
||||||
|
'selector' => $selector,
|
||||||
|
'time_bucket' => $timeBucket,
|
||||||
|
'attempts' => 1
|
||||||
|
]
|
||||||
|
);
|
||||||
}
|
}
|
||||||
catch (\PDOException $e) {
|
catch (IntegrityConstraintViolationException $e) {
|
||||||
// if we have a duplicate entry
|
// if we have a duplicate entry, update the old entry
|
||||||
if ($e->getCode() == '23000') {
|
try {
|
||||||
// update the old entry
|
$this->db->exec(
|
||||||
$stmt = $this->db->prepare('UPDATE users_throttling SET attempts = attempts+1 WHERE action_type = :actionType AND selector = :selector AND time_bucket = :timeBucket');
|
'UPDATE users_throttling SET attempts = attempts+1 WHERE action_type = ? AND selector = ? AND time_bucket = ?',
|
||||||
$stmt->bindValue(':actionType', $actionType, \PDO::PARAM_STR);
|
[
|
||||||
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
|
$actionType,
|
||||||
$stmt->bindValue(':timeBucket', $timeBucket, \PDO::PARAM_INT);
|
$selector,
|
||||||
$stmt->execute();
|
$timeBucket
|
||||||
|
]
|
||||||
|
);
|
||||||
}
|
}
|
||||||
// if we have another error
|
catch (Error $e) {
|
||||||
else {
|
throw new DatabaseError();
|
||||||
// throw an exception
|
|
||||||
throw new DatabaseError(null, null, $e);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
catch (Error $e) {
|
||||||
|
throw new DatabaseError();
|
||||||
|
}
|
||||||
|
|
||||||
$stmt = $this->db->prepare('SELECT attempts FROM users_throttling WHERE action_type = :actionType AND selector = :selector AND time_bucket = :timeBucket');
|
try {
|
||||||
$stmt->bindValue(':actionType', $actionType, \PDO::PARAM_STR);
|
$attempts = $this->db->selectValue(
|
||||||
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
|
'SELECT attempts FROM users_throttling WHERE action_type = ? AND selector = ? AND time_bucket = ?',
|
||||||
$stmt->bindValue(':timeBucket', $timeBucket, \PDO::PARAM_INT);
|
[
|
||||||
if ($stmt->execute()) {
|
$actionType,
|
||||||
$attempts = $stmt->fetchColumn();
|
$selector,
|
||||||
|
$timeBucket
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (Error $e) {
|
||||||
|
throw new DatabaseError();
|
||||||
|
}
|
||||||
|
|
||||||
if ($attempts !== false) {
|
if (!empty($attempts)) {
|
||||||
// if the number of attempts has acceeded our accepted limit
|
// if the number of attempts has acceeded our accepted limit
|
||||||
if ($attempts > $this->throttlingActionsPerTimeBucket) {
|
if ($attempts > $this->throttlingActionsPerTimeBucket) {
|
||||||
// send a HTTP status code that indicates active throttling
|
self::onTooManyRequests($this->throttlingTimeBucketSize);
|
||||||
http_response_code(self::THROTTLE_HTTP_RESPONSE_CODE);
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called when there have been too many requests for some action or object
|
||||||
|
*
|
||||||
|
* @param int|null $retryAfterInterval (optional) the interval in seconds after which the client should retry
|
||||||
|
* @throws TooManyRequestsException to inform any calling method about this problem
|
||||||
|
*/
|
||||||
|
private static function onTooManyRequests($retryAfterInterval = null) {
|
||||||
|
// if no interval has been provided after which the client should retry
|
||||||
|
if ($retryAfterInterval === null) {
|
||||||
|
// use one day as the default
|
||||||
|
$retryAfterInterval = 60 * 60 * 24;
|
||||||
|
}
|
||||||
|
|
||||||
|
// send an appropriate HTTP status code
|
||||||
|
http_response_code(self::HTTP_STATUS_CODE_TOO_MANY_REQUESTS);
|
||||||
// tell the client when they should try again
|
// tell the client when they should try again
|
||||||
@header('Retry-After: '.$this->throttlingTimeBucketSize);
|
@header('Retry-After: '.$retryAfterInterval);
|
||||||
// throw an exception
|
// throw an exception
|
||||||
throw new TooManyRequestsException();
|
throw new TooManyRequestsException();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Customizes the throttling options
|
* Customizes the throttling options
|
||||||
|
@@ -20,7 +20,6 @@ header('Content-type: text/html; charset=utf-8');
|
|||||||
require __DIR__.'/../vendor/autoload.php';
|
require __DIR__.'/../vendor/autoload.php';
|
||||||
|
|
||||||
$db = new PDO('mysql:dbname=php_auth;host=127.0.0.1;charset=utf8mb4', 'root', '');
|
$db = new PDO('mysql:dbname=php_auth;host=127.0.0.1;charset=utf8mb4', 'root', '');
|
||||||
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
|
||||||
|
|
||||||
$auth = new \Delight\Auth\Auth($db);
|
$auth = new \Delight\Auth\Auth($db);
|
||||||
|
|
||||||
@@ -109,6 +108,50 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
|||||||
return 'too many requests';
|
return 'too many requests';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
else if ($_POST['action'] === 'forgotPassword') {
|
||||||
|
try {
|
||||||
|
$auth->forgotPassword($_POST['email'], function ($selector, $token) {
|
||||||
|
echo '<pre>';
|
||||||
|
echo 'Password reset';
|
||||||
|
echo "\n";
|
||||||
|
echo ' > Selector';
|
||||||
|
echo "\t\t\t\t";
|
||||||
|
echo htmlspecialchars($selector);
|
||||||
|
echo "\n";
|
||||||
|
echo ' > Token';
|
||||||
|
echo "\t\t\t\t";
|
||||||
|
echo htmlspecialchars($token);
|
||||||
|
echo '</pre>';
|
||||||
|
});
|
||||||
|
|
||||||
|
return 'ok';
|
||||||
|
}
|
||||||
|
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||||
|
return 'invalid email address';
|
||||||
|
}
|
||||||
|
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||||
|
return 'too many requests';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if ($_POST['action'] === 'resetPassword') {
|
||||||
|
try {
|
||||||
|
$auth->resetPassword($_POST['selector'], $_POST['token'], $_POST['password']);
|
||||||
|
|
||||||
|
return 'ok';
|
||||||
|
}
|
||||||
|
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
|
||||||
|
return 'invalid token';
|
||||||
|
}
|
||||||
|
catch (\Delight\Auth\TokenExpiredException $e) {
|
||||||
|
return 'token expired';
|
||||||
|
}
|
||||||
|
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||||
|
return 'invalid password';
|
||||||
|
}
|
||||||
|
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||||
|
return 'too many requests';
|
||||||
|
}
|
||||||
|
}
|
||||||
else if ($_POST['action'] === 'changePassword') {
|
else if ($_POST['action'] === 'changePassword') {
|
||||||
try {
|
try {
|
||||||
$auth->changePassword($_POST['oldPassword'], $_POST['newPassword']);
|
$auth->changePassword($_POST['oldPassword'], $_POST['newPassword']);
|
||||||
@@ -205,8 +248,8 @@ function showGuestUserForm() {
|
|||||||
echo '<input type="text" name="email" placeholder="Email" /> ';
|
echo '<input type="text" name="email" placeholder="Email" /> ';
|
||||||
echo '<input type="text" name="password" placeholder="Password" /> ';
|
echo '<input type="text" name="password" placeholder="Password" /> ';
|
||||||
echo '<select name="remember" size="1">';
|
echo '<select name="remember" size="1">';
|
||||||
echo '<option value="0">Remember? — No</option>';
|
echo '<option value="0">Remember (28 days)? — No</option>';
|
||||||
echo '<option value="1">Remember? — Yes</option>';
|
echo '<option value="1">Remember (28 days)? — Yes</option>';
|
||||||
echo '</select> ';
|
echo '</select> ';
|
||||||
echo '<button type="submit">Login</button>';
|
echo '<button type="submit">Login</button>';
|
||||||
echo '</form>';
|
echo '</form>';
|
||||||
@@ -229,4 +272,18 @@ function showGuestUserForm() {
|
|||||||
echo '<input type="text" name="token" placeholder="Token" /> ';
|
echo '<input type="text" name="token" placeholder="Token" /> ';
|
||||||
echo '<button type="submit">Confirm email</button>';
|
echo '<button type="submit">Confirm email</button>';
|
||||||
echo '</form>';
|
echo '</form>';
|
||||||
|
|
||||||
|
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 '<button type="submit">Forgot password</button>';
|
||||||
|
echo '</form>';
|
||||||
|
|
||||||
|
echo '<form action="" method="post" accept-charset="utf-8">';
|
||||||
|
echo '<input type="hidden" name="action" value="resetPassword" />';
|
||||||
|
echo '<input type="text" name="selector" placeholder="Selector" /> ';
|
||||||
|
echo '<input type="text" name="token" placeholder="Token" /> ';
|
||||||
|
echo '<input type="text" name="password" placeholder="New password" /> ';
|
||||||
|
echo '<button type="submit">Reset password</button>';
|
||||||
|
echo '</form>';
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user