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

10 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
3 changed files with 82 additions and 35 deletions

View File

@@ -58,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 {
@@ -90,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
}
@@ -114,13 +114,7 @@ catch (\Delight\Auth\TooManyRequestsException $e) {
}
```
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
### Email verification
Extract the selector and token from the URL that the user clicked on in the verification email.
@@ -141,7 +135,32 @@ catch (\Delight\Auth\TooManyRequestsException $e) {
}
```
### Reset a password ("forgot 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 {
@@ -200,7 +219,7 @@ catch (\Delight\Auth\TooManyRequestsException $e) {
}
```
### Change the current user's password
### Changing the current user's password
If a user is currently logged in, they may change their password.
@@ -226,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()) {
@@ -239,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();
@@ -249,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();
@@ -257,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();
@@ -267,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()) {
@@ -280,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();

View File

@@ -231,7 +231,9 @@ class Auth {
$selector = self::createRandomString(16);
$token = self::createRandomString(16);
$tokenHashed = password_hash($token, PASSWORD_DEFAULT);
$expires = time() + 3600 * 24;
// the request shall be valid for one day
$expires = time() + 60 * 60 * 24;
try {
$this->db->insert(
@@ -261,13 +263,13 @@ class Auth {
*
* @param string $email the user's email address
* @param string $password the user's password
* @param bool $remember whether to keep the user logged in ("remember me") or not
* @param int|bool|null $rememberDuration (optional) the duration in seconds to keep the user logged in ("remember me"), e.g. `60 * 60 * 24 * 365.25` for one year
* @throws InvalidEmailException if the email address was invalid or could not be found
* @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) {
public function login($email, $password, $rememberDuration = null) {
$email = self::validateEmailAddress($email);
$password = self::validatePassword($password);
@@ -292,8 +294,16 @@ class Auth {
if ($userData['verified'] === 1) {
$this->onLoginSuccessful($userData['id'], $email, $userData['username'], false);
if ($remember) {
$this->createRememberDirective($userData['id']);
// continue to support the old parameter format
if ($rememberDuration === true) {
$rememberDuration = 60 * 60 * 24 * 28;
}
elseif ($rememberDuration === false) {
$rememberDuration = null;
}
if ($rememberDuration !== null) {
$this->createRememberDirective($userData['id'], $rememberDuration);
}
return;
@@ -363,13 +373,14 @@ class Auth {
* Creates a new directive keeping the user logged in ("remember me")
*
* @param int $userId the user ID to keep signed in
* @param int $duration the duration in seconds
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
private function createRememberDirective($userId) {
private function createRememberDirective($userId, $duration) {
$selector = self::createRandomString(24);
$token = self::createRandomString(24);
$token = self::createRandomString(32);
$tokenHashed = password_hash($token, PASSWORD_DEFAULT);
$expires = time() + 3600 * 24 * 28;
$expires = time() + ((int) $duration);
try {
$this->db->insert(
@@ -622,7 +633,11 @@ class Auth {
if (!empty($passwordInDatabase)) {
if (password_verify($oldPassword, $passwordInDatabase)) {
// update the password in the database
$this->updatePassword($userId, $newPassword);
// delete any remaining remember directives
$this->deleteRememberDirective($userId);
}
else {
throw new InvalidPasswordException();
@@ -842,8 +857,12 @@ class Auth {
if ($resetData['expires'] >= time()) {
$newPassword = self::validatePassword($newPassword);
// update the password in the database
$this->updatePassword($resetData['user'], $newPassword);
// delete any remaining remember directives
$this->deleteRememberDirective($resetData['user']);
try {
$this->db->delete(
'users_resets',

View File

@@ -12,14 +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 = new PDO('mysql:dbname=php_auth;host=127.0.0.1;charset=utf8mb4', 'root', 'monkey');
$auth = new \Delight\Auth\Auth($db);
@@ -38,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';
}
@@ -248,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 (28 days)? — No</option>';
echo '<option value="1">Remember (28 days)? — 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>';