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

39 Commits

Author SHA1 Message Date
Marco
78a16d8f50 Improve language 2016-12-04 17:27:58 +01:00
Marco
e669f6f017 Move documentation on 'remember me' to its own section 2016-12-04 17:24:21 +01:00
Marco
5aafd0b009 Improve language 2016-12-04 17:23:09 +01:00
Marco
d53a484c2e Improve language 2016-12-04 17:13:33 +01:00
Marco
07732dcaa9 Change 'remember me' for login from binary choice to custom interval 2016-12-04 17:05:57 +01:00
Marco
f486ab6763 Forget remembered sessions when passwords are reset or changed 2016-12-04 16:54:34 +01:00
Marco
5e331924f6 Increase entropy in tokens for remember directives 2016-12-04 16:52:18 +01:00
Marco
ac95be3714 Use dummy password (instead of no password at all) in examples 2016-12-04 16:49:09 +01:00
Marco
e6c8ae056c Ignore warnings for 'zend.assertions' that cannot be set 2016-12-04 16:46:05 +01:00
Marco
5bac29065d Improve documentation 2016-12-04 16:44:50 +01:00
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
7 changed files with 841 additions and 282 deletions

View File

@@ -1,3 +1,12 @@
-- PHP-Auth (https://github.com/delight-im/PHP-Auth)
-- Copyright (c) delight.im (https://www.delight.im/)
-- Licensed under the MIT License (https://opensource.org/licenses/MIT)
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(249) COLLATE utf8mb4_unicode_ci NOT NULL,
@@ -35,12 +44,12 @@ CREATE TABLE IF NOT EXISTS `users_remembered` (
CREATE TABLE IF NOT EXISTS `users_resets` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user` int(10) unsigned NOT NULL,
`selector` varchar(24) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
`selector` varchar(20) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
`token` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
`expires` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `selector` (`selector`),
KEY `user` (`user`)
KEY `user_expires` (`user`,`expires`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `users_throttling` (
@@ -52,3 +61,7 @@ CREATE TABLE IF NOT EXISTS `users_throttling` (
PRIMARY KEY (`id`),
UNIQUE KEY `action_type_selector_time_bucket` (`action_type`,`selector`,`time_bucket`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

View File

@@ -38,3 +38,7 @@
## 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.

127
README.md
View File

@@ -16,8 +16,8 @@ Completely framework-agnostic and database-agnostic.
## Requirements
* PHP 5.5.0+
* OpenSSL extension
* 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=utf8mb4', '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);
```
@@ -57,7 +58,7 @@ Only in the very rare case that you need access to your cookies from JavaScript,
If your web server is behind a proxy server and `$_SERVER['REMOTE_ADDR']` only contains the proxy's IP address, you must pass the user's real IP address to the constructor in the fourth argument. The default is `null`.
### Sign up a new user (register)
### Registration (sign up a new user)
```php
try {
@@ -89,13 +90,13 @@ For email verification, you should build an URL with the selector and token and
$url = 'https://www.example.com/verify_email?selector='.urlencode($selector).'&token='.urlencode($token);
```
If you don't want to perform email verification, just omit the last parameter to `register(...)`. The new user will be active immediately, then.
If you don't want to perform email verification, just omit the last parameter to `Auth#register`. The new user will be active immediately, then.
### Sign in an existing user (login)
### Login (sign in an existing user)
```php
try {
$auth->login($_POST['email'], $_POST['password'], ($_POST['remember'] == 1));
$auth->login($_POST['email'], $_POST['password']);
// user is logged in
}
@@ -113,9 +114,7 @@ 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`.
### Perform email verification
### Email verification
Extract the selector and token from the URL that the user clicked on in the verification email.
@@ -136,7 +135,91 @@ catch (\Delight\Auth\TooManyRequestsException $e) {
}
```
### Change the current user's password
### Keeping the user logged in
The third parameter to the `Auth#login` method 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.
```php
if ($_POST['remember'] == 1) {
// keep logged in for one year
$rememberDuration = (int) (60 * 60 * 24 * 365.25);
}
else {
// do not keep logged in after session ends
$rememberDuration = null;
}
// ...
$auth->login($_POST['email'], $_POST['password'], $rememberDuration);
// ...
```
*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.
Omit the third parameter or set it to `null` to disable the feature. Otherwise, you may ask the user whether 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 `null` and a pre-defined duration in seconds here, e.g. `60 * 60 * 24 * 365.25` for one year.
### Password reset ("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
}
```
### Changing the current user's password
If a user is currently logged in, they may change their password.
@@ -162,7 +245,7 @@ $auth->logout();
// user has been signed out
```
### Check if the user is signed in
### Checking if the user is signed in
```php
if ($auth->isLoggedIn()) {
@@ -175,7 +258,7 @@ else {
A shorthand/alias for this method is `$auth->check()`.
### Get the user's ID
### Getting the user's ID
```php
$id = $auth->getUserId();
@@ -185,7 +268,7 @@ If the user is not currently signed in, this returns `null`.
A shorthand/alias for this method is `$auth->id()`.
### Get the user's email address
### Getting the user's email address
```php
$email = $auth->getEmail();
@@ -193,7 +276,7 @@ $email = $auth->getEmail();
If the user is not currently signed in, this returns `null`.
### Get the user's display name
### Getting the user's display name
```php
$email = $auth->getUsername();
@@ -203,7 +286,7 @@ Remember that usernames are optional and there is only a username if you supplie
If the user is not currently signed in, this returns `null`.
### Check if the user was "remembered"
### Checking if the user was "remembered"
```php
if ($auth->isRemembered()) {
@@ -216,26 +299,26 @@ else {
If the user is not currently signed in, this returns `null`.
### Get the user's IP address
### Getting the user's IP address
```php
$ip = $auth->getIpAddress();
```
### Read and write session data
### Reading and writing 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
#### Creating a random string
```php
$length = 24;
$randomStr = \Delight\Auth\Auth::createRandomString($length);
```
#### Create a UUID v4 as per RFC 4122
#### Creating a UUID v4 as per RFC 4122
```php
$uuid = \Delight\Auth\Auth::createUuid();
@@ -250,7 +333,7 @@ $uuid = \Delight\Auth\Auth::createUuid();
* customizable password requirements and enforcement
* optional usernames with customizable restrictions
* login
* keeping the user logged in for a long time via secure long-lived token ("remember me")
* keeping the user logged in for a long time (beyond expiration of browser session) via secure long-lived token ("remember me")
* account management
* change password
* tracking the time of sign up and last login

View File

@@ -2,9 +2,10 @@
"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.0"
"delight-im/cookie": "^2.1",
"delight-im/db": "^1.0"
},
"type": "library",
"keywords": [ "auth", "authentication", "login", "security" ],

57
composer.lock generated
View File

@@ -4,21 +4,21 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"hash": "22e56875c7a1386807d5cf6ae01f50fa",
"content-hash": "b914ccd7ac15e1519d7a04b55dbe725e",
"hash": "bd80e3e52b8bd8a4a0c74c7cf9f5bf5e",
"content-hash": "3f836c43e0ff2293051f2ccb739d23cf",
"packages": [
{
"name": "delight-im/cookie",
"version": "v2.0.0",
"version": "v2.1.0",
"source": {
"type": "git",
"url": "https://github.com/delight-im/PHP-Cookie.git",
"reference": "a746f4096885b6715a640a2122b1c21324624f8f"
"reference": "3e41e0d44959b59de98722b5b1b1fb83f9f528f3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/delight-im/PHP-Cookie/zipball/a746f4096885b6715a640a2122b1c21324624f8f",
"reference": "a746f4096885b6715a640a2122b1c21324624f8f",
"url": "https://api.github.com/repos/delight-im/PHP-Cookie/zipball/3e41e0d44959b59de98722b5b1b1fb83f9f528f3",
"reference": "3e41e0d44959b59de98722b5b1b1fb83f9f528f3",
"shasum": ""
},
"require": {
@@ -46,7 +46,48 @@
"samesite",
"xss"
],
"time": "2016-07-21 15:20:20"
"time": "2016-11-23 20:09:42"
},
{
"name": "delight-im/db",
"version": "v1.0.2",
"source": {
"type": "git",
"url": "https://github.com/delight-im/PHP-DB.git",
"reference": "c8d1eba6583007471d55bf7d88eb3c9d87ea849d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/delight-im/PHP-DB/zipball/c8d1eba6583007471d55bf7d88eb3c9d87ea849d",
"reference": "c8d1eba6583007471d55bf7d88eb3c9d87ea849d",
"shasum": ""
},
"require": {
"ext-pdo": "*",
"php": ">=5.6.0"
},
"type": "library",
"autoload": {
"psr-4": {
"Delight\\Db\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "Safe and convenient SQL database access in a driver-agnostic way",
"homepage": "https://github.com/delight-im/PHP-DB",
"keywords": [
"database",
"mysql",
"pdo",
"pgsql",
"postgresql",
"sql",
"sqlite"
],
"time": "2016-12-01 12:40:36"
},
{
"name": "delight-im/http",
@@ -92,7 +133,7 @@
"prefer-stable": false,
"prefer-lowest": false,
"platform": {
"php": ">=5.5.0",
"php": ">=5.6.0",
"ext-openssl": "*"
},
"platform-dev": []

File diff suppressed because it is too large Load Diff

View File

@@ -12,15 +12,14 @@ ini_set('display_errors', 'stdout');
// enable assertions
ini_set('assert.active', 1);
ini_set('zend.assertions', 1);
@ini_set('zend.assertions', 1);
ini_set('assert.exception', 1);
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', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db = new PDO('mysql:dbname=php_auth;host=127.0.0.1;charset=utf8mb4', 'root', 'monkey');
$auth = new \Delight\Auth\Auth($db);
@@ -39,8 +38,17 @@ function processRequestData(\Delight\Auth\Auth $auth) {
if (isset($_POST)) {
if (isset($_POST['action'])) {
if ($_POST['action'] === 'login') {
if ($_POST['remember'] == 1) {
// keep logged in for one year
$rememberDuration = (int) (60 * 60 * 24 * 365.25);
}
else {
// do not keep logged in after session ends
$rememberDuration = null;
}
try {
$auth->login($_POST['email'], $_POST['password'], ($_POST['remember'] == 1));
$auth->login($_POST['email'], $_POST['password'], $rememberDuration);
return 'ok';
}
@@ -109,6 +117,50 @@ function processRequestData(\Delight\Auth\Auth $auth) {
return 'too many requests';
}
}
else if ($_POST['action'] === 'forgotPassword') {
try {
$auth->forgotPassword($_POST['email'], function ($selector, $token) {
echo '<pre>';
echo 'Password reset';
echo "\n";
echo ' > Selector';
echo "\t\t\t\t";
echo htmlspecialchars($selector);
echo "\n";
echo ' > Token';
echo "\t\t\t\t";
echo htmlspecialchars($token);
echo '</pre>';
});
return 'ok';
}
catch (\Delight\Auth\InvalidEmailException $e) {
return 'invalid email address';
}
catch (\Delight\Auth\TooManyRequestsException $e) {
return 'too many requests';
}
}
else if ($_POST['action'] === 'resetPassword') {
try {
$auth->resetPassword($_POST['selector'], $_POST['token'], $_POST['password']);
return 'ok';
}
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
return 'invalid token';
}
catch (\Delight\Auth\TokenExpiredException $e) {
return 'token expired';
}
catch (\Delight\Auth\InvalidPasswordException $e) {
return 'invalid password';
}
catch (\Delight\Auth\TooManyRequestsException $e) {
return 'too many requests';
}
}
else if ($_POST['action'] === 'changePassword') {
try {
$auth->changePassword($_POST['oldPassword'], $_POST['newPassword']);
@@ -205,8 +257,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 (keep logged in)? — No</option>';
echo '<option value="1">Remember (keep logged in)? — Yes</option>';
echo '</select> ';
echo '<button type="submit">Login</button>';
echo '</form>';
@@ -229,4 +281,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>';
}