1
0
mirror of https://github.com/delight-im/PHP-Auth.git synced 2025-08-05 23:57:24 +02:00

21 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
6 changed files with 443 additions and 290 deletions

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.

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,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.
@@ -140,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 {
@@ -199,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.
@@ -225,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()) {
@@ -238,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();
@@ -248,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();
@@ -256,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();
@@ -266,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()) {
@@ -279,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

@@ -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": []

View File

@@ -8,6 +8,13 @@
namespace Delight\Auth;
use Delight\Cookie\Cookie;
use Delight\Cookie\Session;
use Delight\Db\PdoDatabase;
use Delight\Db\PdoDsn;
use Delight\Db\Throwable\Error;
use Delight\Db\Throwable\IntegrityConstraintViolationException;
require __DIR__.'/Base64.php';
require __DIR__.'/Exceptions.php';
@@ -27,7 +34,7 @@ class Auth {
const THROTTLE_ACTION_CONSUME_TOKEN = 'confirm_email';
const HTTP_STATUS_CODE_TOO_MANY_REQUESTS = 429;
/** @var \PDO the database connection that will be used */
/** @var PdoDatabase the database connection that will be used */
private $db;
/** @var boolean whether HTTPS (TLS/SSL) will be used (recommended) */
private $useHttps;
@@ -41,13 +48,25 @@ class Auth {
private $throttlingTimeBucketSize;
/**
* @param \PDO $databaseConnection the database connection that will be used
* @param PdoDatabase|PdoDsn|\PDO $databaseConnection the database connection that will be used
* @param bool $useHttps whether HTTPS (TLS/SSL) will be used (recommended)
* @param bool $allowCookiesScriptAccess whether cookies should be accessible via client-side scripts (*not* recommended)
* @param string $ipAddress the IP address that should be used instead of the default setting (if any), e.g. when behind a proxy
*/
public function __construct(\PDO $databaseConnection, $useHttps = false, $allowCookiesScriptAccess = false, $ipAddress = null) {
$this->db = $databaseConnection;
public function __construct($databaseConnection, $useHttps = false, $allowCookiesScriptAccess = false, $ipAddress = null) {
if ($databaseConnection instanceof PdoDatabase) {
$this->db = $databaseConnection;
}
elseif ($databaseConnection instanceof PdoDsn) {
$this->db = PdoDatabase::fromDsn($databaseConnection);
}
elseif ($databaseConnection instanceof \PDO) {
$this->db = PdoDatabase::fromPdo($databaseConnection, true);
}
else {
throw new \InvalidArgumentException('The database connection must be an instance of either `PdoDatabase`, `PdoDsn` or `PDO`');
}
$this->useHttps = $useHttps;
$this->allowCookiesScriptAccess = $allowCookiesScriptAccess;
$this->ipAddress = empty($ipAddress) ? $_SERVER['REMOTE_ADDR'] : $ipAddress;
@@ -75,7 +94,7 @@ class Auth {
session_set_cookie_params($params['lifetime'], $params['path'], $params['domain'], $params['secure'], $params['httponly']);
// start the session
@\Delight\Cookie\Session::start();
@Session::start();
}
/** Improves the application's security over HTTP(S) by setting specific headers */
@@ -107,15 +126,20 @@ class Auth {
$parts = explode(self::COOKIE_CONTENT_SEPARATOR, $_COOKIE[self::COOKIE_NAME_REMEMBER], 2);
// if both selector and token were found
if (isset($parts[0]) && isset($parts[1])) {
$stmt = $this->db->prepare("SELECT a.user, a.token, a.expires, b.email, b.username FROM users_remembered AS a JOIN users AS b ON a.user = b.id WHERE a.selector = :selector");
$stmt->bindValue(':selector', $parts[0], \PDO::PARAM_STR);
if ($stmt->execute()) {
$rememberData = $stmt->fetch(\PDO::FETCH_ASSOC);
if ($rememberData !== false) {
if ($rememberData['expires'] >= time()) {
if (password_verify($parts[1], $rememberData['token'])) {
$this->onLoginSuccessful($rememberData['user'], $rememberData['email'], $rememberData['username'], true);
}
try {
$rememberData = $this->db->selectRow(
'SELECT a.user, a.token, a.expires, b.email, b.username FROM users_remembered AS a JOIN users AS b ON a.user = b.id WHERE a.selector = ?',
[ $parts[0] ]
);
}
catch (Error $e) {
throw new DatabaseError();
}
if (!empty($rememberData)) {
if ($rememberData['expires'] >= time()) {
if (password_verify($parts[1], $rememberData['token'])) {
$this->onLoginSuccessful($rememberData['user'], $rememberData['email'], $rememberData['username'], true);
}
}
}
@@ -159,53 +183,33 @@ class Auth {
$password = password_hash($password, PASSWORD_DEFAULT);
$verified = isset($callback) && is_callable($callback) ? 0 : 1;
$stmt = $this->db->prepare("INSERT INTO users (email, password, username, verified, registered) VALUES (:email, :password, :username, :verified, :registered)");
$stmt->bindValue(':email', $email, \PDO::PARAM_STR);
$stmt->bindValue(':password', $password, \PDO::PARAM_STR);
$stmt->bindValue(':username', $username, \PDO::PARAM_STR);
$stmt->bindValue(':verified', $verified, \PDO::PARAM_INT);
$stmt->bindValue(':registered', time(), \PDO::PARAM_INT);
try {
$result = $stmt->execute();
$this->db->insert(
'users',
[
'email' => $email,
'password' => $password,
'username' => $username,
'verified' => $verified,
'registered' => time()
]
);
}
catch (\PDOException $e) {
catch (IntegrityConstraintViolationException $e) {
// if we have a duplicate entry
if ($e->getCode() == '23000') {
throw new UserAlreadyExistsException();
}
// if we have another error
else {
// throw an exception
throw new DatabaseError(null, null, $e);
}
throw new UserAlreadyExistsException();
}
// if creating the new user was successful
if ($result) {
// get the ID of the user that we've just created
$stmt = $this->db->prepare("SELECT id FROM users WHERE email = :email");
$stmt->bindValue(':email', $email, \PDO::PARAM_STR);
if ($result = $stmt->execute()) {
$newUserId = $stmt->fetchColumn();
}
else {
$newUserId = null;
}
if ($verified === 1) {
return $newUserId;
}
else {
$this->createConfirmationRequest($email, $callback);
return $newUserId;
}
}
else {
catch (Error $e) {
throw new DatabaseError();
}
$newUserId = (int) $this->db->getLastInsertId();
if ($verified === 0) {
$this->createConfirmationRequest($email, $callback);
}
return $newUserId;
}
/**
@@ -227,26 +231,30 @@ class Auth {
$selector = self::createRandomString(16);
$token = self::createRandomString(16);
$tokenHashed = password_hash($token, PASSWORD_DEFAULT);
$expires = time() + 3600 * 24;
$stmt = $this->db->prepare("INSERT INTO users_confirmations (email, selector, token, expires) VALUES (:email, :selector, :token, :expires)");
$stmt->bindValue(':email', $email, \PDO::PARAM_STR);
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
$stmt->bindValue(':token', $tokenHashed, \PDO::PARAM_STR);
$stmt->bindValue(':expires', $expires, \PDO::PARAM_INT);
// the request shall be valid for one day
$expires = time() + 60 * 60 * 24;
if ($stmt->execute()) {
if (isset($callback) && is_callable($callback)) {
$callback($selector, $token);
}
else {
throw new MissingCallbackError();
}
try {
$this->db->insert(
'users_confirmations',
[
'email' => $email,
'selector' => $selector,
'token' => $tokenHashed,
'expires' => $expires
]
);
}
catch (Error $e) {
throw new DatabaseError();
}
return;
if (isset($callback) && is_callable($callback)) {
$callback($selector, $token);
}
else {
throw new DatabaseError();
throw new MissingCallbackError();
}
}
@@ -255,57 +263,67 @@ 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);
$stmt = $this->db->prepare("SELECT id, password, verified, username FROM users WHERE email = :email");
$stmt->bindValue(':email', $email, \PDO::PARAM_STR);
if ($stmt->execute()) {
$userData = $stmt->fetch(\PDO::FETCH_ASSOC);
if ($userData !== false) {
if (password_verify($password, $userData['password'])) {
// if the password needs to be re-hashed to keep up with improving password cracking techniques
if (password_needs_rehash($userData['password'], PASSWORD_DEFAULT)) {
// create a new hash from the password and update it in the database
$this->updatePassword($userData['id'], $password);
try {
$userData = $this->db->selectRow(
'SELECT id, password, verified, username FROM users WHERE email = ?',
[ $email ]
);
}
catch (Error $e) {
throw new DatabaseError();
}
if (!empty($userData)) {
if (password_verify($password, $userData['password'])) {
// if the password needs to be re-hashed to keep up with improving password cracking techniques
if (password_needs_rehash($userData['password'], PASSWORD_DEFAULT)) {
// create a new hash from the password and update it in the database
$this->updatePassword($userData['id'], $password);
}
if ($userData['verified'] === 1) {
$this->onLoginSuccessful($userData['id'], $email, $userData['username'], false);
// continue to support the old parameter format
if ($rememberDuration === true) {
$rememberDuration = 60 * 60 * 24 * 28;
}
elseif ($rememberDuration === false) {
$rememberDuration = null;
}
if ($userData['verified'] == 1) {
$this->onLoginSuccessful($userData['id'], $email, $userData['username'], false);
if ($remember) {
$this->createRememberDirective($userData['id']);
}
return;
}
else {
throw new EmailNotVerifiedException();
if ($rememberDuration !== null) {
$this->createRememberDirective($userData['id'], $rememberDuration);
}
return;
}
else {
$this->throttle(self::THROTTLE_ACTION_LOGIN);
$this->throttle(self::THROTTLE_ACTION_LOGIN, $email);
throw new InvalidPasswordException();
throw new EmailNotVerifiedException();
}
}
else {
$this->throttle(self::THROTTLE_ACTION_LOGIN);
$this->throttle(self::THROTTLE_ACTION_LOGIN, $email);
throw new InvalidEmailException();
throw new InvalidPasswordException();
}
}
else {
throw new DatabaseError();
$this->throttle(self::THROTTLE_ACTION_LOGIN);
$this->throttle(self::THROTTLE_ACTION_LOGIN, $email);
throw new InvalidEmailException();
}
}
@@ -355,28 +373,31 @@ 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);
$stmt = $this->db->prepare("INSERT INTO users_remembered (user, selector, token, expires) VALUES (:user, :selector, :token, :expires)");
$stmt->bindValue(':user', $userId, \PDO::PARAM_INT);
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
$stmt->bindValue(':token', $tokenHashed, \PDO::PARAM_STR);
$stmt->bindValue(':expires', $expires, \PDO::PARAM_INT);
if ($stmt->execute()) {
$this->setRememberCookie($selector, $token, $expires);
return;
try {
$this->db->insert(
'users_remembered',
[
'user' => $userId,
'selector' => $selector,
'token' => $tokenHashed,
'expires' => $expires
]
);
}
else {
catch (Error $e) {
throw new DatabaseError();
}
$this->setRememberCookie($selector, $token, $expires);
}
/**
@@ -386,17 +407,17 @@ class Auth {
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
private function deleteRememberDirective($userId) {
$stmt = $this->db->prepare("DELETE FROM users_remembered WHERE user = :user");
$stmt->bindValue(':user', $userId, \PDO::PARAM_INT);
if ($stmt->execute()) {
$this->setRememberCookie(null, null, time() - 3600);
return;
try {
$this->db->delete(
'users_remembered',
[ 'user' => $userId ]
);
}
else {
catch (Error $e) {
throw new DatabaseError();
}
$this->setRememberCookie(null, null, time() - 3600);
}
/**
@@ -419,7 +440,7 @@ class Auth {
}
// set the cookie with the selector and token
$cookie = new \Delight\Cookie\Cookie(self::COOKIE_NAME_REMEMBER);
$cookie = new Cookie(self::COOKIE_NAME_REMEMBER);
$cookie->setValue($content);
$cookie->setExpiryTime($expires);
if (!empty($params['path'])) {
@@ -444,15 +465,22 @@ class Auth {
* @param string $email the email address of the user who has just logged in
* @param string $username the username (if any)
* @param bool $remembered whether the user was remembered ("remember me") or logged in actively
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
private function onLoginSuccessful($userId, $email, $username, $remembered) {
$stmt = $this->db->prepare("UPDATE users SET last_login = :lastLogin WHERE id = :id");
$stmt->bindValue(':lastLogin', time(), \PDO::PARAM_INT);
$stmt->bindValue(':id', $userId, \PDO::PARAM_INT);
$stmt->execute();
try {
$this->db->update(
'users',
[ 'last_login' => time() ],
[ 'id' => $userId ]
);
}
catch (Error $e) {
throw new DatabaseError();
}
// re-generate the session ID to prevent session fixation attacks
\Delight\Cookie\Session::regenerate(true);
Session::regenerate(true);
// save the user data in the session
$this->setLoggedIn(true);
@@ -499,7 +527,7 @@ class Auth {
$params = $this->createCookieSettings();
// cause the session cookie to be deleted
$cookie = new \Delight\Cookie\Cookie(session_name());
$cookie = new Cookie(session_name());
if (!empty($params['path'])) {
$cookie->setPath($params['path']);
}
@@ -530,36 +558,42 @@ class Auth {
$this->throttle(self::THROTTLE_ACTION_CONSUME_TOKEN);
$this->throttle(self::THROTTLE_ACTION_CONSUME_TOKEN, $selector);
$stmt = $this->db->prepare("SELECT id, email, token, expires FROM users_confirmations WHERE selector = :selector");
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
if ($stmt->execute()) {
$confirmationData = $stmt->fetch(\PDO::FETCH_ASSOC);
if ($confirmationData !== false) {
if (password_verify($token, $confirmationData['token'])) {
if ($confirmationData['expires'] >= time()) {
$stmt = $this->db->prepare("UPDATE users SET verified = :verified WHERE email = :email");
$stmt->bindValue(':verified', 1, \PDO::PARAM_INT);
$stmt->bindValue(':email', $confirmationData['email'], \PDO::PARAM_STR);
if ($stmt->execute()) {
$stmt = $this->db->prepare("DELETE FROM users_confirmations WHERE id = :id");
$stmt->bindValue(':id', $confirmationData['id'], \PDO::PARAM_INT);
if ($stmt->execute()) {
return;
}
else {
throw new DatabaseError();
}
}
else {
throw new DatabaseError();
}
try {
$confirmationData = $this->db->selectRow(
'SELECT id, email, token, expires FROM users_confirmations WHERE selector = ?',
[ $selector ]
);
}
catch (Error $e) {
throw new DatabaseError();
}
if (!empty($confirmationData)) {
if (password_verify($token, $confirmationData['token'])) {
if ($confirmationData['expires'] >= time()) {
try {
$this->db->update(
'users',
[ 'verified' => 1 ],
[ 'email' => $confirmationData['email'] ]
);
}
else {
throw new TokenExpiredException();
catch (Error $e) {
throw new DatabaseError();
}
try {
$this->db->delete(
'users_confirmations',
[ 'id' => $confirmationData['id'] ]
);
}
catch (Error $e) {
throw new DatabaseError();
}
}
else {
throw new InvalidSelectorTokenPairException();
throw new TokenExpiredException();
}
}
else {
@@ -567,7 +601,7 @@ class Auth {
}
}
else {
throw new DatabaseError();
throw new InvalidSelectorTokenPairException();
}
}
@@ -587,21 +621,30 @@ class Auth {
$userId = $this->getUserId();
$stmt = $this->db->prepare("SELECT password FROM users WHERE id = :userId");
$stmt->bindValue(':userId', $userId, \PDO::PARAM_INT);
if ($stmt->execute()) {
$passwordInDatabase = $stmt->fetchColumn();
try {
$passwordInDatabase = $this->db->selectValue(
'SELECT password FROM users WHERE id = ?',
[ $userId ]
);
}
catch (Error $e) {
throw new DatabaseError();
}
if (!empty($passwordInDatabase)) {
if (password_verify($oldPassword, $passwordInDatabase)) {
// update the password in the database
$this->updatePassword($userId, $newPassword);
return;
// delete any remaining remember directives
$this->deleteRememberDirective($userId);
}
else {
throw new InvalidPasswordException();
}
}
else {
throw new DatabaseError();
throw new NotLoggedInException();
}
}
else {
@@ -614,14 +657,21 @@ class Auth {
*
* @param int $userId the ID of the user whose password should be updated
* @param string $newPassword the new password
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
private function updatePassword($userId, $newPassword) {
$newPassword = password_hash($newPassword, PASSWORD_DEFAULT);
$stmt = $this->db->prepare("UPDATE users SET password = :password WHERE id = :userId");
$stmt->bindValue(':password', $newPassword, \PDO::PARAM_STR);
$stmt->bindValue(':userId', $userId, \PDO::PARAM_INT);
$stmt->execute();
try {
$this->db->update(
'users',
[ 'password' => $newPassword ],
[ 'id' => $userId ]
);
}
catch (Error $e) {
throw new DatabaseError();
}
}
/**
@@ -682,21 +732,21 @@ class Auth {
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
private function getUserIdByEmailAddress($email) {
$stmt = $this->db->prepare("SELECT id FROM users WHERE email = :email");
$stmt->bindValue(':email', $email, \PDO::PARAM_STR);
try {
$userId = $this->db->selectValue(
'SELECT id FROM users WHERE email = ?',
[ $email ]
);
}
catch (Error $e) {
throw new DatabaseError();
}
if ($stmt->execute()) {
$userId = $stmt->fetchColumn();
if ($userId !== false) {
return $userId;
}
else {
throw new InvalidEmailException();
}
if (!empty($userId)) {
return $userId;
}
else {
throw new DatabaseError();
throw new InvalidEmailException();
}
}
@@ -708,14 +758,23 @@ class Auth {
* @throws AuthError if an internal problem occurred (do *not* catch)
*/
private function getOpenPasswordResetRequests($userId) {
$stmt = $this->db->prepare("SELECT COUNT(*) FROM users_resets WHERE user = :userId AND expires > :expiresAfter");
$stmt->bindValue(':userId', $userId, \PDO::PARAM_INT);
$stmt->bindValue(':expiresAfter', time(), \PDO::PARAM_INT);
try {
$requests = $this->db->selectValue(
'SELECT COUNT(*) FROM users_resets WHERE user = ? AND expires > ?',
[
$userId,
time()
]
);
if ($stmt->execute()) {
return $stmt->fetchColumn();
if (!empty($requests)) {
return $requests;
}
else {
return 0;
}
}
else {
catch (Error $e) {
throw new DatabaseError();
}
}
@@ -742,24 +801,26 @@ class Auth {
$tokenHashed = password_hash($token, PASSWORD_DEFAULT);
$expiresAt = time() + $expiresAfter;
$stmt = $this->db->prepare("INSERT INTO users_resets (user, selector, token, expires) VALUES (:userId, :selector, :token, :expires)");
$stmt->bindValue(':userId', $userId, \PDO::PARAM_INT);
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
$stmt->bindValue(':token', $tokenHashed, \PDO::PARAM_STR);
$stmt->bindValue(':expires', $expiresAt, \PDO::PARAM_INT);
try {
$this->db->insert(
'users_resets',
[
'user' => $userId,
'selector' => $selector,
'token' => $tokenHashed,
'expires' => $expiresAt
]
);
}
catch (Error $e) {
throw new DatabaseError();
}
if ($stmt->execute()) {
if (isset($callback) && is_callable($callback)) {
$callback($selector, $token);
}
else {
throw new MissingCallbackError();
}
return;
if (isset($callback) && is_callable($callback)) {
$callback($selector, $token);
}
else {
throw new DatabaseError();
throw new MissingCallbackError();
}
}
@@ -781,34 +842,39 @@ class Auth {
$this->throttle(self::THROTTLE_ACTION_CONSUME_TOKEN);
$this->throttle(self::THROTTLE_ACTION_CONSUME_TOKEN, $selector);
$stmt = $this->db->prepare("SELECT id, user, token, expires FROM users_resets WHERE selector = :selector");
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
if ($stmt->execute()) {
$resetData = $stmt->fetch(\PDO::FETCH_ASSOC);
try {
$resetData = $this->db->selectRow(
'SELECT id, user, token, expires FROM users_resets WHERE selector = ?',
[ $selector ]
);
}
catch (Error $e) {
throw new DatabaseError();
}
if ($resetData !== false) {
if (password_verify($token, $resetData['token'])) {
if ($resetData['expires'] >= time()) {
$newPassword = self::validatePassword($newPassword);
if (!empty($resetData)) {
if (password_verify($token, $resetData['token'])) {
if ($resetData['expires'] >= time()) {
$newPassword = self::validatePassword($newPassword);
$this->updatePassword($resetData['user'], $newPassword);
// update the password in the database
$this->updatePassword($resetData['user'], $newPassword);
$stmt = $this->db->prepare("DELETE FROM users_resets WHERE id = :id");
$stmt->bindValue(':id', $resetData['id'], \PDO::PARAM_INT);
// delete any remaining remember directives
$this->deleteRememberDirective($resetData['user']);
if ($stmt->execute()) {
return;
}
else {
throw new DatabaseError();
}
try {
$this->db->delete(
'users_resets',
[ 'id' => $resetData['id'] ]
);
}
else {
throw new TokenExpiredException();
catch (Error $e) {
throw new DatabaseError();
}
}
else {
throw new InvalidSelectorTokenPairException();
throw new TokenExpiredException();
}
}
else {
@@ -816,7 +882,7 @@ class Auth {
}
}
else {
throw new DatabaseError();
throw new InvalidSelectorTokenPairException();
}
}
@@ -1030,42 +1096,55 @@ class Auth {
// get the time bucket that we do the throttling for
$timeBucket = self::getTimeBucket();
$stmt = $this->db->prepare('INSERT INTO users_throttling (action_type, selector, time_bucket, attempts) VALUES (:actionType, :selector, :timeBucket, 1)');
$stmt->bindValue(':actionType', $actionType, \PDO::PARAM_STR);
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
$stmt->bindValue(':timeBucket', $timeBucket, \PDO::PARAM_INT);
try {
$stmt->execute();
$this->db->insert(
'users_throttling',
[
'action_type' => $actionType,
'selector' => $selector,
'time_bucket' => $timeBucket,
'attempts' => 1
]
);
}
catch (\PDOException $e) {
// if we have a duplicate entry
if ($e->getCode() == '23000') {
// update the old entry
$stmt = $this->db->prepare('UPDATE users_throttling SET attempts = attempts+1 WHERE action_type = :actionType AND selector = :selector AND time_bucket = :timeBucket');
$stmt->bindValue(':actionType', $actionType, \PDO::PARAM_STR);
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
$stmt->bindValue(':timeBucket', $timeBucket, \PDO::PARAM_INT);
$stmt->execute();
catch (IntegrityConstraintViolationException $e) {
// if we have a duplicate entry, update the old entry
try {
$this->db->exec(
'UPDATE users_throttling SET attempts = attempts+1 WHERE action_type = ? AND selector = ? AND time_bucket = ?',
[
$actionType,
$selector,
$timeBucket
]
);
}
// if we have another error
else {
// throw an exception
throw new DatabaseError(null, null, $e);
catch (Error $e) {
throw new DatabaseError();
}
}
catch (Error $e) {
throw new DatabaseError();
}
$stmt = $this->db->prepare('SELECT attempts FROM users_throttling WHERE action_type = :actionType AND selector = :selector AND time_bucket = :timeBucket');
$stmt->bindValue(':actionType', $actionType, \PDO::PARAM_STR);
$stmt->bindValue(':selector', $selector, \PDO::PARAM_STR);
$stmt->bindValue(':timeBucket', $timeBucket, \PDO::PARAM_INT);
if ($stmt->execute()) {
$attempts = $stmt->fetchColumn();
try {
$attempts = $this->db->selectValue(
'SELECT attempts FROM users_throttling WHERE action_type = ? AND selector = ? AND time_bucket = ?',
[
$actionType,
$selector,
$timeBucket
]
);
}
catch (Error $e) {
throw new DatabaseError();
}
if ($attempts !== false) {
// if the number of attempts has acceeded our accepted limit
if ($attempts > $this->throttlingActionsPerTimeBucket) {
self::onTooManyRequests($this->throttlingTimeBucketSize);
}
if (!empty($attempts)) {
// if the number of attempts has acceeded our accepted limit
if ($attempts > $this->throttlingActionsPerTimeBucket) {
self::onTooManyRequests($this->throttlingTimeBucketSize);
}
}
}

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';
}
@@ -249,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>';