mirror of
https://github.com/delight-im/PHP-Auth.git
synced 2025-08-07 16:46:29 +02:00
Compare commits
28 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
7bce546def | ||
|
df16db9b2b | ||
|
fa655c4908 | ||
|
fd67044826 | ||
|
6333d25cf2 | ||
|
f5060b5a1d | ||
|
729c76668f | ||
|
cc6430a83e | ||
|
6f933ac560 | ||
|
157a7095b0 | ||
|
0f976a260b | ||
|
dcd893a12c | ||
|
0086419175 | ||
|
d49b35690c | ||
|
171519fdf3 | ||
|
14ce7b1e8f | ||
|
49c70eff41 | ||
|
2f772b00c8 | ||
|
5214da1f59 | ||
|
d8847fb197 | ||
|
1757ad3fd1 | ||
|
54f6c5320a | ||
|
4b3f2ab91c | ||
|
df990b5b75 | ||
|
7b2ac9b107 | ||
|
ad90c7d04a | ||
|
c0baa517fa | ||
|
3120e3a6a5 |
320
README.md
320
README.md
@@ -8,7 +8,7 @@ Completely framework-agnostic and database-agnostic.
|
||||
|
||||
## Why do I need this?
|
||||
|
||||
* There are [tons](http://www.troyhunt.com/2011/01/whos-who-of-bad-password-practices.html) [of](http://www.jeremytunnell.com/posts/swab-password-policies-and-two-factor-authentication-a-comedy-of-errors) [websites](http://badpasswordpolicies.tumblr.com/) with weak authentication systems. Don’t build such a site.
|
||||
* There are [tons](https://www.troyhunt.com/whos-who-of-bad-password-practices/) [of](https://blog.codinghorror.com/password-rules-are-bullshit/) [websites](https://badpasswordpolicies.tumblr.com/) with weak authentication systems. Don’t build such a site.
|
||||
* Re-implementing a new authentication system for every PHP project is *not* a good idea.
|
||||
* Building your own authentication classes piece by piece, and copying it to every project, is *not* recommended, either.
|
||||
* A secure authentication system with an easy-to-use API should be thoroughly designed and planned.
|
||||
@@ -55,6 +55,9 @@ Migrating from an earlier version of this project? See our [upgrade guide](Migra
|
||||
* [Email verification](#email-verification)
|
||||
* [Keeping the user logged in](#keeping-the-user-logged-in)
|
||||
* [Password reset (“forgot password”)](#password-reset-forgot-password)
|
||||
* [Initiating the request](#step-1-of-3-initiating-the-request)
|
||||
* [Verifying an attempt](#step-2-of-3-verifying-an-attempt)
|
||||
* [Updating the password](#step-3-of-3-updating-the-password)
|
||||
* [Changing the current user’s password](#changing-the-current-users-password)
|
||||
* [Changing the current user’s email address](#changing-the-current-users-email-address)
|
||||
* [Re-sending confirmation requests](#re-sending-confirmation-requests)
|
||||
@@ -64,6 +67,7 @@ Migrating from an earlier version of this project? See our [upgrade guide](Migra
|
||||
* [User ID](#user-id)
|
||||
* [Email address](#email-address)
|
||||
* [Display name](#display-name)
|
||||
* [Status information](#status-information)
|
||||
* [Checking whether the user was “remembered”](#checking-whether-the-user-was-remembered)
|
||||
* [IP address](#ip-address)
|
||||
* [Additional user information](#additional-user-information)
|
||||
@@ -105,11 +109,11 @@ Migrating from an earlier version of this project? See our [upgrade guide](Migra
|
||||
|
||||
// or
|
||||
|
||||
// $db = new \Delight\Db\PdoDsn('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password');
|
||||
// $db = \Delight\Db\PdoDatabase::fromDsn(new \Delight\Db\PdoDsn('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password'));
|
||||
// or
|
||||
// $db = new \Delight\Db\PdoDsn('pgsql:dbname=my-database;host=localhost;port=5432', 'my-username', 'my-password');
|
||||
// $db = \Delight\Db\PdoDatabase::fromDsn(new \Delight\Db\PdoDsn('pgsql:dbname=my-database;host=localhost;port=5432', 'my-username', 'my-password'));
|
||||
// or
|
||||
// $db = new \Delight\Db\PdoDsn('sqlite:../Databases/my-database.sqlite');
|
||||
// $db = \Delight\Db\PdoDatabase::fromDsn(new \Delight\Db\PdoDsn('sqlite:../Databases/my-database.sqlite'));
|
||||
|
||||
$auth = new \Delight\Auth\Auth($db);
|
||||
```
|
||||
@@ -126,36 +130,46 @@ During the lifetime of a session, some user data may be changed remotely, either
|
||||
|
||||
If all your database tables need a common database name, schema name, or other qualifier that must be specified explicitly, you can optionally pass that qualifier to the constructor as the sixth parameter, which is named `$dbSchema`.
|
||||
|
||||
If you want to use a `PdoDatabase` instance (e.g. `$db`) independently as well, please refer to the [documentation of the database library](https://github.com/delight-im/PHP-DB).
|
||||
|
||||
### Registration (sign up)
|
||||
|
||||
```php
|
||||
try {
|
||||
$userId = $auth->register($_POST['email'], $_POST['password'], $_POST['username'], function ($selector, $token) {
|
||||
// send `$selector` and `$token` to the user (e.g. via email)
|
||||
echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)';
|
||||
});
|
||||
|
||||
// we have signed up a new user with the ID `$userId`
|
||||
echo 'We have signed up a new user with the ID ' . $userId;
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// invalid email address
|
||||
die('Invalid email address');
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
// invalid password
|
||||
die('Invalid password');
|
||||
}
|
||||
catch (\Delight\Auth\UserAlreadyExistsException $e) {
|
||||
// user already exists
|
||||
die('User already exists');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** The anonymous callback function is a [closure](http://php.net/manual/en/functions.anonymous.php). Thus, besides its own parameters, only [superglobals](http://php.net/manual/en/language.variables.superglobals.php) like `$_GET`, `$_POST`, `$_COOKIE` and `$_SERVER` are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a `use` clause after the parameter list.
|
||||
**Note:** The anonymous callback function is a [closure](https://www.php.net/manual/functions.anonymous.php). Thus, besides its own parameters, only [superglobals](https://www.php.net/manual/language.variables.superglobals.php) like `$_GET`, `$_POST`, `$_COOKIE` and `$_SERVER` are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a `use` clause after the parameter list.
|
||||
|
||||
The username in the third parameter is optional. You can pass `null` there if you don’t want to manage usernames.
|
||||
|
||||
If you want to enforce unique usernames, on the other hand, simply call `registerWithUniqueUsername` instead of `register`, and be prepared to catch the `DuplicateUsernameException`.
|
||||
|
||||
**Note:** When accepting and managing usernames, you may want to exclude non-printing control characters and certain printable special characters, as in the character class `[\x00-\x1f\x7f\/:\\]`. In order to do so, you could wrap the call to `Auth#register` or `Auth#registerWithUniqueUsername` inside a conditional branch, for example by only accepting usernames when the following condition is satisfied:
|
||||
|
||||
```php
|
||||
if (\preg_match('/[\x00-\x1f\x7f\/:\\\\]/', $username) === 0) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
For email verification, you should build an URL with the selector and token and send it to the user, e.g.:
|
||||
|
||||
```php
|
||||
@@ -164,25 +178,29 @@ $url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector)
|
||||
|
||||
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.
|
||||
|
||||
Need to store additional user information? Read on [here](#additional-user-information).
|
||||
|
||||
**Note:** When sending an email to the user, please note that the (optional) username, at this point, has not yet been confirmed as acceptable to the owner of the (new) email address. It could contain offensive or misleading language chosen by someone who is not actually the owner of the address.
|
||||
|
||||
### Login (sign in)
|
||||
|
||||
```php
|
||||
try {
|
||||
$auth->login($_POST['email'], $_POST['password']);
|
||||
|
||||
// user is logged in
|
||||
echo 'User is logged in';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// wrong email address
|
||||
die('Wrong email address');
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
// wrong password
|
||||
die('Wrong password');
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email not verified
|
||||
die('Email not verified');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -196,24 +214,26 @@ Extract the selector and token from the URL that the user clicked on in the veri
|
||||
try {
|
||||
$auth->confirmEmail($_GET['selector'], $_GET['token']);
|
||||
|
||||
// email address has been verified
|
||||
echo 'Email address has been verified';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
|
||||
// invalid token
|
||||
die('Invalid token');
|
||||
}
|
||||
catch (\Delight\Auth\TokenExpiredException $e) {
|
||||
// token expired
|
||||
die('Token expired');
|
||||
}
|
||||
catch (\Delight\Auth\UserAlreadyExistsException $e) {
|
||||
// email address already exists
|
||||
die('Email address already exists');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
If you want the user to be automatically signed in after successful confirmation, just call `confirmEmailAndSignIn` instead of `confirmEmail`. That alternative method also supports [persistent logins](#keeping-the-user-logged-in) via its optional third parameter.
|
||||
|
||||
On success, the two methods `confirmEmail` and `confirmEmailAndSignIn` both return an array with the user’s new email address, which has just been verified, at index one. If the confirmation was for an address change instead of a simple address verification, the user’s old email address will be included in the array at index zero.
|
||||
|
||||
### Keeping the user logged in
|
||||
|
||||
The third parameter to the `Auth#login` and `Auth#confirmEmailAndSignIn` methods 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.
|
||||
@@ -246,26 +266,26 @@ Omit the third parameter or set it to `null` to disable the feature. Otherwise,
|
||||
```php
|
||||
try {
|
||||
$auth->forgotPassword($_POST['email'], function ($selector, $token) {
|
||||
// send `$selector` and `$token` to the user (e.g. via email)
|
||||
echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)';
|
||||
});
|
||||
|
||||
// request has been generated
|
||||
echo 'Request has been generated';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// invalid email address
|
||||
die('Invalid email address');
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email not verified
|
||||
die('Email not verified');
|
||||
}
|
||||
catch (\Delight\Auth\ResetDisabledException $e) {
|
||||
// password reset is disabled
|
||||
die('Password reset is disabled');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** The anonymous callback function is a [closure](http://php.net/manual/en/functions.anonymous.php). Thus, besides its own parameters, only [superglobals](http://php.net/manual/en/language.variables.superglobals.php) like `$_GET`, `$_POST`, `$_COOKIE` and `$_SERVER` are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a `use` clause after the parameter list.
|
||||
**Note:** The anonymous callback function is a [closure](https://www.php.net/manual/functions.anonymous.php). Thus, besides its own parameters, only [superglobals](https://www.php.net/manual/language.variables.superglobals.php) like `$_GET`, `$_POST`, `$_COOKIE` and `$_SERVER` are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a `use` clause after the parameter list.
|
||||
|
||||
You should build an URL with the selector and token and send it to the user, e.g.:
|
||||
|
||||
@@ -273,6 +293,8 @@ You should build an URL with the selector and token and send it to the user, e.g
|
||||
$url = 'https://www.example.com/reset_password?selector=' . \urlencode($selector) . '&token=' . \urlencode($token);
|
||||
```
|
||||
|
||||
If the default lifetime of the password reset requests does not work for you, you can use the third parameter of `Auth#forgotPassword` to specify a custom interval in seconds after which the requests should expire.
|
||||
|
||||
#### Step 2 of 3: Verifying an attempt
|
||||
|
||||
As the next step, users will click on the link that they received. Extract the selector and token from the URL.
|
||||
@@ -283,22 +305,22 @@ If the selector/token pair is valid, let the user choose a new password:
|
||||
try {
|
||||
$auth->canResetPasswordOrThrow($_GET['selector'], $_GET['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)
|
||||
echo 'Put the selector into a "hidden" field (or keep it in the URL)';
|
||||
echo 'Put the token into a "hidden" field (or keep it in the URL)';
|
||||
|
||||
// ask the user for their new password
|
||||
echo 'Ask the user for their new password';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
|
||||
// invalid token
|
||||
die('Invalid token');
|
||||
}
|
||||
catch (\Delight\Auth\TokenExpiredException $e) {
|
||||
// token expired
|
||||
die('Token expired');
|
||||
}
|
||||
catch (\Delight\Auth\ResetDisabledException $e) {
|
||||
// password reset is disabled
|
||||
die('Password reset is disabled');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -306,10 +328,10 @@ Alternatively, if you don’t need any error messages but only want to check the
|
||||
|
||||
```php
|
||||
if ($auth->canResetPassword($_GET['selector'], $_GET['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)
|
||||
echo 'Put the selector into a "hidden" field (or keep it in the URL)';
|
||||
echo 'Put the token into a "hidden" field (or keep it in the URL)';
|
||||
|
||||
// ask the user for their new password
|
||||
echo 'Ask the user for their new password';
|
||||
}
|
||||
```
|
||||
|
||||
@@ -321,25 +343,29 @@ Now when you have the new password for the user (and still have the other two pi
|
||||
try {
|
||||
$auth->resetPassword($_POST['selector'], $_POST['token'], $_POST['password']);
|
||||
|
||||
// password has been reset
|
||||
echo 'Password has been reset';
|
||||
}
|
||||
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
|
||||
// invalid token
|
||||
die('Invalid token');
|
||||
}
|
||||
catch (\Delight\Auth\TokenExpiredException $e) {
|
||||
// token expired
|
||||
die('Token expired');
|
||||
}
|
||||
catch (\Delight\Auth\ResetDisabledException $e) {
|
||||
// password reset is disabled
|
||||
die('Password reset is disabled');
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
// invalid password
|
||||
die('Invalid password');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
Do you want to have the respective user signed in automatically when their password reset succeeds? Simply use `Auth#resetPasswordAndSignIn` instead of `Auth#resetPassword` to log in the user immediately.
|
||||
|
||||
If you need the user’s ID or email address, e.g. for sending them a notification that their password has successfully been reset, just use the return value of `Auth#resetPassword`, which is an array containing two entries named `id` and `email`.
|
||||
|
||||
### Changing the current user’s password
|
||||
|
||||
If a user is currently logged in, they may change their password.
|
||||
@@ -348,16 +374,16 @@ If a user is currently logged in, they may change their password.
|
||||
try {
|
||||
$auth->changePassword($_POST['oldPassword'], $_POST['newPassword']);
|
||||
|
||||
// password has been changed
|
||||
echo 'Password has been changed';
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
// not logged in
|
||||
die('Not logged in');
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
// invalid password(s)
|
||||
die('Invalid password(s)');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -375,33 +401,33 @@ If a user is currently logged in, they may change their email address.
|
||||
try {
|
||||
if ($auth->reconfirmPassword($_POST['password'])) {
|
||||
$auth->changeEmail($_POST['newEmail'], function ($selector, $token) {
|
||||
// send `$selector` and `$token` to the user (e.g. via email to the *new* address)
|
||||
echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email to the *new* address)';
|
||||
});
|
||||
|
||||
// the change will take effect as soon as the new email address has been confirmed
|
||||
echo 'The change will take effect as soon as the new email address has been confirmed';
|
||||
}
|
||||
else {
|
||||
// we can't say if the user is who they claim to be
|
||||
echo 'We can\'t say if the user is who they claim to be';
|
||||
}
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// invalid email address
|
||||
die('Invalid email address');
|
||||
}
|
||||
catch (\Delight\Auth\UserAlreadyExistsException $e) {
|
||||
// email address already exists
|
||||
die('Email address already exists');
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// account not verified
|
||||
die('Account not verified');
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
// not logged in
|
||||
die('Not logged in');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** The anonymous callback function is a [closure](http://php.net/manual/en/functions.anonymous.php). Thus, besides its own parameters, only [superglobals](http://php.net/manual/en/language.variables.superglobals.php) like `$_GET`, `$_POST`, `$_COOKIE` and `$_SERVER` are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a `use` clause after the parameter list.
|
||||
**Note:** The anonymous callback function is a [closure](https://www.php.net/manual/functions.anonymous.php). Thus, besides its own parameters, only [superglobals](https://www.php.net/manual/language.variables.superglobals.php) like `$_GET`, `$_POST`, `$_COOKIE` and `$_SERVER` are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a `use` clause after the parameter list.
|
||||
|
||||
For email verification, you should build an URL with the selector and token and send it to the user, e.g.:
|
||||
|
||||
@@ -409,6 +435,8 @@ 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);
|
||||
```
|
||||
|
||||
**Note:** When sending an email to the user, please note that the (optional) username, at this point, has not yet been confirmed as acceptable to the owner of the (new) email address. It could contain offensive or misleading language chosen by someone who is not actually the owner of the address.
|
||||
|
||||
After the request to change the email address has been made, or even better, after the change has been confirmed by the user, you should send an email to their account’s *previous* email address as an out-of-band notification informing the account owner about this critical change.
|
||||
|
||||
**Note:** Changes to a user’s email address take effect in the local session immediately, as expected. In other sessions (e.g. on other devices), the changes may need up to five minutes to take effect, though. This increases performance and usually poses no problem. If you want to change this behavior, nevertheless, simply decrease (or perhaps increase) the value that you pass to the [`Auth` constructor](#creating-a-new-instance) as the argument named `$sessionResyncInterval`.
|
||||
@@ -420,16 +448,16 @@ If an earlier confirmation request could not be delivered to the user, or if the
|
||||
```php
|
||||
try {
|
||||
$auth->resendConfirmationForEmail($_POST['email'], function ($selector, $token) {
|
||||
// send `$selector` and `$token` to the user (e.g. via email)
|
||||
echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)';
|
||||
});
|
||||
|
||||
// the user may now respond to the confirmation request (usually by clicking a link)
|
||||
echo 'The user may now respond to the confirmation request (usually by clicking a link)';
|
||||
}
|
||||
catch (\Delight\Auth\ConfirmationRequestNotFound $e) {
|
||||
// no earlier request found that could be re-sent
|
||||
die('No earlier request found that could be re-sent');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// there have been too many requests -- try again later
|
||||
die('There have been too many requests -- try again later');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -438,20 +466,20 @@ If you want to specify the user by their ID instead of by their email address, t
|
||||
```php
|
||||
try {
|
||||
$auth->resendConfirmationForUserId($_POST['userId'], function ($selector, $token) {
|
||||
// send `$selector` and `$token` to the user (e.g. via email)
|
||||
echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)';
|
||||
});
|
||||
|
||||
// the user may now respond to the confirmation request (usually by clicking a link)
|
||||
echo 'The user may now respond to the confirmation request (usually by clicking a link)';
|
||||
}
|
||||
catch (\Delight\Auth\ConfirmationRequestNotFound $e) {
|
||||
// no earlier request found that could be re-sent
|
||||
die('No earlier request found that could be re-sent');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// there have been too many requests -- try again later
|
||||
die('There have been too many requests -- try again later');
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** The anonymous callback function is a [closure](http://php.net/manual/en/functions.anonymous.php). Thus, besides its own parameters, only [superglobals](http://php.net/manual/en/language.variables.superglobals.php) like `$_GET`, `$_POST`, `$_COOKIE` and `$_SERVER` are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a `use` clause after the parameter list.
|
||||
**Note:** The anonymous callback function is a [closure](https://www.php.net/manual/functions.anonymous.php). Thus, besides its own parameters, only [superglobals](https://www.php.net/manual/language.variables.superglobals.php) like `$_GET`, `$_POST`, `$_COOKIE` and `$_SERVER` are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a `use` clause after the parameter list.
|
||||
|
||||
Usually, you should build an URL with the selector and token and send it to the user, e.g. as follows:
|
||||
|
||||
@@ -459,6 +487,8 @@ Usually, you should build an URL with the selector and token and send it to the
|
||||
$url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector) . '&token=' . \urlencode($token);
|
||||
```
|
||||
|
||||
**Note:** When sending an email to the user, please note that the (optional) username, at this point, has not yet been confirmed as acceptable to the owner of the (new) email address. It could contain offensive or misleading language chosen by someone who is not actually the owner of the address.
|
||||
|
||||
### Logout
|
||||
|
||||
```php
|
||||
@@ -470,7 +500,7 @@ try {
|
||||
$auth->logOutEverywhereElse();
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
// not logged in
|
||||
die('Not logged in');
|
||||
}
|
||||
|
||||
// or
|
||||
@@ -479,7 +509,7 @@ try {
|
||||
$auth->logOutEverywhere();
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
// not logged in
|
||||
die('Not logged in');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -497,10 +527,10 @@ $auth->destroySession();
|
||||
|
||||
```php
|
||||
if ($auth->isLoggedIn()) {
|
||||
// user is signed in
|
||||
echo 'User is signed in';
|
||||
}
|
||||
else {
|
||||
// user is *not* signed in yet
|
||||
echo 'User is not signed in yet';
|
||||
}
|
||||
```
|
||||
|
||||
@@ -527,7 +557,7 @@ If the user is not currently signed in, this returns `null`.
|
||||
#### Display name
|
||||
|
||||
```php
|
||||
$email = $auth->getUsername();
|
||||
$username = $auth->getUsername();
|
||||
```
|
||||
|
||||
Remember that usernames are optional and there is only a username if you supplied it during registration.
|
||||
@@ -538,27 +568,27 @@ If the user is not currently signed in, this returns `null`.
|
||||
|
||||
```php
|
||||
if ($auth->isNormal()) {
|
||||
// user is in default state
|
||||
echo 'User is in default state';
|
||||
}
|
||||
|
||||
if ($auth->isArchived()) {
|
||||
// user has been archived
|
||||
echo 'User has been archived';
|
||||
}
|
||||
|
||||
if ($auth->isBanned()) {
|
||||
// user has been banned
|
||||
echo 'User has been banned';
|
||||
}
|
||||
|
||||
if ($auth->isLocked()) {
|
||||
// user has been locked
|
||||
echo 'User has been locked';
|
||||
}
|
||||
|
||||
if ($auth->isPendingReview()) {
|
||||
// user is pending review
|
||||
echo 'User is pending review';
|
||||
}
|
||||
|
||||
if ($auth->isSuspended()) {
|
||||
// user has been suspended
|
||||
echo 'User has been suspended';
|
||||
}
|
||||
```
|
||||
|
||||
@@ -566,10 +596,10 @@ if ($auth->isSuspended()) {
|
||||
|
||||
```php
|
||||
if ($auth->isRemembered()) {
|
||||
// user did not sign in but was logged in through their long-lived cookie
|
||||
echo 'User did not sign in but was logged in through their long-lived cookie';
|
||||
}
|
||||
else {
|
||||
// user signed in manually
|
||||
echo 'User signed in manually';
|
||||
}
|
||||
```
|
||||
|
||||
@@ -615,17 +645,17 @@ For example, when a user has been remembered by a long-lived cookie and thus `Au
|
||||
```php
|
||||
try {
|
||||
if ($auth->reconfirmPassword($_POST['password'])) {
|
||||
// the user really seems to be who they claim to be
|
||||
echo 'The user really seems to be who they claim to be';
|
||||
}
|
||||
else {
|
||||
// we can't say if the user is who they claim to be
|
||||
echo 'We can\'t say if the user is who they claim to be';
|
||||
}
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
// the user is not signed in
|
||||
die('The user is not signed in');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -639,19 +669,19 @@ Users may have no role at all (which they do by default), exactly one role, or a
|
||||
|
||||
```php
|
||||
if ($auth->hasRole(\Delight\Auth\Role::SUPER_MODERATOR)) {
|
||||
// the user is a super moderator
|
||||
echo 'The user is a super moderator';
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
if ($auth->hasAnyRole(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER)) {
|
||||
// the user is either a developer, or a manager, or both
|
||||
echo 'The user is either a developer, or a manager, or both';
|
||||
}
|
||||
|
||||
// or
|
||||
|
||||
if ($auth->hasAllRoles(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER)) {
|
||||
// the user is both a developer and a manager
|
||||
echo 'The user is both a developer and a manager';
|
||||
}
|
||||
```
|
||||
|
||||
@@ -719,19 +749,19 @@ function canEditArticle(\Delight\Auth\Auth $auth) {
|
||||
// ...
|
||||
|
||||
if (canEditArticle($auth)) {
|
||||
// the user can edit articles here
|
||||
echo 'The user can edit articles here';
|
||||
}
|
||||
|
||||
// ...
|
||||
|
||||
if (canEditArticle($auth)) {
|
||||
// ... and here
|
||||
echo '... and here';
|
||||
}
|
||||
|
||||
// ...
|
||||
|
||||
if (canEditArticle($auth)) {
|
||||
// ... and here
|
||||
echo '... and here';
|
||||
}
|
||||
```
|
||||
|
||||
@@ -787,17 +817,17 @@ try {
|
||||
if ($auth->reconfirmPassword($_POST['password'])) {
|
||||
$auth->setPasswordResetEnabled($_POST['enabled'] == 1);
|
||||
|
||||
// the setting has been changed
|
||||
echo 'The setting has been changed';
|
||||
}
|
||||
else {
|
||||
// we can't say if the user is who they claim to be
|
||||
echo 'We can\'t say if the user is who they claim to be';
|
||||
}
|
||||
}
|
||||
catch (\Delight\Auth\NotLoggedInException $e) {
|
||||
// the user is not signed in
|
||||
die('The user is not signed in');
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// too many requests
|
||||
die('Too many requests');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -811,7 +841,7 @@ for the correct default option in your user interface. You don’t need to check
|
||||
|
||||
### Throttling or rate limiting
|
||||
|
||||
All methods provided by this library are *automatically* protected against excessive numbers of requests from clients.
|
||||
All methods provided by this library are *automatically* protected against excessive numbers of requests from clients. If the need arises, you can (temporarily) disable this protection using the [`$throttling` parameter](#creating-a-new-instance) passed to the constructor.
|
||||
|
||||
If you would like to throttle or rate limit *external* features or methods as well, e.g. those in your own code, you can make use of the built-in helper method for throttling and rate limiting:
|
||||
|
||||
@@ -820,7 +850,7 @@ try {
|
||||
// throttle the specified resource or feature to *3* requests per *60* seconds
|
||||
$auth->throttle([ 'my-resource-name' ], 3, 60);
|
||||
|
||||
// do something with the resource or feature
|
||||
echo 'Do something with the resource or feature';
|
||||
}
|
||||
catch (\Delight\Auth\TooManyRequestsException $e) {
|
||||
// operation cancelled
|
||||
@@ -842,6 +872,8 @@ Allowing short bursts of activity during peak demand is possible by specifying a
|
||||
|
||||
In some cases, you may just want to *simulate* the throttling or rate limiting. This lets you check whether an action would be permitted without actually modifying the activity tracker. To do so, simply pass `true` as the fifth argument.
|
||||
|
||||
**Note:** When you disable throttling on the instance (using the [`$throttling` parameter](#creating-a-new-instance) passed to the constructor), this turns off both the automatic internal protection and the effect of any calls to `Auth#throttle` in your own application code – unless you also set the optional `$force` parameter to `true` in specific `Auth#throttle` calls.
|
||||
|
||||
### Administration (managing users)
|
||||
|
||||
The administrative interface is available via `$auth->admin()`. You can call various method on this interface, as documented below.
|
||||
@@ -854,16 +886,16 @@ Do not forget to implement secure access control before exposing access to this
|
||||
try {
|
||||
$userId = $auth->admin()->createUser($_POST['email'], $_POST['password'], $_POST['username']);
|
||||
|
||||
// we have signed up a new user with the ID `$userId`
|
||||
echo 'We have signed up a new user with the ID ' . $userId;
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// invalid email address
|
||||
die('Invalid email address');
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
// invalid password
|
||||
die('Invalid password');
|
||||
}
|
||||
catch (\Delight\Auth\UserAlreadyExistsException $e) {
|
||||
// user already exists
|
||||
die('User already exists');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -880,7 +912,7 @@ try {
|
||||
$auth->admin()->deleteUserById($_POST['id']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown ID
|
||||
die('Unknown ID');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -891,7 +923,7 @@ try {
|
||||
$auth->admin()->deleteUserByEmail($_POST['email']);
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// unknown email address
|
||||
die('Unknown email address');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -902,13 +934,23 @@ try {
|
||||
$auth->admin()->deleteUserByUsername($_POST['username']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
// unknown username
|
||||
die('Unknown username');
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
// ambiguous username
|
||||
die('Ambiguous username');
|
||||
}
|
||||
```
|
||||
|
||||
#### Retrieving a list of registered users
|
||||
|
||||
When fetching a list of all users, the requirements vary greatly between projects and use cases, and customization is common. For example, you might want to fetch different columns, join related tables, filter by certain criteria, change how results are sorted (in varying direction), and limit the number of results (while providing an offset).
|
||||
|
||||
That’s why it’s easier to use a single custom SQL query. Start with the following:
|
||||
|
||||
```sql
|
||||
SELECT id, email, username, status, verified, roles_mask, registered, last_login FROM users;
|
||||
```
|
||||
|
||||
#### Assigning roles to users
|
||||
|
||||
```php
|
||||
@@ -916,7 +958,7 @@ try {
|
||||
$auth->admin()->addRoleForUserById($userId, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown user ID
|
||||
die('Unknown user ID');
|
||||
}
|
||||
|
||||
// or
|
||||
@@ -925,7 +967,7 @@ try {
|
||||
$auth->admin()->addRoleForUserByEmail($userEmail, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// unknown email address
|
||||
die('Unknown email address');
|
||||
}
|
||||
|
||||
// or
|
||||
@@ -934,14 +976,14 @@ try {
|
||||
$auth->admin()->addRoleForUserByUsername($username, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
// unknown username
|
||||
die('Unknown username');
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
// ambiguous username
|
||||
die('Ambiguous username');
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** Changes to a user’s set of roles take effect in the local session immediately, as expected. In other sessions (e.g. on other devices), the changes may need up to five minutes to take effect, though. This increases performance and usually poses no problem. If you want to change this behavior, nevertheless, simply decrease (or perhaps increase) the value that you pass to the [`Auth` constructor](#creating-a-new-instance) as the argument named `$sessionResyncInterval`.
|
||||
**Note:** Changes to a user’s set of roles may need up to five minutes to take effect. This increases performance and usually poses no problem. If you want to change this behavior, nevertheless, simply decrease (or perhaps increase) the value that you pass to the [`Auth` constructor](#creating-a-new-instance) as the argument named `$sessionResyncInterval`.
|
||||
|
||||
#### Taking roles away from users
|
||||
|
||||
@@ -950,7 +992,7 @@ try {
|
||||
$auth->admin()->removeRoleForUserById($userId, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown user ID
|
||||
die('Unknown user ID');
|
||||
}
|
||||
|
||||
// or
|
||||
@@ -959,7 +1001,7 @@ try {
|
||||
$auth->admin()->removeRoleForUserByEmail($userEmail, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// unknown email address
|
||||
die('Unknown email address');
|
||||
}
|
||||
|
||||
// or
|
||||
@@ -968,28 +1010,28 @@ try {
|
||||
$auth->admin()->removeRoleForUserByUsername($username, \Delight\Auth\Role::ADMIN);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
// unknown username
|
||||
die('Unknown username');
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
// ambiguous username
|
||||
die('Ambiguous username');
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** Changes to a user’s set of roles take effect in the local session immediately, as expected. In other sessions (e.g. on other devices), the changes may need up to five minutes to take effect, though. This increases performance and usually poses no problem. If you want to change this behavior, nevertheless, simply decrease (or perhaps increase) the value that you pass to the [`Auth` constructor](#creating-a-new-instance) as the argument named `$sessionResyncInterval`.
|
||||
**Note:** Changes to a user’s set of roles may need up to five minutes to take effect. This increases performance and usually poses no problem. If you want to change this behavior, nevertheless, simply decrease (or perhaps increase) the value that you pass to the [`Auth` constructor](#creating-a-new-instance) as the argument named `$sessionResyncInterval`.
|
||||
|
||||
#### Checking roles
|
||||
|
||||
```php
|
||||
try {
|
||||
if ($auth->admin()->doesUserHaveRole($userId, \Delight\Auth\Role::ADMIN)) {
|
||||
// the specified user is an administrator
|
||||
echo 'The specified user is an administrator';
|
||||
}
|
||||
else {
|
||||
// the specified user is *not* an administrator
|
||||
echo 'The specified user is not an administrator';
|
||||
}
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown user ID
|
||||
die('Unknown user ID');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1006,10 +1048,10 @@ try {
|
||||
$auth->admin()->logInAsUserById($_POST['id']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown ID
|
||||
die('Unknown ID');
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email address not verified
|
||||
die('Email address not verified');
|
||||
}
|
||||
|
||||
// or
|
||||
@@ -1018,10 +1060,10 @@ try {
|
||||
$auth->admin()->logInAsUserByEmail($_POST['email']);
|
||||
}
|
||||
catch (\Delight\Auth\InvalidEmailException $e) {
|
||||
// unknown email address
|
||||
die('Unknown email address');
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email address not verified
|
||||
die('Email address not verified');
|
||||
}
|
||||
|
||||
// or
|
||||
@@ -1030,13 +1072,13 @@ try {
|
||||
$auth->admin()->logInAsUserByUsername($_POST['username']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
// unknown username
|
||||
die('Unknown username');
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
// ambiguous username
|
||||
die('Ambiguous username');
|
||||
}
|
||||
catch (\Delight\Auth\EmailNotVerifiedException $e) {
|
||||
// email address not verified
|
||||
die('Email address not verified');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1047,10 +1089,10 @@ try {
|
||||
$auth->admin()->changePasswordForUserById($_POST['id'], $_POST['newPassword']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownIdException $e) {
|
||||
// unknown ID
|
||||
die('Unknown ID');
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
// invalid password
|
||||
die('Invalid password');
|
||||
}
|
||||
|
||||
// or
|
||||
@@ -1059,13 +1101,13 @@ try {
|
||||
$auth->admin()->changePasswordForUserByUsername($_POST['username'], $_POST['newPassword']);
|
||||
}
|
||||
catch (\Delight\Auth\UnknownUsernameException $e) {
|
||||
// unknown username
|
||||
die('Unknown username');
|
||||
}
|
||||
catch (\Delight\Auth\AmbiguousUsernameException $e) {
|
||||
// ambiguous username
|
||||
die('Ambiguous username');
|
||||
}
|
||||
catch (\Delight\Auth\InvalidPasswordException $e) {
|
||||
// invalid password
|
||||
die('Invalid password');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1087,7 +1129,7 @@ is the general (mandatory) session cookie. The second (optional) cookie is only
|
||||
|
||||
You can rename the session cookie used by this library through one of the following means, in order of recommendation:
|
||||
|
||||
* In the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), find the line with the `session.name` directive and change its value to something like `session_v1`, as in:
|
||||
* In the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`), find the line with the `session.name` directive and change its value to something like `session_v1`, as in:
|
||||
|
||||
```
|
||||
session.name = session_v1
|
||||
@@ -1099,7 +1141,7 @@ You can rename the session cookie used by this library through one of the follow
|
||||
\ini_set('session.name', 'session_v1');
|
||||
```
|
||||
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`).
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`).
|
||||
|
||||
* As early as possible in your application, and before you create the `Auth` instance, call `\session_name` with an argument like `session_v1`, as in:
|
||||
|
||||
@@ -1107,7 +1149,7 @@ You can rename the session cookie used by this library through one of the follow
|
||||
\session_name('session_v1');
|
||||
```
|
||||
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`).
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`).
|
||||
|
||||
The name of the cookie for [persistent logins](#keeping-the-user-logged-in) will change as well – automatically – following your change of the session cookie’s name.
|
||||
|
||||
@@ -1121,7 +1163,7 @@ Whatever set of subdomains you choose, you should set the cookie’s attribute t
|
||||
|
||||
You can change the attribute through one of the following means, in order of recommendation:
|
||||
|
||||
* In the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), find the line with the `session.cookie_domain` directive and change its value as desired, e.g.:
|
||||
* In the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`), find the line with the `session.cookie_domain` directive and change its value as desired, e.g.:
|
||||
|
||||
```
|
||||
session.cookie_domain = example.com
|
||||
@@ -1133,7 +1175,7 @@ You can change the attribute through one of the following means, in order of rec
|
||||
\ini_set('session.cookie_domain', 'example.com');
|
||||
```
|
||||
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`).
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`).
|
||||
|
||||
#### Restricting the path where cookies are available
|
||||
|
||||
@@ -1143,7 +1185,7 @@ In most cases, you’ll want to make cookies available for all paths, i.e. any d
|
||||
|
||||
You can change the attribute through one of the following means, in order of recommendation:
|
||||
|
||||
* In the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), find the line with the `session.cookie_path` directive and change its value as desired, e.g.:
|
||||
* In the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`), find the line with the `session.cookie_path` directive and change its value as desired, e.g.:
|
||||
|
||||
```
|
||||
session.cookie_path = /
|
||||
@@ -1155,7 +1197,7 @@ You can change the attribute through one of the following means, in order of rec
|
||||
\ini_set('session.cookie_path', '/');
|
||||
```
|
||||
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`).
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`).
|
||||
|
||||
#### Controlling client-side script access to cookies
|
||||
|
||||
@@ -1165,7 +1207,7 @@ Thus, you should always set `httponly` to `1`, except for the rare cases where y
|
||||
|
||||
You can change the attribute through one of the following means, in order of recommendation:
|
||||
|
||||
* In the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), find the line with the `session.cookie_httponly` directive and change its value as desired, e.g.:
|
||||
* In the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`), find the line with the `session.cookie_httponly` directive and change its value as desired, e.g.:
|
||||
|
||||
```
|
||||
session.cookie_httponly = 1
|
||||
@@ -1177,7 +1219,7 @@ You can change the attribute through one of the following means, in order of rec
|
||||
\ini_set('session.cookie_httponly', 1);
|
||||
```
|
||||
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`).
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`).
|
||||
|
||||
#### Configuring transport security for cookies
|
||||
|
||||
@@ -1187,7 +1229,7 @@ Obviously, this solely depends on whether you are able to serve *all* pages excl
|
||||
|
||||
You can change the attribute through one of the following means, in order of recommendation:
|
||||
|
||||
* In the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), find the line with the `session.cookie_secure` directive and change its value as desired, e.g.:
|
||||
* In the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`), find the line with the `session.cookie_secure` directive and change its value as desired, e.g.:
|
||||
|
||||
```
|
||||
session.cookie_secure = 1
|
||||
@@ -1199,7 +1241,7 @@ You can change the attribute through one of the following means, in order of rec
|
||||
\ini_set('session.cookie_secure', 1);
|
||||
```
|
||||
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`).
|
||||
For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`).
|
||||
|
||||
### Utilities
|
||||
|
||||
|
@@ -12,8 +12,6 @@ use Delight\Db\PdoDatabase;
|
||||
use Delight\Db\PdoDsn;
|
||||
use Delight\Db\Throwable\Error;
|
||||
|
||||
require_once __DIR__ . '/Exceptions.php';
|
||||
|
||||
/** Component that can be used for administrative tasks by privileged and authorized users */
|
||||
final class Administration extends UserManager {
|
||||
|
||||
|
11
src/AmbiguousUsernameException.php
Normal file
11
src/AmbiguousUsernameException.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class AmbiguousUsernameException extends AuthException {}
|
11
src/AttemptCancelledException.php
Normal file
11
src/AttemptCancelledException.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class AttemptCancelledException extends AuthException {}
|
95
src/Auth.php
95
src/Auth.php
@@ -16,8 +16,6 @@ use Delight\Db\PdoDsn;
|
||||
use Delight\Db\Throwable\Error;
|
||||
use Delight\Db\Throwable\IntegrityConstraintViolationException;
|
||||
|
||||
require_once __DIR__ . '/Exceptions.php';
|
||||
|
||||
/** Component that provides all features and utilities for secure authentication of individual users */
|
||||
final class Auth extends UserManager {
|
||||
|
||||
@@ -35,7 +33,7 @@ final class Auth extends UserManager {
|
||||
|
||||
/**
|
||||
* @param PdoDatabase|PdoDsn|\PDO $databaseConnection the database connection to operate on
|
||||
* @param string $ipAddress the IP address that should be used instead of the default setting (if any), e.g. when behind a proxy
|
||||
* @param string|null $ipAddress (optional) the IP address that should be used instead of the default setting (if any), e.g. when behind a proxy
|
||||
* @param string|null $dbTablePrefix (optional) the prefix for the names of all database tables used by this component
|
||||
* @param bool|null $throttling (optional) whether throttling should be enabled (e.g. in production) or disabled (e.g. during development)
|
||||
* @param int|null $sessionResyncInterval (optional) the interval in seconds after which to resynchronize the session data with its authoritative source in the database
|
||||
@@ -962,6 +960,11 @@ final class Auth extends UserManager {
|
||||
* @throws ResetDisabledException if the user has explicitly disabled password resets for their account
|
||||
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*
|
||||
* @see canResetPasswordOrThrow
|
||||
* @see canResetPassword
|
||||
* @see resetPassword
|
||||
* @see resetPasswordAndSignIn
|
||||
*/
|
||||
public function forgotPassword($email, callable $callback, $requestExpiresAfter = null, $maxOpenRequests = null) {
|
||||
$email = self::validateEmailAddress($email);
|
||||
@@ -999,7 +1002,7 @@ final class Auth extends UserManager {
|
||||
throw new ResetDisabledException();
|
||||
}
|
||||
|
||||
$openRequests = (int) $this->getOpenPasswordResetRequests($userData['id']);
|
||||
$openRequests = $this->throttling ? (int) $this->getOpenPasswordResetRequests($userData['id']) : 0;
|
||||
|
||||
if ($openRequests < $maxOpenRequests) {
|
||||
$this->throttle([ 'requestPasswordReset', $this->getIpAddress() ], 4, (60 * 60 * 24 * 7), 2);
|
||||
@@ -1226,17 +1229,23 @@ final class Auth extends UserManager {
|
||||
/**
|
||||
* 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(...)`
|
||||
* The selector/token pair must have been generated previously by calling {@see 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
|
||||
* @return string[] an array with the user's ID at index `id` and the user's email address at index `email`
|
||||
* @throws InvalidSelectorTokenPairException if either the selector or the token was not correct
|
||||
* @throws TokenExpiredException if the token has already expired
|
||||
* @throws ResetDisabledException if the user has explicitly disabled password resets for their account
|
||||
* @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)
|
||||
*
|
||||
* @see forgotPassword
|
||||
* @see canResetPasswordOrThrow
|
||||
* @see canResetPassword
|
||||
* @see resetPasswordAndSignIn
|
||||
*/
|
||||
public function resetPassword($selector, $token, $newPassword) {
|
||||
$this->throttle([ 'resetPassword', $this->getIpAddress() ], 5, (60 * 60), 10);
|
||||
@@ -1245,7 +1254,7 @@ final class Auth extends UserManager {
|
||||
|
||||
try {
|
||||
$resetData = $this->db->selectRow(
|
||||
'SELECT a.id, a.user, a.token, a.expires, b.resettable FROM ' . $this->makeTableName('users_resets') . ' AS a JOIN ' . $this->makeTableName('users') . ' AS b ON b.id = a.user WHERE a.selector = ?',
|
||||
'SELECT a.id, a.user, a.token, a.expires, b.email, b.resettable FROM ' . $this->makeTableName('users_resets') . ' AS a JOIN ' . $this->makeTableName('users') . ' AS b ON b.id = a.user WHERE a.selector = ?',
|
||||
[ $selector ]
|
||||
);
|
||||
}
|
||||
@@ -1270,6 +1279,11 @@ final class Auth extends UserManager {
|
||||
catch (Error $e) {
|
||||
throw new DatabaseError($e->getMessage());
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => $resetData['user'],
|
||||
'email' => $resetData['email']
|
||||
];
|
||||
}
|
||||
else {
|
||||
throw new TokenExpiredException();
|
||||
@@ -1288,12 +1302,57 @@ final class Auth extends UserManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {@see forgotPassword}
|
||||
*
|
||||
* The user will be automatically signed in if this operation is successful
|
||||
*
|
||||
* @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
|
||||
* @param int|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
|
||||
* @return string[] an array with the user's ID at index `id` and the user's email address at index `email`
|
||||
* @throws InvalidSelectorTokenPairException if either the selector or the token was not correct
|
||||
* @throws TokenExpiredException if the token has already expired
|
||||
* @throws ResetDisabledException if the user has explicitly disabled password resets for their account
|
||||
* @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)
|
||||
*
|
||||
* @see forgotPassword
|
||||
* @see canResetPasswordOrThrow
|
||||
* @see canResetPassword
|
||||
* @see resetPassword
|
||||
*/
|
||||
public function resetPasswordAndSignIn($selector, $token, $newPassword, $rememberDuration = null) {
|
||||
$idAndEmail = $this->resetPassword($selector, $token, $newPassword);
|
||||
|
||||
if (!$this->isLoggedIn()) {
|
||||
$idAndEmail['email'] = self::validateEmailAddress($idAndEmail['email']);
|
||||
|
||||
$userData = $this->getUserDataByEmailAddress(
|
||||
$idAndEmail['email'],
|
||||
[ 'username', 'status', 'roles_mask', 'force_logout' ]
|
||||
);
|
||||
|
||||
$this->onLoginSuccessful($idAndEmail['id'], $idAndEmail['email'], $userData['username'], $userData['status'], $userData['roles_mask'], $userData['force_logout'], true);
|
||||
|
||||
if ($rememberDuration !== null) {
|
||||
$this->createRememberDirective($idAndEmail['id'], $rememberDuration);
|
||||
}
|
||||
}
|
||||
|
||||
return $idAndEmail;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the supplied selector/token pair can be used to reset a password
|
||||
*
|
||||
* The password can be reset using the supplied information if this method does *not* throw any exception
|
||||
*
|
||||
* The selector/token pair must have been generated previously by calling `Auth#forgotPassword(...)`
|
||||
* The selector/token pair must have been generated previously by calling {@see forgotPassword}
|
||||
*
|
||||
* @param string $selector the selector from the selector/token pair
|
||||
* @param string $token the token from the selector/token pair
|
||||
@@ -1302,6 +1361,11 @@ final class Auth extends UserManager {
|
||||
* @throws ResetDisabledException if the user has explicitly disabled password resets for their account
|
||||
* @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*
|
||||
* @see forgotPassword
|
||||
* @see canResetPassword
|
||||
* @see resetPassword
|
||||
* @see resetPasswordAndSignIn
|
||||
*/
|
||||
public function canResetPasswordOrThrow($selector, $token) {
|
||||
try {
|
||||
@@ -1325,12 +1389,17 @@ final class Auth extends UserManager {
|
||||
/**
|
||||
* 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(...)`
|
||||
* The selector/token pair must have been generated previously by calling {@see 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)
|
||||
*
|
||||
* @see forgotPassword
|
||||
* @see canResetPasswordOrThrow
|
||||
* @see resetPassword
|
||||
* @see resetPasswordAndSignIn
|
||||
*/
|
||||
public function canResetPassword($selector, $token) {
|
||||
try {
|
||||
@@ -1433,7 +1502,7 @@ final class Auth extends UserManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Shorthand/alias for `getUserId()`
|
||||
* Shorthand/alias for {@see getUserId}
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
@@ -1659,12 +1728,16 @@ final class Auth extends UserManager {
|
||||
* @param int|null $burstiness (optional) the permitted degree of variation or unevenness during peaks (>= 1)
|
||||
* @param bool|null $simulated (optional) whether to simulate a dry run instead of actually consuming the requested units
|
||||
* @param int|null $cost (optional) the number of units to request (>= 1)
|
||||
* @param bool|null $force (optional) whether to apply throttling locally (with this call) even when throttling has been disabled globally (on the instance, via the constructor option)
|
||||
* @return float the number of units remaining from the supply
|
||||
* @throws TooManyRequestsException if the actual demand has exceeded the designated supply
|
||||
* @throws AuthError if an internal problem occurred (do *not* catch)
|
||||
*/
|
||||
public function throttle(array $criteria, $supply, $interval, $burstiness = null, $simulated = null, $cost = null) {
|
||||
if (!$this->throttling) {
|
||||
public function throttle(array $criteria, $supply, $interval, $burstiness = null, $simulated = null, $cost = null, $force = null) {
|
||||
// validate the supplied parameters and set appropriate defaults where necessary
|
||||
$force = ($force !== null) ? (bool) $force : false;
|
||||
|
||||
if (!$this->throttling && !$force) {
|
||||
return $supply;
|
||||
}
|
||||
|
||||
|
12
src/AuthError.php
Normal file
12
src/AuthError.php
Normal file
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
/** Base class for all (unchecked) errors */
|
||||
class AuthError extends \Exception {}
|
12
src/AuthException.php
Normal file
12
src/AuthException.php
Normal file
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
/** Base class for all (checked) exceptions */
|
||||
class AuthException extends \Exception {}
|
11
src/ConfirmationRequestNotFound.php
Normal file
11
src/ConfirmationRequestNotFound.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class ConfirmationRequestNotFound extends AuthException {}
|
11
src/DatabaseError.php
Normal file
11
src/DatabaseError.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class DatabaseError extends AuthError {}
|
11
src/DuplicateUsernameException.php
Normal file
11
src/DuplicateUsernameException.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class DuplicateUsernameException extends AuthException {}
|
11
src/EmailNotVerifiedException.php
Normal file
11
src/EmailNotVerifiedException.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class EmailNotVerifiedException extends AuthException {}
|
11
src/EmailOrUsernameRequiredError.php
Normal file
11
src/EmailOrUsernameRequiredError.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class EmailOrUsernameRequiredError extends AuthError {}
|
@@ -1,51 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class AuthException extends \Exception {}
|
||||
|
||||
class UnknownIdException extends AuthException {}
|
||||
|
||||
class InvalidEmailException extends AuthException {}
|
||||
|
||||
class UnknownUsernameException extends AuthException {}
|
||||
|
||||
class InvalidPasswordException extends AuthException {}
|
||||
|
||||
class EmailNotVerifiedException extends AuthException {}
|
||||
|
||||
class UserAlreadyExistsException extends AuthException {}
|
||||
|
||||
class NotLoggedInException extends AuthException {}
|
||||
|
||||
class InvalidSelectorTokenPairException extends AuthException {}
|
||||
|
||||
class TokenExpiredException extends AuthException {}
|
||||
|
||||
class TooManyRequestsException extends AuthException {}
|
||||
|
||||
class DuplicateUsernameException extends AuthException {}
|
||||
|
||||
class AmbiguousUsernameException extends AuthException {}
|
||||
|
||||
class AttemptCancelledException extends AuthException {}
|
||||
|
||||
class ResetDisabledException extends AuthException {}
|
||||
|
||||
class ConfirmationRequestNotFound extends AuthException {}
|
||||
|
||||
class AuthError extends \Exception {}
|
||||
|
||||
class DatabaseError extends AuthError {}
|
||||
|
||||
class MissingCallbackError extends AuthError {}
|
||||
|
||||
class HeadersAlreadySentError extends AuthError {}
|
||||
|
||||
class EmailOrUsernameRequiredError extends AuthError {}
|
11
src/HeadersAlreadySentError.php
Normal file
11
src/HeadersAlreadySentError.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class HeadersAlreadySentError extends AuthError {}
|
11
src/InvalidEmailException.php
Normal file
11
src/InvalidEmailException.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class InvalidEmailException extends AuthException {}
|
11
src/InvalidPasswordException.php
Normal file
11
src/InvalidPasswordException.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class InvalidPasswordException extends AuthException {}
|
11
src/InvalidSelectorTokenPairException.php
Normal file
11
src/InvalidSelectorTokenPairException.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class InvalidSelectorTokenPairException extends AuthException {}
|
11
src/MissingCallbackError.php
Normal file
11
src/MissingCallbackError.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class MissingCallbackError extends AuthError {}
|
11
src/NotLoggedInException.php
Normal file
11
src/NotLoggedInException.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class NotLoggedInException extends AuthException {}
|
11
src/ResetDisabledException.php
Normal file
11
src/ResetDisabledException.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class ResetDisabledException extends AuthException {}
|
11
src/TokenExpiredException.php
Normal file
11
src/TokenExpiredException.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class TokenExpiredException extends AuthException {}
|
11
src/TooManyRequestsException.php
Normal file
11
src/TooManyRequestsException.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class TooManyRequestsException extends AuthException {}
|
11
src/UnknownIdException.php
Normal file
11
src/UnknownIdException.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class UnknownIdException extends AuthException {}
|
11
src/UnknownUsernameException.php
Normal file
11
src/UnknownUsernameException.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class UnknownUsernameException extends AuthException {}
|
11
src/UserAlreadyExistsException.php
Normal file
11
src/UserAlreadyExistsException.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
class UserAlreadyExistsException extends AuthException {}
|
@@ -15,8 +15,6 @@ use Delight\Db\PdoDsn;
|
||||
use Delight\Db\Throwable\Error;
|
||||
use Delight\Db\Throwable\IntegrityConstraintViolationException;
|
||||
|
||||
require_once __DIR__ . '/Exceptions.php';
|
||||
|
||||
/**
|
||||
* Abstract base class for components implementing user management
|
||||
*
|
||||
|
@@ -254,9 +254,21 @@ function processRequestData(\Delight\Auth\Auth $auth) {
|
||||
}
|
||||
else if ($_POST['action'] === 'resetPassword') {
|
||||
try {
|
||||
$auth->resetPassword($_POST['selector'], $_POST['token'], $_POST['password']);
|
||||
if (isset($_POST['login']) && $_POST['login'] > 0) {
|
||||
if ($_POST['login'] == 2) {
|
||||
// keep logged in for one year
|
||||
$rememberDuration = (int) (60 * 60 * 24 * 365.25);
|
||||
}
|
||||
else {
|
||||
// do not keep logged in after session ends
|
||||
$rememberDuration = null;
|
||||
}
|
||||
|
||||
return 'ok';
|
||||
return $auth->resetPasswordAndSignIn($_POST['selector'], $_POST['token'], $_POST['password'], $rememberDuration);
|
||||
}
|
||||
else {
|
||||
return $auth->resetPassword($_POST['selector'], $_POST['token'], $_POST['password']);
|
||||
}
|
||||
}
|
||||
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
|
||||
return 'invalid token';
|
||||
@@ -893,6 +905,11 @@ function showGuestUserForm() {
|
||||
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 '<select name="login" size="1">';
|
||||
echo '<option value="0">Sign in automatically? — No</option>';
|
||||
echo '<option value="1">Sign in automatically? — Yes</option>';
|
||||
echo '<option value="2">Sign in automatically? — Yes (and remember)</option>';
|
||||
echo '</select> ';
|
||||
echo '<button type="submit">Reset password</button>';
|
||||
echo '</form>';
|
||||
|
||||
|
Reference in New Issue
Block a user