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

47 Commits

Author SHA1 Message Date
Marco
36b590eb81 Update dependencies 2016-12-01 13:48:48 +01:00
Marco
5c6a71d921 Update migration guide 2016-09-15 23:52:24 +02:00
Marco
d94243f19d Update examples of how to provide a database connection 2016-09-15 23:51:29 +02:00
Marco
2a2d93f534 Improve exemplary database credentials 2016-09-15 23:45:35 +02:00
Marco
989c7940e5 Rewrite all SQL operations to use 'delight-im/db' instead of raw PDO 2016-09-15 23:43:40 +02:00
Marco
51a5735295 Require 'delight-im/db' as dependency 2016-09-14 16:54:54 +02:00
Marco
e5e465782b Update dependencies 2016-09-14 16:52:01 +02:00
Marco
83caa3e785 Improve list of requirements in README 2016-09-14 16:50:42 +02:00
Marco
f2a1aedf7a Change minimum required PHP version from 5.5.0 to 5.6.0 2016-09-14 16:49:13 +02:00
Marco
5c87e877db Import class 'Delight\Cookie\Session' 2016-09-14 16:42:52 +02:00
Marco
70842b4320 Import class 'Delight\Cookie\Cookie' 2016-09-14 16:42:00 +02:00
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
Marco
b9b6d46b4d Change the license from 'Apache License 2.0' to 'MIT License' 2016-07-21 17:42:31 +02:00
Marco
ad2c338f6a Re-format 'Migration.md' 2016-07-21 17:36:32 +02:00
Marco
1f8df61168 Update dependencies 2016-07-21 17:33:48 +02:00
Marco
ab55f7e562 Explain how to manage session data conveniently 2016-07-20 00:37:48 +02:00
Marco
e768243798 Update dependencies 2016-07-20 00:36:18 +02:00
Marco
27a3990472 Only throttle login attempts that have wrong credentials 2016-07-09 00:58:04 +02:00
Marco
1979799480 Improve cookie handling to fix domain issues and add same-site flag 2016-07-09 00:48:55 +02:00
Marco
fff4a59be5 Include 'delight-im/cookie' as dependency for cookie handling 2016-07-09 00:14:51 +02:00
Marco
122e2b8006 Add missing '+' 2016-06-07 19:04:31 +02:00
Marco
bebd3efce2 Use Composer autoloader for tests as well 2016-06-07 19:01:56 +02:00
Marco
00dc8c3158 Enable both error reporting and assertions in 'tests' 2016-06-07 18:48:50 +02:00
Marco
e074474955 Fix list of dependencies 2016-06-07 18:42:29 +02:00
Marco
44907f3489 Add 'NOTICE' 2016-04-02 22:25:14 +02:00
Marco
ea27e8b7d3 Remove trailing newline in 'LICENSE' 2016-04-02 22:24:51 +02:00
Marco
354b34a724 Add migration guide for switch from v1.x.x to v2.x.x 2016-02-24 01:00:23 +01:00
Marco
3e083f9f17 Update '.editorconfig' to indent with spaces in Markdown 2016-02-24 01:00:08 +01:00
Marco
227c37e2b5 Update MySQL database schema to ensure full Unicode support 2016-02-24 00:59:50 +01:00
Marco
5403270ed2 Always use 'bindValue' instead of 'bindParam' with PDO 2016-02-24 00:59:18 +01:00
12 changed files with 998 additions and 574 deletions

View File

@@ -7,3 +7,7 @@ indent_style = tab
trim_trailing_whitespace = true
end_of_line = lf
insert_final_newline = true
[*.md]
indent_style = space
indent_size = 4

5
.gitignore vendored
View File

@@ -1 +1,6 @@
# IntelliJ
.idea/
# Composer
vendor/
composer.phar

View File

@@ -1,25 +1,34 @@
-- 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(254) NOT NULL,
`email` varchar(249) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
`username` varchar(100) DEFAULT NULL,
`username` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`verified` tinyint(1) unsigned NOT NULL DEFAULT '0',
`registered` int(10) unsigned NOT NULL,
`last_login` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `users_confirmations` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(254) NOT NULL,
`email` varchar(249) COLLATE utf8mb4_unicode_ci NOT NULL,
`selector` varchar(16) 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 `email_expires` (`email`,`expires`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `users_remembered` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
@@ -30,25 +39,29 @@ CREATE TABLE IF NOT EXISTS `users_remembered` (
PRIMARY KEY (`id`),
UNIQUE KEY `selector` (`selector`),
KEY `user` (`user`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
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`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
KEY `user_expires` (`user`,`expires`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `users_throttling` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`action_type` enum('login','register','confirm_email') NOT NULL,
`action_type` enum('login','register','confirm_email') COLLATE utf8mb4_unicode_ci NOT NULL,
`selector` varchar(44) CHARACTER SET latin1 COLLATE latin1_general_cs DEFAULT NULL,
`time_bucket` int(10) unsigned NOT NULL,
`attempts` mediumint(8) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
UNIQUE KEY `action_type_selector_time_bucket` (`action_type`,`selector`,`time_bucket`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
) 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 */;

215
LICENSE
View File

@@ -1,202 +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.
"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 above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.

44
Migration.md Normal file
View File

@@ -0,0 +1,44 @@
# Migration
## From `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:
```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 DATABASE `<DATABASE_NAME>` CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
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` 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_confirmations` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
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).
## From `v3.x.x` to `v4.x.x`
* PHP 5.6.0 or higher is now required.

105
README.md
View File

@@ -16,9 +16,9 @@ Completely framework-agnostic and database-agnostic.
## Requirements
* PHP 5.5.0+
* PDO
* OpenSSL
* PHP 5.6.0+
* OpenSSL extension (`openssl`)
* MySQL 5.5.3+ **or** MariaDB 5.5.23+
## Installation
@@ -43,8 +43,9 @@ Completely framework-agnostic and database-agnostic.
### Create a new instance
```php
// $db = new PDO('mysql:dbname=database;host=localhost;charset=utf8', 'username', 'password');
// $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// $db = new PDO('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
// or
// $db = new \Delight\Db\PdoDsn('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
$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
@@ -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
If a user is currently logged in, they may change their password.
@@ -222,6 +286,10 @@ If the user is not currently signed in, this returns `null`.
$ip = $auth->getIpAddress();
```
### Read and write session data
For detailed information on how to read and write session data conveniently, please refer to [the documentation of the session library](https://github.com/delight-im/PHP-Cookie), which is included by default.
### Utilities
#### Create a random string
@@ -246,7 +314,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
@@ -254,8 +322,13 @@ $uuid = \Delight\Auth\Auth::createUuid();
* logout
* full and reliable destruction of session
* session management
* protection against session hijacking
* protection against session hijacking via cross-site scripting (XSS)
* do *not* permit script-based access to cookies
* restrict cookies to HTTPS to prevent session hijacking via non-secure HTTP
* protection against session fixation attacks
* protection against cross-site request forgery (CSRF)
* works automatically (i.e. no need for CSRF tokens everywhere)
* do *not* use HTTP `GET` requests for "dangerous" operations
* throttling
* per IP address
* per account
@@ -292,18 +365,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).

View File

@@ -2,12 +2,15 @@
"name": "delight-im/auth",
"description": "Authentication for PHP. Simple, lightweight and secure.",
"require": {
"php": ">=5.5.0"
"php": ">=5.6.0",
"ext-openssl": "*",
"delight-im/cookie": "^2.1",
"delight-im/db": "^1.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/"

140
composer.lock generated Normal file
View File

@@ -0,0 +1,140 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"hash": "bd80e3e52b8bd8a4a0c74c7cf9f5bf5e",
"content-hash": "3f836c43e0ff2293051f2ccb739d23cf",
"packages": [
{
"name": "delight-im/cookie",
"version": "v2.1.0",
"source": {
"type": "git",
"url": "https://github.com/delight-im/PHP-Cookie.git",
"reference": "3e41e0d44959b59de98722b5b1b1fb83f9f528f3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/delight-im/PHP-Cookie/zipball/3e41e0d44959b59de98722b5b1b1fb83f9f528f3",
"reference": "3e41e0d44959b59de98722b5b1b1fb83f9f528f3",
"shasum": ""
},
"require": {
"delight-im/http": "^2.0",
"php": ">=5.3.0"
},
"type": "library",
"autoload": {
"psr-4": {
"Delight\\Cookie\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "Modern cookie management for PHP",
"homepage": "https://github.com/delight-im/PHP-Cookie",
"keywords": [
"cookie",
"cookies",
"csrf",
"http",
"same-site",
"samesite",
"xss"
],
"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",
"version": "v2.0.0",
"source": {
"type": "git",
"url": "https://github.com/delight-im/PHP-HTTP.git",
"reference": "0a19a72a7eac8b1301aa972fb20cff494ac43e09"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/delight-im/PHP-HTTP/zipball/0a19a72a7eac8b1301aa972fb20cff494ac43e09",
"reference": "0a19a72a7eac8b1301aa972fb20cff494ac43e09",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"type": "library",
"autoload": {
"psr-4": {
"Delight\\Http\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "Hypertext Transfer Protocol (HTTP) utilities for PHP",
"homepage": "https://github.com/delight-im/PHP-HTTP",
"keywords": [
"headers",
"http",
"https"
],
"time": "2016-07-21 15:05:01"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": {
"php": ">=5.6.0",
"ext-openssl": "*"
},
"platform-dev": []
}

File diff suppressed because it is too large Load Diff

View File

@@ -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;

View File

@@ -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;

View File

@@ -1,29 +1,25 @@
<?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)
*/
header('Content-type: text/html; charset=utf-8');
// enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 'stdout');
$db = new PDO('mysql:dbname=php_auth;host=127.0.0.1;charset=utf8', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// enable assertions
ini_set('assert.active', 1);
ini_set('zend.assertions', 1);
ini_set('assert.exception', 1);
require __DIR__.'/../src/Auth.php';
header('Content-type: text/html; charset=utf-8');
require __DIR__.'/../vendor/autoload.php';
$db = new PDO('mysql:dbname=php_auth;host=127.0.0.1;charset=utf8mb4', 'root', '');
$auth = new \Delight\Auth\Auth($db);
@@ -112,6 +108,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']);
@@ -208,8 +248,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>';
@@ -232,4 +272,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>';
}