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

18 Commits

Author SHA1 Message Date
Marco
d527a82bfa Update documentation to include guide on password reset 2016-08-20 22:02:18 +02:00
Marco
31ae135740 Add method 'canResetPassword' 2016-08-20 22:00:41 +02:00
Marco
c5e3bd191d Postpone validation of new password in 'Auth#resetPassword' 2016-08-20 21:48:53 +02:00
Marco
53e1a5c1fc Add method 'resetPassword' 2016-08-20 21:09:56 +02:00
Marco
f3ca69010f Add method 'forgotPassword' 2016-08-20 21:09:34 +02:00
Marco
da8d22c599 Create internal method 'Auth#createPasswordResetRequest' 2016-08-20 21:00:49 +02:00
Marco
c993657f20 Improve PHPDoc 2016-08-20 20:57:48 +02:00
Marco
cce172442d Rename constant 2016-08-20 20:57:00 +02:00
Marco
aef2672942 Refactor validation of passwords 2016-08-20 20:55:50 +02:00
Marco
e0b69ee33c Update database schema 2016-08-20 20:51:38 +02:00
Marco
40a5518ba7 Rename parameters 2016-08-20 20:42:54 +02:00
Marco
2441ea2dc1 Improve PHPDoc 2016-08-20 20:39:29 +02:00
Marco
07f60d6610 Improve PHPDoc 2016-08-20 18:24:14 +02:00
Marco
35cc941f20 Add internal method 'Auth#getOpenPasswordResetRequests' 2016-08-20 18:07:18 +02:00
Marco
f4b464a6f8 Add internal method 'Auth#getUserIdByEmailAddress' 2016-08-20 18:06:36 +02:00
Marco
bfa5b5e6b1 Refactor announcement of exceeded request limit to the client 2016-08-20 18:04:01 +02:00
Marco
9d2d764ced Refactor validation of email addresses 2016-08-20 17:05:47 +02:00
Marco
f45e0f1cb4 Explain 'remember me' feature more clearly 2016-07-25 12:06:14 +02:00
4 changed files with 467 additions and 61 deletions

View File

@@ -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` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`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` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`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,
`expires` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `selector` (`selector`),
KEY `user` (`user`)
KEY `user_expires` (`user`,`expires`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `users_throttling` (
@@ -52,3 +61,7 @@ CREATE TABLE IF NOT EXISTS `users_throttling` (
PRIMARY KEY (`id`),
UNIQUE KEY `action_type_selector_time_bucket` (`action_type`,`selector`,`time_bucket`)
) 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 */;

View File

@@ -113,7 +113,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
@@ -136,6 +140,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
If a user is currently logged in, they may change their password.
@@ -250,7 +313,7 @@ $uuid = \Delight\Auth\Auth::createUuid();
* customizable password requirements and enforcement
* optional usernames with customizable restrictions
* 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
* change password
* tracking the time of sign up and last login

View File

@@ -24,8 +24,8 @@ class Auth {
const IP_ADDRESS_HASH_ALGORITHM = 'sha256';
const THROTTLE_ACTION_LOGIN = 'login';
const THROTTLE_ACTION_REGISTER = 'register';
const THROTTLE_ACTION_CONFIRM_EMAIL = 'confirm_email';
const THROTTLE_HTTP_RESPONSE_CODE = 429;
const THROTTLE_ACTION_CONSUME_TOKEN = 'confirm_email';
const HTTP_STATUS_CODE_TOO_MANY_REQUESTS = 429;
/** @var \PDO the database connection that will be used */
private $db;
@@ -127,39 +127,37 @@ class Auth {
/**
* 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 $password the password for the new account
* @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)
* @throws InvalidEmailException if the email address was invalid
* @throws InvalidPasswordException if the password was invalid
* @throws UserAlreadyExistsException if a user with the specified email address already exists
* @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);
$email = isset($email) ? trim($email) : null;
if (empty($email)) {
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();
}
$email = self::validateEmailAddress($email);
$password = self::validatePassword($password);
$username = isset($username) ? trim($username) : null;
$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);
@@ -200,7 +198,7 @@ class Auth {
return $newUserId;
}
else {
$this->createConfirmationRequest($email, $emailConfirmationCallback);
$this->createConfirmationRequest($email, $callback);
return $newUserId;
}
@@ -213,11 +211,19 @@ class Auth {
/**
* 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 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)
*/
private function createConfirmationRequest($email, callable $emailConfirmationCallback) {
private function createConfirmationRequest($email, callable $callback) {
$selector = self::createRandomString(16);
$token = self::createRandomString(16);
$tokenHashed = password_hash($token, PASSWORD_DEFAULT);
@@ -230,8 +236,8 @@ class Auth {
$stmt->bindValue(':expires', $expires, \PDO::PARAM_INT);
if ($stmt->execute()) {
if (isset($emailConfirmationCallback) && is_callable($emailConfirmationCallback)) {
$emailConfirmationCallback($selector, $token);
if (isset($callback) && is_callable($callback)) {
$callback($selector, $token);
}
else {
throw new MissingCallbackError();
@@ -251,23 +257,13 @@ class Auth {
* @param string $password the user's password
* @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 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 AuthError if an internal problem occurred (do *not* catch)
*/
public function login($email, $password, $remember = false) {
$email = isset($email) ? trim($email) : null;
if (empty($email)) {
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();
}
$email = self::validateEmailAddress($email);
$password = self::validatePassword($password);
$stmt = $this->db->prepare("SELECT id, password, verified, username FROM users WHERE email = :email");
$stmt->bindValue(':email', $email, \PDO::PARAM_STR);
@@ -313,6 +309,48 @@ class Auth {
}
}
/**
* 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;
}
/**
* Creates a new directive keeping the user logged in ("remember me")
*
@@ -366,7 +404,7 @@ class Auth {
*
* @param string $selector the selector 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)
*/
private function setRememberCookie($selector, $token, $expires) {
@@ -489,8 +527,8 @@ class Auth {
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
public function confirmEmail($selector, $token) {
$this->throttle(self::THROTTLE_ACTION_CONFIRM_EMAIL);
$this->throttle(self::THROTTLE_ACTION_CONFIRM_EMAIL, $selector);
$this->throttle(self::THROTTLE_ACTION_CONSUME_TOKEN);
$this->throttle(self::THROTTLE_ACTION_CONSUME_TOKEN, $selector);
$stmt = $this->db->prepare("SELECT id, email, token, expires FROM users_confirmations WHERE selector = :selector");
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
@@ -544,15 +582,8 @@ class Auth {
*/
public function changePassword($oldPassword, $newPassword) {
if ($this->isLoggedIn()) {
$oldPassword = isset($oldPassword) ? trim($oldPassword) : null;
if (empty($oldPassword)) {
throw new InvalidPasswordException();
}
$newPassword = isset($newPassword) ? trim($newPassword) : null;
if (empty($newPassword)) {
throw new InvalidPasswordException();
}
$oldPassword = self::validatePassword($oldPassword);
$newPassword = self::validatePassword($newPassword);
$userId = $this->getUserId();
@@ -593,6 +624,231 @@ class Auth {
$stmt->execute();
}
/**
* 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) {
$stmt = $this->db->prepare("SELECT id FROM users WHERE email = :email");
$stmt->bindValue(':email', $email, \PDO::PARAM_STR);
if ($stmt->execute()) {
$userId = $stmt->fetchColumn();
if ($userId !== false) {
return $userId;
}
else {
throw new InvalidEmailException();
}
}
else {
throw new DatabaseError();
}
}
/**
* 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) {
$stmt = $this->db->prepare("SELECT COUNT(*) FROM users_resets WHERE user = :userId AND expires > :expiresAfter");
$stmt->bindValue(':userId', $userId, \PDO::PARAM_INT);
$stmt->bindValue(':expiresAfter', time(), \PDO::PARAM_INT);
if ($stmt->execute()) {
return $stmt->fetchColumn();
}
else {
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;
$stmt = $this->db->prepare("INSERT INTO users_resets (user, selector, token, expires) VALUES (:userId, :selector, :token, :expires)");
$stmt->bindValue(':userId', $userId, \PDO::PARAM_INT);
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
$stmt->bindValue(':token', $tokenHashed, \PDO::PARAM_STR);
$stmt->bindValue(':expires', $expiresAt, \PDO::PARAM_INT);
if ($stmt->execute()) {
if (isset($callback) && is_callable($callback)) {
$callback($selector, $token);
}
else {
throw new MissingCallbackError();
}
return;
}
else {
throw new DatabaseError();
}
}
/**
* 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);
$stmt = $this->db->prepare("SELECT id, user, token, expires FROM users_resets WHERE selector = :selector");
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
if ($stmt->execute()) {
$resetData = $stmt->fetch(\PDO::FETCH_ASSOC);
if ($resetData !== false) {
if (password_verify($token, $resetData['token'])) {
if ($resetData['expires'] >= time()) {
$newPassword = self::validatePassword($newPassword);
$this->updatePassword($resetData['user'], $newPassword);
$stmt = $this->db->prepare("DELETE FROM users_resets WHERE id = :id");
$stmt->bindValue(':id', $resetData['id'], \PDO::PARAM_INT);
if ($stmt->execute()) {
return;
}
else {
throw new DatabaseError();
}
}
else {
throw new TokenExpiredException();
}
}
else {
throw new InvalidSelectorTokenPairException();
}
}
else {
throw new InvalidSelectorTokenPairException();
}
}
else {
throw new DatabaseError();
}
}
/**
* 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;
}
}
/**
* Sets whether the user is currently logged in and updates the session
*
@@ -808,17 +1064,33 @@ class Auth {
if ($attempts !== false) {
// if the number of attempts has acceeded our accepted limit
if ($attempts > $this->throttlingActionsPerTimeBucket) {
// send a HTTP status code that indicates active throttling
http_response_code(self::THROTTLE_HTTP_RESPONSE_CODE);
// tell the client when they should try again
@header('Retry-After: '.$this->throttlingTimeBucketSize);
// throw an exception
throw new TooManyRequestsException();
self::onTooManyRequests($this->throttlingTimeBucketSize);
}
}
}
}
/**
* 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
@header('Retry-After: '.$retryAfterInterval);
// throw an exception
throw new TooManyRequestsException();
}
/**
* Customizes the throttling options
*

View File

@@ -109,6 +109,50 @@ function processRequestData(\Delight\Auth\Auth $auth) {
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') {
try {
$auth->changePassword($_POST['oldPassword'], $_POST['newPassword']);
@@ -205,8 +249,8 @@ function showGuestUserForm() {
echo '<input type="text" name="email" placeholder="Email" /> ';
echo '<input type="text" name="password" placeholder="Password" /> ';
echo '<select name="remember" size="1">';
echo '<option value="0">Remember? — No</option>';
echo '<option value="1">Remember? — Yes</option>';
echo '<option value="0">Remember (28 days)? — No</option>';
echo '<option value="1">Remember (28 days)? — Yes</option>';
echo '</select> ';
echo '<button type="submit">Login</button>';
echo '</form>';
@@ -229,4 +273,18 @@ function showGuestUserForm() {
echo '<input type="text" name="token" placeholder="Token" /> ';
echo '<button type="submit">Confirm email</button>';
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>';
}