mirror of
https://github.com/delight-im/PHP-Auth.git
synced 2025-08-07 00:26:28 +02:00
Compare commits
21 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
d527a82bfa | ||
|
31ae135740 | ||
|
c5e3bd191d | ||
|
53e1a5c1fc | ||
|
f3ca69010f | ||
|
da8d22c599 | ||
|
c993657f20 | ||
|
cce172442d | ||
|
aef2672942 | ||
|
e0b69ee33c | ||
|
40a5518ba7 | ||
|
2441ea2dc1 | ||
|
07f60d6610 | ||
|
35cc941f20 | ||
|
f4b464a6f8 | ||
|
bfa5b5e6b1 | ||
|
9d2d764ced | ||
|
f45e0f1cb4 | ||
|
b9b6d46b4d | ||
|
ad2c338f6a | ||
|
1f8df61168 |
@@ -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 */;
|
||||
|
214
LICENSE
214
LICENSE
@@ -1,201 +1,21 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
The MIT License (MIT)
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
Copyright (c) delight.im (https://www.delight.im/)
|
||||
|
||||
1. Definitions.
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
57
Migration.md
57
Migration.md
@@ -1,35 +1,40 @@
|
||||
# Migration
|
||||
|
||||
* `v1.x.x` to `v2.x.x`
|
||||
* The MySQL schema has been changed from charset `utf8` to charset `utf8mb4` and from collation `utf8_general_ci` to collation `utf8mb4_unicode_ci`. Use the statements below to update the database schema:
|
||||
## From `v1.x.x` to `v2.x.x`
|
||||
|
||||
```sql
|
||||
ALTER TABLE `users` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
|
||||
ALTER TABLE `users_confirmations` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
|
||||
* The MySQL schema has been changed from charset `utf8` to charset `utf8mb4` and from collation `utf8_general_ci` to collation `utf8mb4_unicode_ci`. Use the statements below to update the database schema:
|
||||
|
||||
-- ALTER DATABASE `<DATABASE_NAME>` CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
|
||||
```sql
|
||||
ALTER TABLE `users` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
|
||||
ALTER TABLE `users_confirmations` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
|
||||
|
||||
ALTER TABLE `users` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
ALTER TABLE `users_confirmations` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
ALTER TABLE `users_remembered` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
ALTER TABLE `users_resets` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
ALTER TABLE `users_throttling` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
-- ALTER DATABASE `<DATABASE_NAME>` CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
|
||||
|
||||
ALTER TABLE `users` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
|
||||
ALTER TABLE `users` CHANGE `username` `username` VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL;
|
||||
ALTER TABLE `users` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
ALTER TABLE `users_confirmations` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
ALTER TABLE `users_remembered` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
ALTER TABLE `users_resets` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
ALTER TABLE `users_throttling` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
ALTER TABLE `users_confirmations` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
|
||||
ALTER TABLE `users` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
|
||||
ALTER TABLE `users` CHANGE `username` `username` VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL;
|
||||
|
||||
ALTER TABLE `users_throttling` CHANGE `action_type` `action_type` ENUM('login','register','confirm_email') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
|
||||
ALTER TABLE `users_confirmations` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
|
||||
|
||||
REPAIR TABLE users;
|
||||
OPTIMIZE TABLE users;
|
||||
REPAIR TABLE users_confirmations;
|
||||
OPTIMIZE TABLE users_confirmations;
|
||||
REPAIR TABLE users_remembered;
|
||||
OPTIMIZE TABLE users_remembered;
|
||||
REPAIR TABLE users_resets;
|
||||
OPTIMIZE TABLE users_resets;
|
||||
REPAIR TABLE users_throttling;
|
||||
OPTIMIZE TABLE users_throttling;
|
||||
```
|
||||
ALTER TABLE `users_throttling` CHANGE `action_type` `action_type` ENUM('login','register','confirm_email') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
|
||||
|
||||
REPAIR TABLE users;
|
||||
OPTIMIZE TABLE users;
|
||||
REPAIR TABLE users_confirmations;
|
||||
OPTIMIZE TABLE users_confirmations;
|
||||
REPAIR TABLE users_remembered;
|
||||
OPTIMIZE TABLE users_remembered;
|
||||
REPAIR TABLE users_resets;
|
||||
OPTIMIZE TABLE users_resets;
|
||||
REPAIR TABLE users_throttling;
|
||||
OPTIMIZE TABLE users_throttling;
|
||||
```
|
||||
|
||||
## 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).
|
||||
|
5
NOTICE
5
NOTICE
@@ -1,5 +0,0 @@
|
||||
PHP-Auth
|
||||
Copyright (c) delight.im <info@delight.im>
|
||||
|
||||
This product includes software developed by
|
||||
delight.im (http://www.delight.im/).
|
83
README.md
83
README.md
@@ -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
|
||||
@@ -301,18 +364,4 @@ All contributions are welcome! If you wish to contribute, please create an issue
|
||||
|
||||
## License
|
||||
|
||||
```
|
||||
Copyright (c) delight.im <info@delight.im>
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
```
|
||||
This project is licensed under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
||||
|
@@ -4,12 +4,12 @@
|
||||
"require": {
|
||||
"php": ">=5.5.0",
|
||||
"ext-openssl": "*",
|
||||
"delight-im/cookie": "^1.3"
|
||||
"delight-im/cookie": "^2.0"
|
||||
},
|
||||
"type": "library",
|
||||
"keywords": [ "auth", "authentication", "login", "security" ],
|
||||
"homepage": "https://github.com/delight-im/PHP-Auth",
|
||||
"license": "Apache-2.0",
|
||||
"license": "MIT",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Delight\\Auth\\": "src/"
|
||||
|
30
composer.lock
generated
30
composer.lock
generated
@@ -4,25 +4,25 @@
|
||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"hash": "32e4912115e164a1a86227d49db9ac29",
|
||||
"content-hash": "1a5c0056d726ae6195da0faa38f37fdd",
|
||||
"hash": "22e56875c7a1386807d5cf6ae01f50fa",
|
||||
"content-hash": "b914ccd7ac15e1519d7a04b55dbe725e",
|
||||
"packages": [
|
||||
{
|
||||
"name": "delight-im/cookie",
|
||||
"version": "v1.3.0",
|
||||
"version": "v2.0.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/delight-im/PHP-Cookie.git",
|
||||
"reference": "481c569d6f4bcb0391f56203f078d425b3339001"
|
||||
"reference": "a746f4096885b6715a640a2122b1c21324624f8f"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/delight-im/PHP-Cookie/zipball/481c569d6f4bcb0391f56203f078d425b3339001",
|
||||
"reference": "481c569d6f4bcb0391f56203f078d425b3339001",
|
||||
"url": "https://api.github.com/repos/delight-im/PHP-Cookie/zipball/a746f4096885b6715a640a2122b1c21324624f8f",
|
||||
"reference": "a746f4096885b6715a640a2122b1c21324624f8f",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"delight-im/http": "^1.1",
|
||||
"delight-im/http": "^2.0",
|
||||
"php": ">=5.3.0"
|
||||
},
|
||||
"type": "library",
|
||||
@@ -33,7 +33,7 @@
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"Apache-2.0"
|
||||
"MIT"
|
||||
],
|
||||
"description": "Modern cookie management for PHP",
|
||||
"homepage": "https://github.com/delight-im/PHP-Cookie",
|
||||
@@ -46,20 +46,20 @@
|
||||
"samesite",
|
||||
"xss"
|
||||
],
|
||||
"time": "2016-07-19 22:20:24"
|
||||
"time": "2016-07-21 15:20:20"
|
||||
},
|
||||
{
|
||||
"name": "delight-im/http",
|
||||
"version": "v1.1.0",
|
||||
"version": "v2.0.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/delight-im/PHP-HTTP.git",
|
||||
"reference": "2ca9001f047c8b4e1b7ca7281823a1a9437850f8"
|
||||
"reference": "0a19a72a7eac8b1301aa972fb20cff494ac43e09"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/delight-im/PHP-HTTP/zipball/2ca9001f047c8b4e1b7ca7281823a1a9437850f8",
|
||||
"reference": "2ca9001f047c8b4e1b7ca7281823a1a9437850f8",
|
||||
"url": "https://api.github.com/repos/delight-im/PHP-HTTP/zipball/0a19a72a7eac8b1301aa972fb20cff494ac43e09",
|
||||
"reference": "0a19a72a7eac8b1301aa972fb20cff494ac43e09",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -73,7 +73,7 @@
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"Apache-2.0"
|
||||
"MIT"
|
||||
],
|
||||
"description": "Hypertext Transfer Protocol (HTTP) utilities for PHP",
|
||||
"homepage": "https://github.com/delight-im/PHP-HTTP",
|
||||
@@ -82,7 +82,7 @@
|
||||
"http",
|
||||
"https"
|
||||
],
|
||||
"time": "2016-07-08 21:19:02"
|
||||
"time": "2016-07-21 15:05:01"
|
||||
}
|
||||
],
|
||||
"packages-dev": [],
|
||||
|
398
src/Auth.php
398
src/Auth.php
@@ -1,19 +1,9 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (c) delight.im <info@delight.im>
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* 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)
|
||||
*/
|
||||
|
||||
namespace Delight\Auth;
|
||||
@@ -34,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;
|
||||
@@ -137,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);
|
||||
@@ -210,7 +198,7 @@ class Auth {
|
||||
return $newUserId;
|
||||
}
|
||||
else {
|
||||
$this->createConfirmationRequest($email, $emailConfirmationCallback);
|
||||
$this->createConfirmationRequest($email, $callback);
|
||||
|
||||
return $newUserId;
|
||||
}
|
||||
@@ -223,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);
|
||||
@@ -240,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();
|
||||
@@ -261,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);
|
||||
@@ -323,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")
|
||||
*
|
||||
@@ -376,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) {
|
||||
@@ -499,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);
|
||||
@@ -554,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();
|
||||
|
||||
@@ -603,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
|
||||
*
|
||||
@@ -818,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
|
||||
*
|
||||
|
@@ -1,19 +1,9 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (c) delight.im <info@delight.im>
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* 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)
|
||||
*/
|
||||
|
||||
namespace Delight\Auth;
|
||||
|
@@ -1,19 +1,9 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (c) delight.im <info@delight.im>
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* 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)
|
||||
*/
|
||||
|
||||
namespace Delight\Auth;
|
||||
|
@@ -1,19 +1,9 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (c) delight.im <info@delight.im>
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* 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)
|
||||
*/
|
||||
|
||||
// enable error reporting
|
||||
@@ -119,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']);
|
||||
@@ -215,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>';
|
||||
@@ -239,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>';
|
||||
}
|
||||
|
Reference in New Issue
Block a user