├── .gitignore ├── .editorconfig ├── src ├── DatabaseError.php ├── MissingCallbackError.php ├── NotLoggedInException.php ├── UnknownIdException.php ├── HeadersAlreadySentError.php ├── InvalidEmailException.php ├── ResetDisabledException.php ├── TokenExpiredException.php ├── AttemptCancelledException.php ├── EmailNotVerifiedException.php ├── InvalidPasswordException.php ├── TooManyRequestsException.php ├── UnknownUsernameException.php ├── AmbiguousUsernameException.php ├── ConfirmationRequestNotFound.php ├── DuplicateUsernameException.php ├── EmailOrUsernameRequiredError.php ├── UserAlreadyExistsException.php ├── AuthError.php ├── InvalidSelectorTokenPairException.php ├── AuthException.php ├── Status.php ├── Role.php ├── UserManager.php └── Administration.php ├── composer.json ├── LICENSE ├── Database ├── PostgreSQL.sql ├── SQLite.sql └── MySQL.sql ├── composer.lock ├── Migration.md ├── tests └── index.php └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # IntelliJ 2 | .idea/ 3 | 4 | # Composer 5 | vendor/ 6 | composer.phar 7 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = tab 7 | trim_trailing_whitespace = true 8 | end_of_line = lf 9 | insert_final_newline = true 10 | 11 | [*.md] 12 | indent_style = space 13 | indent_size = 4 14 | -------------------------------------------------------------------------------- /src/DatabaseError.php: -------------------------------------------------------------------------------- 1 | =7.2.0", 6 | "ext-openssl": "*", 7 | "delight-im/base64": "^1.0", 8 | "delight-im/db": "^1.3" 9 | }, 10 | "type": "library", 11 | "keywords": [ "psr", "php-auth", "auth", "authentication", "login", "security" ], 12 | "homepage": "https://github.com/gotzmann/auth", 13 | "license": "MIT", 14 | "autoload": { 15 | "psr-4": { 16 | "Comet\\": "src/" 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) delight.im (https://www.delight.im/) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/Role.php: -------------------------------------------------------------------------------- 1 | getConstants()); 53 | } 54 | 55 | /** 56 | * Returns the descriptive role names 57 | * 58 | * @return string[] 59 | */ 60 | public static function getNames() { 61 | $reflectionClass = new \ReflectionClass(static::class); 62 | 63 | return \array_keys($reflectionClass->getConstants()); 64 | } 65 | 66 | /** 67 | * Returns the numerical role values 68 | * 69 | * @return int[] 70 | */ 71 | public static function getValues() { 72 | $reflectionClass = new \ReflectionClass(static::class); 73 | 74 | return \array_values($reflectionClass->getConstants()); 75 | } 76 | 77 | private function __construct() {} 78 | 79 | } 80 | -------------------------------------------------------------------------------- /Database/PostgreSQL.sql: -------------------------------------------------------------------------------- 1 | -- PHP-Auth (https://github.com/delight-im/PHP-Auth) 2 | -- Copyright (c) delight.im (https://www.delight.im/) 3 | -- Licensed under the MIT License (https://opensource.org/licenses/MIT) 4 | 5 | BEGIN; 6 | 7 | CREATE TABLE IF NOT EXISTS "users" ( 8 | "id" SERIAL PRIMARY KEY CHECK ("id" >= 0), 9 | "email" VARCHAR(249) UNIQUE NOT NULL, 10 | "password" VARCHAR(255) NOT NULL, 11 | "username" VARCHAR(100) DEFAULT NULL, 12 | "status" SMALLINT NOT NULL DEFAULT '0' CHECK ("status" >= 0), 13 | "verified" SMALLINT NOT NULL DEFAULT '0' CHECK ("verified" >= 0), 14 | "resettable" SMALLINT NOT NULL DEFAULT '1' CHECK ("resettable" >= 0), 15 | "roles_mask" INTEGER NOT NULL DEFAULT '0' CHECK ("roles_mask" >= 0), 16 | "registered" INTEGER NOT NULL CHECK ("registered" >= 0), 17 | "last_login" INTEGER DEFAULT NULL CHECK ("last_login" >= 0), 18 | "force_logout" INTEGER NOT NULL DEFAULT '0' CHECK ("force_logout" >= 0) 19 | ); 20 | 21 | CREATE TABLE IF NOT EXISTS "users_confirmations" ( 22 | "id" SERIAL PRIMARY KEY CHECK ("id" >= 0), 23 | "user_id" INTEGER NOT NULL CHECK ("user_id" >= 0), 24 | "email" VARCHAR(249) NOT NULL, 25 | "selector" VARCHAR(16) UNIQUE NOT NULL, 26 | "token" VARCHAR(255) NOT NULL, 27 | "expires" INTEGER NOT NULL CHECK ("expires" >= 0) 28 | ); 29 | CREATE INDEX IF NOT EXISTS "email_expires" ON "users_confirmations" ("email", "expires"); 30 | CREATE INDEX IF NOT EXISTS "user_id" ON "users_confirmations" ("user_id"); 31 | 32 | CREATE TABLE IF NOT EXISTS "users_remembered" ( 33 | "id" BIGSERIAL PRIMARY KEY CHECK ("id" >= 0), 34 | "user" INTEGER NOT NULL CHECK ("user" >= 0), 35 | "selector" VARCHAR(24) UNIQUE NOT NULL, 36 | "token" VARCHAR(255) NOT NULL, 37 | "expires" INTEGER NOT NULL CHECK ("expires" >= 0) 38 | ); 39 | CREATE INDEX IF NOT EXISTS "user" ON "users_remembered" ("user"); 40 | 41 | CREATE TABLE IF NOT EXISTS "users_resets" ( 42 | "id" BIGSERIAL PRIMARY KEY CHECK ("id" >= 0), 43 | "user" INTEGER NOT NULL CHECK ("user" >= 0), 44 | "selector" VARCHAR(20) UNIQUE NOT NULL, 45 | "token" VARCHAR(255) NOT NULL, 46 | "expires" INTEGER NOT NULL CHECK ("expires" >= 0) 47 | ); 48 | CREATE INDEX IF NOT EXISTS "user_expires" ON "users_resets" ("user", "expires"); 49 | 50 | CREATE TABLE IF NOT EXISTS "users_throttling" ( 51 | "bucket" VARCHAR(44) PRIMARY KEY, 52 | "tokens" REAL NOT NULL CHECK ("tokens" >= 0), 53 | "replenished_at" INTEGER NOT NULL CHECK ("replenished_at" >= 0), 54 | "expires_at" INTEGER NOT NULL CHECK ("expires_at" >= 0) 55 | ); 56 | CREATE INDEX IF NOT EXISTS "expires_at" ON "users_throttling" ("expires_at"); 57 | 58 | COMMIT; 59 | -------------------------------------------------------------------------------- /Database/SQLite.sql: -------------------------------------------------------------------------------- 1 | -- PHP-Auth (https://github.com/delight-im/PHP-Auth) 2 | -- Copyright (c) delight.im (https://www.delight.im/) 3 | -- Licensed under the MIT License (https://opensource.org/licenses/MIT) 4 | 5 | PRAGMA foreign_keys = OFF; 6 | 7 | CREATE TABLE "users" ( 8 | "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0), 9 | "email" VARCHAR(249) NOT NULL, 10 | "password" VARCHAR(255) NOT NULL, 11 | "username" VARCHAR(100) DEFAULT NULL, 12 | "status" INTEGER NOT NULL CHECK ("status" >= 0) DEFAULT "0", 13 | "verified" INTEGER NOT NULL CHECK ("verified" >= 0) DEFAULT "0", 14 | "resettable" INTEGER NOT NULL CHECK ("resettable" >= 0) DEFAULT "1", 15 | "roles_mask" INTEGER NOT NULL CHECK ("roles_mask" >= 0) DEFAULT "0", 16 | "registered" INTEGER NOT NULL CHECK ("registered" >= 0), 17 | "last_login" INTEGER CHECK ("last_login" >= 0) DEFAULT NULL, 18 | "force_logout" INTEGER NOT NULL CHECK ("force_logout" >= 0) DEFAULT "0", 19 | CONSTRAINT "email" UNIQUE ("email") 20 | ); 21 | 22 | CREATE TABLE "users_confirmations" ( 23 | "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0), 24 | "user_id" INTEGER NOT NULL CHECK ("user_id" >= 0), 25 | "email" VARCHAR(249) NOT NULL, 26 | "selector" VARCHAR(16) NOT NULL, 27 | "token" VARCHAR(255) NOT NULL, 28 | "expires" INTEGER NOT NULL CHECK ("expires" >= 0), 29 | CONSTRAINT "selector" UNIQUE ("selector") 30 | ); 31 | CREATE INDEX "users_confirmations.email_expires" ON "users_confirmations" ("email", "expires"); 32 | CREATE INDEX "users_confirmations.user_id" ON "users_confirmations" ("user_id"); 33 | 34 | CREATE TABLE "users_remembered" ( 35 | "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0), 36 | "user" INTEGER NOT NULL CHECK ("user" >= 0), 37 | "selector" VARCHAR(24) NOT NULL, 38 | "token" VARCHAR(255) NOT NULL, 39 | "expires" INTEGER NOT NULL CHECK ("expires" >= 0), 40 | CONSTRAINT "selector" UNIQUE ("selector") 41 | ); 42 | CREATE INDEX "users_remembered.user" ON "users_remembered" ("user"); 43 | 44 | CREATE TABLE "users_resets" ( 45 | "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0), 46 | "user" INTEGER NOT NULL CHECK ("user" >= 0), 47 | "selector" VARCHAR(20) NOT NULL, 48 | "token" VARCHAR(255) NOT NULL, 49 | "expires" INTEGER NOT NULL CHECK ("expires" >= 0), 50 | CONSTRAINT "selector" UNIQUE ("selector") 51 | ); 52 | CREATE INDEX "users_resets.user_expires" ON "users_resets" ("user", "expires"); 53 | 54 | CREATE TABLE "users_throttling" ( 55 | "bucket" VARCHAR(44) PRIMARY KEY NOT NULL, 56 | "tokens" REAL NOT NULL CHECK ("tokens" >= 0), 57 | "replenished_at" INTEGER NOT NULL CHECK ("replenished_at" >= 0), 58 | "expires_at" INTEGER NOT NULL CHECK ("expires_at" >= 0) 59 | ); 60 | CREATE INDEX "users_throttling.expires_at" ON "users_throttling" ("expires_at"); 61 | -------------------------------------------------------------------------------- /Database/MySQL.sql: -------------------------------------------------------------------------------- 1 | -- PHP-Auth (https://github.com/delight-im/PHP-Auth) 2 | -- Copyright (c) delight.im (https://www.delight.im/) 3 | -- Licensed under the MIT License (https://opensource.org/licenses/MIT) 4 | 5 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 6 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 7 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 8 | /*!40101 SET NAMES utf8mb4 */; 9 | 10 | CREATE TABLE IF NOT EXISTS `users` ( 11 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 12 | `email` varchar(249) COLLATE utf8mb4_unicode_ci NOT NULL, 13 | `password` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 14 | `username` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, 15 | `status` tinyint(2) unsigned NOT NULL DEFAULT '0', 16 | `verified` tinyint(1) unsigned NOT NULL DEFAULT '0', 17 | `resettable` tinyint(1) unsigned NOT NULL DEFAULT '1', 18 | `roles_mask` int(10) unsigned NOT NULL DEFAULT '0', 19 | `registered` int(10) unsigned NOT NULL, 20 | `last_login` int(10) unsigned DEFAULT NULL, 21 | `force_logout` mediumint(7) unsigned NOT NULL DEFAULT '0', 22 | PRIMARY KEY (`id`), 23 | UNIQUE KEY `email` (`email`) 24 | ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 25 | 26 | CREATE TABLE IF NOT EXISTS `users_confirmations` ( 27 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 28 | `user_id` int(10) unsigned NOT NULL, 29 | `email` varchar(249) COLLATE utf8mb4_unicode_ci NOT NULL, 30 | `selector` varchar(16) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 31 | `token` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 32 | `expires` int(10) unsigned NOT NULL, 33 | PRIMARY KEY (`id`), 34 | UNIQUE KEY `selector` (`selector`), 35 | KEY `email_expires` (`email`,`expires`), 36 | KEY `user_id` (`user_id`) 37 | ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 38 | 39 | CREATE TABLE IF NOT EXISTS `users_remembered` ( 40 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, 41 | `user` int(10) unsigned NOT NULL, 42 | `selector` varchar(24) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 43 | `token` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 44 | `expires` int(10) unsigned NOT NULL, 45 | PRIMARY KEY (`id`), 46 | UNIQUE KEY `selector` (`selector`), 47 | KEY `user` (`user`) 48 | ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 49 | 50 | CREATE TABLE IF NOT EXISTS `users_resets` ( 51 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, 52 | `user` int(10) unsigned NOT NULL, 53 | `selector` varchar(20) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 54 | `token` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 55 | `expires` int(10) unsigned NOT NULL, 56 | PRIMARY KEY (`id`), 57 | UNIQUE KEY `selector` (`selector`), 58 | KEY `user_expires` (`user`,`expires`) 59 | ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 60 | 61 | CREATE TABLE IF NOT EXISTS `users_throttling` ( 62 | `bucket` varchar(44) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 63 | `tokens` float unsigned NOT NULL, 64 | `replenished_at` int(10) unsigned NOT NULL, 65 | `expires_at` int(10) unsigned NOT NULL, 66 | PRIMARY KEY (`bucket`), 67 | KEY `expires_at` (`expires_at`) 68 | ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 69 | 70 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 71 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 72 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 73 | -------------------------------------------------------------------------------- /composer.lock: -------------------------------------------------------------------------------- 1 | { 2 | "_readme": [ 3 | "This file locks the dependencies of your project to a known state", 4 | "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", 5 | "This file is @generated automatically" 6 | ], 7 | "content-hash": "b1a2ed45e0064efffcbcf0189f505522", 8 | "packages": [ 9 | { 10 | "name": "delight-im/base64", 11 | "version": "v1.0.0", 12 | "source": { 13 | "type": "git", 14 | "url": "https://github.com/delight-im/PHP-Base64.git", 15 | "reference": "687b2a49f663e162030a8d27b32838bbe7f91c78" 16 | }, 17 | "dist": { 18 | "type": "zip", 19 | "url": "https://api.github.com/repos/delight-im/PHP-Base64/zipball/687b2a49f663e162030a8d27b32838bbe7f91c78", 20 | "reference": "687b2a49f663e162030a8d27b32838bbe7f91c78", 21 | "shasum": "" 22 | }, 23 | "require": { 24 | "php": ">=5.3.0" 25 | }, 26 | "type": "library", 27 | "autoload": { 28 | "psr-4": { 29 | "Delight\\Base64\\": "src/" 30 | } 31 | }, 32 | "notification-url": "https://packagist.org/downloads/", 33 | "license": [ 34 | "MIT" 35 | ], 36 | "description": "Simple and convenient Base64 encoding and decoding for PHP", 37 | "homepage": "https://github.com/delight-im/PHP-Base64", 38 | "keywords": [ 39 | "URL-safe", 40 | "base-64", 41 | "base64", 42 | "decode", 43 | "decoding", 44 | "encode", 45 | "encoding", 46 | "url" 47 | ], 48 | "support": { 49 | "issues": "https://github.com/delight-im/PHP-Base64/issues", 50 | "source": "https://github.com/delight-im/PHP-Base64/tree/master" 51 | }, 52 | "time": "2017-07-24T18:59:51+00:00" 53 | }, 54 | { 55 | "name": "delight-im/db", 56 | "version": "v1.3.1", 57 | "source": { 58 | "type": "git", 59 | "url": "https://github.com/delight-im/PHP-DB.git", 60 | "reference": "7d6f4c7a7e8ba6a297bfc30d65702479fd0b5f7c" 61 | }, 62 | "dist": { 63 | "type": "zip", 64 | "url": "https://api.github.com/repos/delight-im/PHP-DB/zipball/7d6f4c7a7e8ba6a297bfc30d65702479fd0b5f7c", 65 | "reference": "7d6f4c7a7e8ba6a297bfc30d65702479fd0b5f7c", 66 | "shasum": "" 67 | }, 68 | "require": { 69 | "ext-pdo": "*", 70 | "php": ">=5.6.0" 71 | }, 72 | "type": "library", 73 | "autoload": { 74 | "psr-4": { 75 | "Delight\\Db\\": "src/" 76 | } 77 | }, 78 | "notification-url": "https://packagist.org/downloads/", 79 | "license": [ 80 | "MIT" 81 | ], 82 | "description": "Safe and convenient SQL database access in a driver-agnostic way", 83 | "homepage": "https://github.com/delight-im/PHP-DB", 84 | "keywords": [ 85 | "database", 86 | "mysql", 87 | "pdo", 88 | "pgsql", 89 | "postgresql", 90 | "sql", 91 | "sqlite" 92 | ], 93 | "support": { 94 | "issues": "https://github.com/delight-im/PHP-DB/issues", 95 | "source": "https://github.com/delight-im/PHP-DB/tree/v1.3.1" 96 | }, 97 | "time": "2020-02-21T10:46:03+00:00" 98 | } 99 | ], 100 | "packages-dev": [], 101 | "aliases": [], 102 | "minimum-stability": "stable", 103 | "stability-flags": [], 104 | "prefer-stable": false, 105 | "prefer-lowest": false, 106 | "platform": { 107 | "php": ">=7.2.0", 108 | "ext-openssl": "*" 109 | }, 110 | "platform-dev": [], 111 | "plugin-api-version": "2.0.0" 112 | } 113 | -------------------------------------------------------------------------------- /Migration.md: -------------------------------------------------------------------------------- 1 | # Migration 2 | 3 | * [General](#general) 4 | * [From `v7.x.x` to `v8.x.x`](#from-v7xx-to-v8xx) 5 | * [From `v6.x.x` to `v7.x.x`](#from-v6xx-to-v7xx) 6 | * [From `v5.x.x` to `v6.x.x`](#from-v5xx-to-v6xx) 7 | * [From `v4.x.x` to `v5.x.x`](#from-v4xx-to-v5xx) 8 | * [From `v3.x.x` to `v4.x.x`](#from-v3xx-to-v4xx) 9 | * [From `v2.x.x` to `v3.x.x`](#from-v2xx-to-v3xx) 10 | * [From `v1.x.x` to `v2.x.x`](#from-v1xx-to-v2xx) 11 | 12 | ## General 13 | 14 | Update your version of this library using Composer and its `composer update` or `composer require` commands [[?]](https://github.com/delight-im/Knowledge/blob/master/Composer%20(PHP).md#how-do-i-update-libraries-or-modules-within-my-application). 15 | 16 | ## From `v7.x.x` to `v8.x.x` 17 | 18 | * The database schema has changed. 19 | 20 | * The MySQL database schema has changed. Use the statement below to update your database: 21 | 22 | ```sql 23 | ALTER TABLE users 24 | ADD COLUMN `force_logout` mediumint(7) unsigned NOT NULL DEFAULT '0' AFTER `last_login`; 25 | ``` 26 | 27 | * The PostgreSQL database schema has changed. Use the statement below to update your database: 28 | 29 | ```sql 30 | ALTER TABLE users 31 | ADD COLUMN "force_logout" INTEGER NOT NULL DEFAULT '0' CHECK ("force_logout" >= 0); 32 | ``` 33 | 34 | * The SQLite database schema has changed. Use the statement below to update your database: 35 | 36 | ```sql 37 | ALTER TABLE users 38 | ADD COLUMN "force_logout" INTEGER NOT NULL CHECK ("force_logout" >= 0) DEFAULT "0"; 39 | ``` 40 | 41 | * The method `logOutAndDestroySession` has been removed from class `Auth`. Instead, call the two separate methods `logOut` and `destroySession` from class `Auth` one after another for the same effect. 42 | 43 | * If you have been using the return values of the methods `confirmEmail` or `confirmEmailAndSignIn` from class `Auth`, these return values have changed. Instead of only returning the new email address (which has just been verified), both methods now return an array with the old email address (if any) at index zero and the new email address (which has just been verified) at index one. 44 | 45 | ## From `v6.x.x` to `v7.x.x` 46 | 47 | * The method `logOutButKeepSession` from class `Auth` is now simply called `logOut`. Therefore, the former method `logout` is now called `logOutAndDestroySession`. 48 | 49 | * The second argument of the `Auth` constructor, which was named `$useHttps`, has been removed. If you previously had it set to `true`, make sure to set the value of the `session.cookie_secure` directive to `1` now. You may do so either directly in your [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), via the `\ini_set` method or via the `\session_set_cookie_params` method. Otherwise, make sure that directive is set to `0`. 50 | 51 | * The third argument of the `Auth` constructor, which was named `$allowCookiesScriptAccess`, has been removed. If you previously had it set to `true`, make sure to set the value of the `session.cookie_httponly` directive to `0` now. You may do so either directly in your [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), via the `\ini_set` method or via the `\session_set_cookie_params` method. Otherwise, make sure that directive is set to `1`. 52 | 53 | * Only if *both* of the following two conditions are met: 54 | 55 | * The directive `session.cookie_domain` is set to an empty value. It may have been set directly in your [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), via the `\ini_set` method or via the `\session_set_cookie_params` method. You can check the value of that directive by executing the following statement somewhere in your application: 56 | 57 | ```php 58 | \var_dump(\ini_get('session.cookie_domain')); 59 | ``` 60 | 61 | * Your application is accessed via a registered or registrable *domain name*, either by yourself during development and testing or by your visitors and users in production. That means your application is *not*, or *not only*, accessed via `localhost` or via an IP address. 62 | 63 | Then the domain scope for the [two cookies](README.md#cookies) used by this library has changed. You can handle this change in one of two different ways: 64 | 65 | * Restore the old behavior by placing the following statement as early as possible in your application, and before you create the `Auth` instance: 66 | 67 | ```php 68 | \ini_set('session.cookie_domain', \preg_replace('/^www\./', '', $_SERVER['HTTP_HOST'])); 69 | ``` 70 | 71 | You may also evaluate the complete second parameter and put its value directly into your [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`). 72 | 73 | * Use the new domain scope for your application. To do so, you only need to [rename the cookies](README.md#renaming-the-librarys-cookies) used by this library in order to prevent conflicts with old cookies that have been created previously. Renaming the cookies is critically important here. We recommend a versioned name such as `session_v1` for the session cookie. 74 | 75 | * Only if *both* of the following two conditions are met: 76 | 77 | * The directive `session.cookie_domain` is set to a value that starts with the `www` subdomain. It may have been set directly in your [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), via the `\ini_set` method or via the `\session_set_cookie_params` method. You can check the value of that directive by executing the following statement somewhere in your application: 78 | 79 | ```php 80 | \var_dump(\ini_get('session.cookie_domain')); 81 | ``` 82 | 83 | * Your application is accessed via a registered or registrable *domain name*, either by yourself during development and testing or by your visitors and users in production. That means your application is *not*, or *not only*, accessed via `localhost` or via an IP address. 84 | 85 | Then the domain scope for [one of the cookies](README.md#cookies) used by this library has changed. To make your application work correctly with the new scope, [rename the cookies](README.md#renaming-the-librarys-cookies) used by this library in order to prevent conflicts with old cookies that have been created previously. Renaming the cookies is critically important here. We recommend a versioned name such as `session_v1` for the session cookie. 86 | 87 | * If the directive `session.cookie_path` is set to an empty value, then the path scope for [one of the cookies](README.md#cookies) used by this library has changed. To make your application work correctly with the new scope, [rename the cookies](README.md#renaming-the-librarys-cookies) used by this library in order to prevent conflicts with old cookies that have been created previously. Renaming the cookies is critically important here. We recommend a versioned name such as `session_v1` for the session cookie. 88 | 89 | The directive may have been set directly in your [PHP configuration](http://php.net/manual/en/configuration.file.php) (`php.ini`), via the `\ini_set` method or via the `\session_set_cookie_params` method. You can check the value of that directive by executing the following statement somewhere in your application: 90 | 91 | ```php 92 | \var_dump(\ini_get('session.cookie_path')); 93 | ``` 94 | 95 | ## From `v5.x.x` to `v6.x.x` 96 | 97 | * The database schema has changed. 98 | 99 | * The MySQL database schema has changed. Use the statements below to update your database: 100 | 101 | ```sql 102 | ALTER TABLE users 103 | ADD COLUMN roles_mask INT(10) UNSIGNED NOT NULL DEFAULT 0 AFTER verified, 104 | ADD COLUMN resettable TINYINT(1) UNSIGNED NOT NULL DEFAULT 1 AFTER verified; 105 | 106 | ALTER TABLE users_confirmations 107 | ADD COLUMN user_id INT(10) UNSIGNED NULL DEFAULT NULL AFTER id; 108 | 109 | UPDATE users_confirmations SET user_id = ( 110 | SELECT id FROM users WHERE email = users_confirmations.email 111 | ) WHERE user_id IS NULL; 112 | 113 | ALTER TABLE users_confirmations 114 | CHANGE COLUMN user_id user_id INT(10) UNSIGNED NOT NULL; 115 | 116 | ALTER TABLE users_confirmations 117 | ADD INDEX user_id (user_id ASC); 118 | 119 | DROP TABLE users_throttling; 120 | 121 | CREATE TABLE users_throttling ( 122 | bucket varchar(44) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 123 | tokens float unsigned NOT NULL, 124 | replenished_at int(10) unsigned NOT NULL, 125 | expires_at int(10) unsigned NOT NULL, 126 | PRIMARY KEY (bucket), 127 | KEY expires_at (expires_at) 128 | ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 129 | ``` 130 | 131 | * The SQLite database schema has changed. Use the statements below to update your database: 132 | 133 | ```sql 134 | ALTER TABLE users 135 | ADD COLUMN "roles_mask" INTEGER NOT NULL CHECK ("roles_mask" >= 0) DEFAULT "0", 136 | ADD COLUMN "resettable" INTEGER NOT NULL CHECK ("resettable" >= 0) DEFAULT "1"; 137 | 138 | ALTER TABLE users_confirmations 139 | ADD COLUMN "user_id" INTEGER CHECK ("user_id" >= 0); 140 | 141 | UPDATE users_confirmations SET user_id = ( 142 | SELECT id FROM users WHERE email = users_confirmations.email 143 | ) WHERE user_id IS NULL; 144 | 145 | CREATE INDEX "users_confirmations.user_id" ON "users_confirmations" ("user_id"); 146 | 147 | DROP TABLE users_throttling; 148 | 149 | CREATE TABLE "users_throttling" ( 150 | "bucket" VARCHAR(44) PRIMARY KEY NOT NULL, 151 | "tokens" REAL NOT NULL CHECK ("tokens" >= 0), 152 | "replenished_at" INTEGER NOT NULL CHECK ("replenished_at" >= 0), 153 | "expires_at" INTEGER NOT NULL CHECK ("expires_at" >= 0) 154 | ); 155 | 156 | CREATE INDEX "users_throttling.expires_at" ON "users_throttling" ("expires_at"); 157 | ``` 158 | 159 | * The method `setThrottlingOptions` has been removed. 160 | 161 | * The method `changePassword` may now throw an additional `\Delight\Auth\TooManyRequestsException` if too many attempts have been made without the correct old password. 162 | 163 | * The two methods `confirmEmail` and `confirmEmailAndSignIn` may now throw an additional `\Delight\Auth\UserAlreadyExistsException` if an attempt has been made to change the email address to an address that has become occupied in the meantime. 164 | 165 | * The two methods `forgotPassword` and `resetPassword` may now throw an additional `\Delight\Auth\ResetDisabledException` if the user has disabled password resets for their account. 166 | 167 | * The `Base64` class is now an external module and has been moved from the namespace `Delight\Auth` to the namespace `Delight\Base64`. The interface and the return values are not compatible with those from previous versions anymore. 168 | 169 | ## From `v4.x.x` to `v5.x.x` 170 | 171 | * The MySQL database schema has changed. Use the statement below to update your database: 172 | 173 | ```sql 174 | ALTER TABLE `users` ADD COLUMN `status` TINYINT(2) UNSIGNED NOT NULL DEFAULT 0 AFTER `username`; 175 | ``` 176 | 177 | * The two classes `Auth` and `Base64` are now `final`, i.e. they can't be extended anymore, which has never been a good idea, anyway. If you still need to wrap your own methods around these classes, consider [object composition instead of class inheritance](https://en.wikipedia.org/wiki/Composition_over_inheritance). 178 | 179 | ## From `v3.x.x` to `v4.x.x` 180 | 181 | * PHP 5.6.0 or higher is now required. 182 | 183 | ## From `v2.x.x` to `v3.x.x` 184 | 185 | * 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). 186 | 187 | ## From `v1.x.x` to `v2.x.x` 188 | 189 | * The MySQL schema has been changed from charset `utf8` to charset `utf8mb4` and from collation `utf8_general_ci` to collation `utf8mb4_unicode_ci`. Use the statements below to update the database schema: 190 | 191 | ```sql 192 | ALTER TABLE `users` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL; 193 | ALTER TABLE `users_confirmations` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL; 194 | 195 | -- ALTER DATABASE `` CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci; 196 | 197 | ALTER TABLE `users` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 198 | ALTER TABLE `users_confirmations` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 199 | ALTER TABLE `users_remembered` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 200 | ALTER TABLE `users_resets` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 201 | ALTER TABLE `users_throttling` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 202 | 203 | ALTER TABLE `users` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL; 204 | ALTER TABLE `users` CHANGE `username` `username` VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL; 205 | 206 | ALTER TABLE `users_confirmations` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL; 207 | 208 | ALTER TABLE `users_throttling` CHANGE `action_type` `action_type` ENUM('login','register','confirm_email') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL; 209 | 210 | REPAIR TABLE users; 211 | OPTIMIZE TABLE users; 212 | REPAIR TABLE users_confirmations; 213 | OPTIMIZE TABLE users_confirmations; 214 | REPAIR TABLE users_remembered; 215 | OPTIMIZE TABLE users_remembered; 216 | REPAIR TABLE users_resets; 217 | OPTIMIZE TABLE users_resets; 218 | REPAIR TABLE users_throttling; 219 | OPTIMIZE TABLE users_throttling; 220 | ``` 221 | -------------------------------------------------------------------------------- /src/UserManager.php: -------------------------------------------------------------------------------- 1 | db = $databaseConnection; 82 | } 83 | elseif ($databaseConnection instanceof PdoDsn) { 84 | $this->db = PdoDatabase::fromDsn($databaseConnection); 85 | } 86 | elseif ($databaseConnection instanceof \PDO) { 87 | $this->db = PdoDatabase::fromPdo($databaseConnection, true); 88 | } 89 | else { 90 | $this->db = null; 91 | 92 | throw new \InvalidArgumentException('The database connection must be an instance of either `PdoDatabase`, `PdoDsn` or `PDO`'); 93 | } 94 | 95 | $this->dbSchema = $dbSchema !== null ? (string) $dbSchema : null; 96 | $this->dbTablePrefix = (string) $dbTablePrefix; 97 | } 98 | 99 | /** 100 | * Creates a new user 101 | * 102 | * If you want the user's account to be activated by default, pass `null` as the callback 103 | * 104 | * If you want to make the user verify their email address first, pass an anonymous function as the callback 105 | * 106 | * The callback function must have the following signature: 107 | * 108 | * `function ($selector, $token)` 109 | * 110 | * Both pieces of information must be sent to the user, usually embedded in a link 111 | * 112 | * When the user wants to verify their email address as a next step, both pieces will be required again 113 | * 114 | * @param bool $requireUniqueUsername whether it must be ensured that the username is unique 115 | * @param string $email the email address to register 116 | * @param string $password the password for the new account 117 | * @param string|null $username (optional) the username that will be displayed 118 | * @param callable|null $callback (optional) the function that sends the confirmation email to the user 119 | * @return int the ID of the user that has been created (if any) 120 | * @throws InvalidEmailException if the email address has been invalid 121 | * @throws InvalidPasswordException if the password has been invalid 122 | * @throws UserAlreadyExistsException if a user with the specified email address already exists 123 | * @throws DuplicateUsernameException if it was specified that the username must be unique while it was *not* 124 | * @throws AuthError if an internal problem occurred (do *not* catch) 125 | * 126 | * @see confirmEmail 127 | * @see confirmEmailAndSignIn 128 | */ 129 | protected function createUserInternal($requireUniqueUsername, $email, $password, $username = null, callable $callback = null) { 130 | $email = self::validateEmailAddress($email); 131 | $password = self::validatePassword($password); 132 | 133 | $username = isset($username) ? \trim($username) : null; 134 | 135 | // if the supplied username is the empty string or has consisted of whitespace only 136 | if ($username === '') { 137 | // this actually means that there is no username 138 | $username = null; 139 | } 140 | 141 | // if the uniqueness of the username is to be ensured 142 | if ($requireUniqueUsername) { 143 | // if a username has actually been provided 144 | if ($username !== null) { 145 | // count the number of users who do already have that specified username 146 | $occurrencesOfUsername = $this->db->selectValue( 147 | 'SELECT COUNT(*) FROM ' . $this->makeTableName('users') . ' WHERE username = ?', 148 | [ $username ] 149 | ); 150 | 151 | // if any user with that username does already exist 152 | if ($occurrencesOfUsername > 0) { 153 | // cancel the operation and report the violation of this requirement 154 | throw new DuplicateUsernameException(); 155 | } 156 | } 157 | } 158 | 159 | $password = \password_hash($password, \PASSWORD_DEFAULT); 160 | $verified = \is_callable($callback) ? 0 : 1; 161 | 162 | try { 163 | $this->db->insert( 164 | $this->makeTableNameComponents('users'), 165 | [ 166 | 'email' => $email, 167 | 'password' => $password, 168 | 'username' => $username, 169 | 'verified' => $verified, 170 | 'registered' => \time() 171 | ] 172 | ); 173 | } 174 | // if we have a duplicate entry 175 | catch (IntegrityConstraintViolationException $e) { 176 | throw new UserAlreadyExistsException(); 177 | } 178 | catch (Error $e) { 179 | throw new DatabaseError($e->getMessage()); 180 | } 181 | 182 | $newUserId = (int) $this->db->getLastInsertId(); 183 | 184 | if ($verified === 0) { 185 | $this->createConfirmationRequest($newUserId, $email, $callback); 186 | } 187 | 188 | return $newUserId; 189 | } 190 | 191 | /** 192 | * Updates the given user's password by setting it to the new specified password 193 | * 194 | * @param int $userId the ID of the user whose password should be updated 195 | * @param string $newPassword the new password 196 | * @throws UnknownIdException if no user with the specified ID has been found 197 | * @throws AuthError if an internal problem occurred (do *not* catch) 198 | */ 199 | protected function updatePasswordInternal($userId, $newPassword) { 200 | $newPassword = \password_hash($newPassword, \PASSWORD_DEFAULT); 201 | 202 | try { 203 | $affected = $this->db->update( 204 | $this->makeTableNameComponents('users'), 205 | [ 'password' => $newPassword ], 206 | [ 'id' => $userId ] 207 | ); 208 | 209 | if ($affected === 0) { 210 | throw new UnknownIdException(); 211 | } 212 | } 213 | catch (Error $e) { 214 | throw new DatabaseError($e->getMessage()); 215 | } 216 | } 217 | 218 | /** 219 | * Called when a user has successfully logged in 220 | * 221 | * This may happen via the standard login, via the "remember me" feature, or due to impersonation by administrators 222 | * 223 | * @param int $userId the ID of the user 224 | * @param string $email the email address of the user 225 | * @param string $username the display name (if any) of the user 226 | * @param int $status the status of the user as one of the constants from the {@see Status} class 227 | * @param int $roles the roles of the user as a bitmask using constants from the {@see Role} class 228 | * @param int $forceLogout the counter that keeps track of forced logouts that need to be performed in the current session 229 | * @param bool $remembered whether the user has been remembered (instead of them having authenticated actively) 230 | * @throws AuthError if an internal problem occurred (do *not* catch) 231 | */ 232 | protected function onLoginSuccessful($userId, $email, $username, $status, $roles, $forceLogout, $remembered) { 233 | } 234 | 235 | /** 236 | * Returns the requested user data for the account with the specified username (if any) 237 | * 238 | * You must never pass untrusted input to the parameter that takes the column list 239 | * 240 | * @param string $username the username to look for 241 | * @param array $requestedColumns the columns to request from the user's record 242 | * @return array the user data (if an account was found unambiguously) 243 | * @throws UnknownUsernameException if no user with the specified username has been found 244 | * @throws AmbiguousUsernameException if multiple users with the specified username have been found 245 | * @throws AuthError if an internal problem occurred (do *not* catch) 246 | */ 247 | protected function getUserDataByUsername($username, array $requestedColumns) { 248 | try { 249 | $projection = \implode(', ', $requestedColumns); 250 | 251 | $users = $this->db->select( 252 | 'SELECT ' . $projection . ' FROM ' . $this->makeTableName('users') . ' WHERE username = ? LIMIT 2 OFFSET 0', 253 | [ $username ] 254 | ); 255 | } 256 | catch (Error $e) { 257 | throw new DatabaseError($e->getMessage()); 258 | } 259 | 260 | if (empty($users)) { 261 | throw new UnknownUsernameException(); 262 | } 263 | else { 264 | if (\count($users) === 1) { 265 | return $users[0]; 266 | } 267 | else { 268 | throw new AmbiguousUsernameException(); 269 | } 270 | } 271 | } 272 | 273 | /** 274 | * Validates an email address 275 | * 276 | * @param string $email the email address to validate 277 | * @return string the sanitized email address 278 | * @throws InvalidEmailException if the email address has been invalid 279 | */ 280 | protected static function validateEmailAddress($email) { 281 | if (empty($email)) { 282 | throw new InvalidEmailException(); 283 | } 284 | 285 | $email = \trim($email); 286 | 287 | if (!\filter_var($email, \FILTER_VALIDATE_EMAIL)) { 288 | throw new InvalidEmailException(); 289 | } 290 | 291 | return $email; 292 | } 293 | 294 | /** 295 | * Validates a password 296 | * 297 | * @param string $password the password to validate 298 | * @return string the sanitized password 299 | * @throws InvalidPasswordException if the password has been invalid 300 | */ 301 | protected static function validatePassword($password) { 302 | if (empty($password)) { 303 | throw new InvalidPasswordException(); 304 | } 305 | 306 | $password = \trim($password); 307 | 308 | if (\strlen($password) < 1) { 309 | throw new InvalidPasswordException(); 310 | } 311 | 312 | return $password; 313 | } 314 | 315 | /** 316 | * Creates a request for email confirmation 317 | * 318 | * The callback function must have the following signature: 319 | * 320 | * `function ($selector, $token)` 321 | * 322 | * Both pieces of information must be sent to the user, usually embedded in a link 323 | * 324 | * When the user wants to verify their email address as a next step, both pieces will be required again 325 | * 326 | * @param int $userId the user's ID 327 | * @param string $email the email address to verify 328 | * @param callable $callback the function that sends the confirmation email to the user 329 | * @throws AuthError if an internal problem occurred (do *not* catch) 330 | */ 331 | protected function createConfirmationRequest($userId, $email, callable $callback) { 332 | $selector = self::createRandomString(16); 333 | $token = self::createRandomString(16); 334 | $tokenHashed = \password_hash($token, \PASSWORD_DEFAULT); 335 | $expires = \time() + 60 * 60 * 24; 336 | 337 | try { 338 | $this->db->insert( 339 | $this->makeTableNameComponents('users_confirmations'), 340 | [ 341 | 'user_id' => (int) $userId, 342 | 'email' => $email, 343 | 'selector' => $selector, 344 | 'token' => $tokenHashed, 345 | 'expires' => $expires 346 | ] 347 | ); 348 | } 349 | catch (Error $e) { 350 | throw new DatabaseError($e->getMessage()); 351 | } 352 | 353 | if (\is_callable($callback)) { 354 | $callback($selector, $token); 355 | } 356 | else { 357 | throw new MissingCallbackError(); 358 | } 359 | } 360 | 361 | /** 362 | * Clears an existing directive that keeps the user logged in ("remember me") 363 | * 364 | * @param int $userId the ID of the user who shouldn't be kept signed in anymore 365 | * @param string $selector (optional) the selector which the deletion should be restricted to 366 | * @throws AuthError if an internal problem occurred (do *not* catch) 367 | */ 368 | protected function deleteRememberDirectiveForUserById($userId, $selector = null) { 369 | $whereMappings = []; 370 | 371 | if (isset($selector)) { 372 | $whereMappings['selector'] = (string) $selector; 373 | } 374 | 375 | $whereMappings['user'] = (int) $userId; 376 | 377 | try { 378 | $this->db->delete( 379 | $this->makeTableNameComponents('users_remembered'), 380 | $whereMappings 381 | ); 382 | } 383 | catch (Error $e) { 384 | throw new DatabaseError($e->getMessage()); 385 | } 386 | } 387 | 388 | /** 389 | * Triggers a forced logout in all sessions that belong to the specified user 390 | * 391 | * @param int $userId the ID of the user to sign out 392 | * @throws AuthError if an internal problem occurred (do *not* catch) 393 | */ 394 | protected function forceLogoutForUserById($userId) { 395 | $this->deleteRememberDirectiveForUserById($userId); 396 | $this->db->exec( 397 | 'UPDATE ' . $this->makeTableName('users') . ' SET force_logout = force_logout + 1 WHERE id = ?', 398 | [ $userId ] 399 | ); 400 | } 401 | 402 | /** 403 | * Builds a (qualified) full table name from an optional qualifier, an optional prefix, and the table name itself 404 | * 405 | * The optional qualifier may be a database name or a schema name, for example 406 | * 407 | * @param string $name the name of the table 408 | * @return string[] the components of the (qualified) full name of the table 409 | */ 410 | protected function makeTableNameComponents($name) { 411 | $components = []; 412 | 413 | if (!empty($this->dbSchema)) { 414 | $components[] = $this->dbSchema; 415 | } 416 | 417 | if (!empty($name)) { 418 | if (!empty($this->dbTablePrefix)) { 419 | $components[] = $this->dbTablePrefix . $name; 420 | } 421 | else { 422 | $components[] = $name; 423 | } 424 | } 425 | 426 | return $components; 427 | } 428 | 429 | /** 430 | * Builds a (qualified) full table name from an optional qualifier, an optional prefix, and the table name itself 431 | * 432 | * The optional qualifier may be a database name or a schema name, for example 433 | * 434 | * @param string $name the name of the table 435 | * @return string the (qualified) full name of the table 436 | */ 437 | protected function makeTableName($name) { 438 | $components = $this->makeTableNameComponents($name); 439 | 440 | return \implode('.', $components); 441 | } 442 | 443 | } 444 | -------------------------------------------------------------------------------- /src/Administration.php: -------------------------------------------------------------------------------- 1 | createUserInternal(false, $email, $password, $username, null); 41 | } 42 | 43 | /** 44 | * Creates a new user while ensuring that the username is unique 45 | * 46 | * @param string $email the email address to register 47 | * @param string $password the password for the new account 48 | * @param string|null $username (optional) the username that will be displayed 49 | * @return int the ID of the user that has been created (if any) 50 | * @throws InvalidEmailException if the email address was invalid 51 | * @throws InvalidPasswordException if the password was invalid 52 | * @throws UserAlreadyExistsException if a user with the specified email address already exists 53 | * @throws DuplicateUsernameException if the specified username wasn't unique 54 | * @throws AuthError if an internal problem occurred (do *not* catch) 55 | */ 56 | public function createUserWithUniqueUsername($email, $password, $username = null) { 57 | return $this->createUserInternal(true, $email, $password, $username, null); 58 | } 59 | 60 | /** 61 | * Deletes the user with the specified ID 62 | * 63 | * This action cannot be undone 64 | * 65 | * @param int $id the ID of the user to delete 66 | * @throws UnknownIdException if no user with the specified ID has been found 67 | * @throws AuthError if an internal problem occurred (do *not* catch) 68 | */ 69 | public function deleteUserById($id) { 70 | $numberOfDeletedUsers = $this->deleteUsersByColumnValue('id', (int) $id); 71 | 72 | if ($numberOfDeletedUsers === 0) { 73 | throw new UnknownIdException(); 74 | } 75 | } 76 | 77 | /** 78 | * Deletes the user with the specified email address 79 | * 80 | * This action cannot be undone 81 | * 82 | * @param string $email the email address of the user to delete 83 | * @throws InvalidEmailException if no user with the specified email address has been found 84 | * @throws AuthError if an internal problem occurred (do *not* catch) 85 | */ 86 | public function deleteUserByEmail($email) { 87 | $email = self::validateEmailAddress($email); 88 | 89 | $numberOfDeletedUsers = $this->deleteUsersByColumnValue('email', $email); 90 | 91 | if ($numberOfDeletedUsers === 0) { 92 | throw new InvalidEmailException(); 93 | } 94 | } 95 | 96 | /** 97 | * Deletes the user with the specified username 98 | * 99 | * This action cannot be undone 100 | * 101 | * @param string $username the username of the user to delete 102 | * @throws UnknownUsernameException if no user with the specified username has been found 103 | * @throws AmbiguousUsernameException if multiple users with the specified username have been found 104 | * @throws AuthError if an internal problem occurred (do *not* catch) 105 | */ 106 | public function deleteUserByUsername($username) { 107 | $userData = $this->getUserDataByUsername( 108 | \trim($username), 109 | [ 'id' ] 110 | ); 111 | 112 | $this->deleteUsersByColumnValue('id', (int) $userData['id']); 113 | } 114 | 115 | /** 116 | * Assigns the specified role to the user with the given ID 117 | * 118 | * A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) 119 | * 120 | * @param int $userId the ID of the user to assign the role to 121 | * @param int $role the role as one of the constants from the {@see Role} class 122 | * @throws UnknownIdException if no user with the specified ID has been found 123 | * 124 | * @see Role 125 | */ 126 | public function addRoleForUserById($userId, $role) { 127 | $userFound = $this->addRoleForUserByColumnValue( 128 | 'id', 129 | (int) $userId, 130 | $role 131 | ); 132 | 133 | if ($userFound === false) { 134 | throw new UnknownIdException(); 135 | } 136 | } 137 | 138 | /** 139 | * Assigns the specified role to the user with the given email address 140 | * 141 | * A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) 142 | * 143 | * @param string $userEmail the email address of the user to assign the role to 144 | * @param int $role the role as one of the constants from the {@see Role} class 145 | * @throws InvalidEmailException if no user with the specified email address has been found 146 | * 147 | * @see Role 148 | */ 149 | public function addRoleForUserByEmail($userEmail, $role) { 150 | $userEmail = self::validateEmailAddress($userEmail); 151 | 152 | $userFound = $this->addRoleForUserByColumnValue( 153 | 'email', 154 | $userEmail, 155 | $role 156 | ); 157 | 158 | if ($userFound === false) { 159 | throw new InvalidEmailException(); 160 | } 161 | } 162 | 163 | /** 164 | * Assigns the specified role to the user with the given username 165 | * 166 | * A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) 167 | * 168 | * @param string $username the username of the user to assign the role to 169 | * @param int $role the role as one of the constants from the {@see Role} class 170 | * @throws UnknownUsernameException if no user with the specified username has been found 171 | * @throws AmbiguousUsernameException if multiple users with the specified username have been found 172 | * 173 | * @see Role 174 | */ 175 | public function addRoleForUserByUsername($username, $role) { 176 | $userData = $this->getUserDataByUsername( 177 | \trim($username), 178 | [ 'id' ] 179 | ); 180 | 181 | $this->addRoleForUserByColumnValue( 182 | 'id', 183 | (int) $userData['id'], 184 | $role 185 | ); 186 | } 187 | 188 | /** 189 | * Takes away the specified role from the user with the given ID 190 | * 191 | * A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) 192 | * 193 | * @param int $userId the ID of the user to take the role away from 194 | * @param int $role the role as one of the constants from the {@see Role} class 195 | * @throws UnknownIdException if no user with the specified ID has been found 196 | * 197 | * @see Role 198 | */ 199 | public function removeRoleForUserById($userId, $role) { 200 | $userFound = $this->removeRoleForUserByColumnValue( 201 | 'id', 202 | (int) $userId, 203 | $role 204 | ); 205 | 206 | if ($userFound === false) { 207 | throw new UnknownIdException(); 208 | } 209 | } 210 | 211 | /** 212 | * Takes away the specified role from the user with the given email address 213 | * 214 | * A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) 215 | * 216 | * @param string $userEmail the email address of the user to take the role away from 217 | * @param int $role the role as one of the constants from the {@see Role} class 218 | * @throws InvalidEmailException if no user with the specified email address has been found 219 | * 220 | * @see Role 221 | */ 222 | public function removeRoleForUserByEmail($userEmail, $role) { 223 | $userEmail = self::validateEmailAddress($userEmail); 224 | 225 | $userFound = $this->removeRoleForUserByColumnValue( 226 | 'email', 227 | $userEmail, 228 | $role 229 | ); 230 | 231 | if ($userFound === false) { 232 | throw new InvalidEmailException(); 233 | } 234 | } 235 | 236 | /** 237 | * Takes away the specified role from the user with the given username 238 | * 239 | * A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) 240 | * 241 | * @param string $username the username of the user to take the role away from 242 | * @param int $role the role as one of the constants from the {@see Role} class 243 | * @throws UnknownUsernameException if no user with the specified username has been found 244 | * @throws AmbiguousUsernameException if multiple users with the specified username have been found 245 | * 246 | * @see Role 247 | */ 248 | public function removeRoleForUserByUsername($username, $role) { 249 | $userData = $this->getUserDataByUsername( 250 | \trim($username), 251 | [ 'id' ] 252 | ); 253 | 254 | $this->removeRoleForUserByColumnValue( 255 | 'id', 256 | (int) $userData['id'], 257 | $role 258 | ); 259 | } 260 | 261 | /** 262 | * Returns whether the user with the given ID has the specified role 263 | * 264 | * @param int $userId the ID of the user to check the roles for 265 | * @param int $role the role as one of the constants from the {@see Role} class 266 | * @return bool 267 | * @throws UnknownIdException if no user with the specified ID has been found 268 | * 269 | * @see Role 270 | */ 271 | public function doesUserHaveRole($userId, $role) { 272 | if (empty($role) || !\is_numeric($role)) { 273 | return false; 274 | } 275 | 276 | $userId = (int) $userId; 277 | 278 | $rolesBitmask = $this->db->selectValue( 279 | 'SELECT roles_mask FROM ' . $this->makeTableName('users') . ' WHERE id = ?', 280 | [ $userId ] 281 | ); 282 | 283 | if ($rolesBitmask === null) { 284 | throw new UnknownIdException(); 285 | } 286 | 287 | $role = (int) $role; 288 | 289 | return ($rolesBitmask & $role) === $role; 290 | } 291 | 292 | /** 293 | * Returns the roles of the user with the given ID, mapping the numerical values to their descriptive names 294 | * 295 | * @param int $userId the ID of the user to return the roles for 296 | * @return array 297 | * @throws UnknownIdException if no user with the specified ID has been found 298 | * 299 | * @see Role 300 | */ 301 | public function getRolesForUserById($userId) { 302 | $userId = (int) $userId; 303 | 304 | $rolesBitmask = $this->db->selectValue( 305 | 'SELECT roles_mask FROM ' . $this->makeTableName('users') . ' WHERE id = ?', 306 | [ $userId ] 307 | ); 308 | 309 | if ($rolesBitmask === null) { 310 | throw new UnknownIdException(); 311 | } 312 | 313 | return \array_filter( 314 | Role::getMap(), 315 | function ($each) use ($rolesBitmask) { 316 | return ($rolesBitmask & $each) === $each; 317 | }, 318 | \ARRAY_FILTER_USE_KEY 319 | ); 320 | } 321 | 322 | /** 323 | * Signs in as the user with the specified ID 324 | * 325 | * @param int $id the ID of the user to sign in as 326 | * @throws UnknownIdException if no user with the specified ID has been found 327 | * @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet 328 | * @throws AuthError if an internal problem occurred (do *not* catch) 329 | */ 330 | public function logInAsUserById($id) { 331 | $numberOfMatchedUsers = $this->logInAsUserByColumnValue('id', (int) $id); 332 | 333 | if ($numberOfMatchedUsers === 0) { 334 | throw new UnknownIdException(); 335 | } 336 | } 337 | 338 | /** 339 | * Signs in as the user with the specified email address 340 | * 341 | * @param string $email the email address of the user to sign in as 342 | * @throws InvalidEmailException if no user with the specified email address has been found 343 | * @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet 344 | * @throws AuthError if an internal problem occurred (do *not* catch) 345 | */ 346 | public function logInAsUserByEmail($email) { 347 | $email = self::validateEmailAddress($email); 348 | 349 | $numberOfMatchedUsers = $this->logInAsUserByColumnValue('email', $email); 350 | 351 | if ($numberOfMatchedUsers === 0) { 352 | throw new InvalidEmailException(); 353 | } 354 | } 355 | 356 | /** 357 | * Signs in as the user with the specified display name 358 | * 359 | * @param string $username the display name of the user to sign in as 360 | * @throws UnknownUsernameException if no user with the specified username has been found 361 | * @throws AmbiguousUsernameException if multiple users with the specified username have been found 362 | * @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet 363 | * @throws AuthError if an internal problem occurred (do *not* catch) 364 | */ 365 | public function logInAsUserByUsername($username) { 366 | $numberOfMatchedUsers = $this->logInAsUserByColumnValue('username', \trim($username)); 367 | 368 | if ($numberOfMatchedUsers === 0) { 369 | throw new UnknownUsernameException(); 370 | } 371 | elseif ($numberOfMatchedUsers > 1) { 372 | throw new AmbiguousUsernameException(); 373 | } 374 | } 375 | 376 | /** 377 | * Changes the password for the user with the given ID 378 | * 379 | * @param int $userId the ID of the user whose password to change 380 | * @param string $newPassword the new password to set 381 | * @throws UnknownIdException if no user with the specified ID has been found 382 | * @throws InvalidPasswordException if the desired new password has been invalid 383 | * @throws AuthError if an internal problem occurred (do *not* catch) 384 | */ 385 | public function changePasswordForUserById($userId, $newPassword) { 386 | $userId = (int) $userId; 387 | $newPassword = self::validatePassword($newPassword); 388 | 389 | $this->updatePasswordInternal( 390 | $userId, 391 | $newPassword 392 | ); 393 | 394 | $this->forceLogoutForUserById($userId); 395 | } 396 | 397 | /** 398 | * Changes the password for the user with the given username 399 | * 400 | * @param string $username the username of the user whose password to change 401 | * @param string $newPassword the new password to set 402 | * @throws UnknownUsernameException if no user with the specified username has been found 403 | * @throws AmbiguousUsernameException if multiple users with the specified username have been found 404 | * @throws InvalidPasswordException if the desired new password has been invalid 405 | * @throws AuthError if an internal problem occurred (do *not* catch) 406 | */ 407 | public function changePasswordForUserByUsername($username, $newPassword) { 408 | $userData = $this->getUserDataByUsername( 409 | \trim($username), 410 | [ 'id' ] 411 | ); 412 | 413 | $this->changePasswordForUserById( 414 | (int) $userData['id'], 415 | $newPassword 416 | ); 417 | } 418 | 419 | /** 420 | * Deletes all existing users where the column with the specified name has the given value 421 | * 422 | * You must never pass untrusted input to the parameter that takes the column name 423 | * 424 | * @param string $columnName the name of the column to filter by 425 | * @param mixed $columnValue the value to look for in the selected column 426 | * @return int the number of deleted users 427 | * @throws AuthError if an internal problem occurred (do *not* catch) 428 | */ 429 | private function deleteUsersByColumnValue($columnName, $columnValue) { 430 | try { 431 | return $this->db->delete( 432 | $this->makeTableNameComponents('users'), 433 | [ 434 | $columnName => $columnValue 435 | ] 436 | ); 437 | } 438 | catch (Error $e) { 439 | throw new DatabaseError($e->getMessage()); 440 | } 441 | } 442 | 443 | /** 444 | * Modifies the roles for the user where the column with the specified name has the given value 445 | * 446 | * You must never pass untrusted input to the parameter that takes the column name 447 | * 448 | * @param string $columnName the name of the column to filter by 449 | * @param mixed $columnValue the value to look for in the selected column 450 | * @param callable $modification the modification to apply to the existing bitmask of roles 451 | * @return bool whether any user with the given column constraints has been found 452 | * @throws AuthError if an internal problem occurred (do *not* catch) 453 | * 454 | * @see Role 455 | */ 456 | private function modifyRolesForUserByColumnValue($columnName, $columnValue, callable $modification) { 457 | try { 458 | $userData = $this->db->selectRow( 459 | 'SELECT id, roles_mask FROM ' . $this->makeTableName('users') . ' WHERE ' . $columnName . ' = ?', 460 | [ $columnValue ] 461 | ); 462 | } 463 | catch (Error $e) { 464 | throw new DatabaseError($e->getMessage()); 465 | } 466 | 467 | if ($userData === null) { 468 | return false; 469 | } 470 | 471 | $newRolesBitmask = $modification($userData['roles_mask']); 472 | 473 | try { 474 | $this->db->exec( 475 | 'UPDATE ' . $this->makeTableName('users') . ' SET roles_mask = ? WHERE id = ?', 476 | [ 477 | $newRolesBitmask, 478 | (int) $userData['id'] 479 | ] 480 | ); 481 | 482 | return true; 483 | } 484 | catch (Error $e) { 485 | throw new DatabaseError($e->getMessage()); 486 | } 487 | } 488 | 489 | /** 490 | * Assigns the specified role to the user where the column with the specified name has the given value 491 | * 492 | * You must never pass untrusted input to the parameter that takes the column name 493 | * 494 | * @param string $columnName the name of the column to filter by 495 | * @param mixed $columnValue the value to look for in the selected column 496 | * @param int $role the role as one of the constants from the {@see Role} class 497 | * @return bool whether any user with the given column constraints has been found 498 | * 499 | * @see Role 500 | */ 501 | private function addRoleForUserByColumnValue($columnName, $columnValue, $role) { 502 | $role = (int) $role; 503 | 504 | return $this->modifyRolesForUserByColumnValue( 505 | $columnName, 506 | $columnValue, 507 | function ($oldRolesBitmask) use ($role) { 508 | return $oldRolesBitmask | $role; 509 | } 510 | ); 511 | } 512 | 513 | /** 514 | * Takes away the specified role from the user where the column with the specified name has the given value 515 | * 516 | * You must never pass untrusted input to the parameter that takes the column name 517 | * 518 | * @param string $columnName the name of the column to filter by 519 | * @param mixed $columnValue the value to look for in the selected column 520 | * @param int $role the role as one of the constants from the {@see Role} class 521 | * @return bool whether any user with the given column constraints has been found 522 | * 523 | * @see Role 524 | */ 525 | private function removeRoleForUserByColumnValue($columnName, $columnValue, $role) { 526 | $role = (int) $role; 527 | 528 | return $this->modifyRolesForUserByColumnValue( 529 | $columnName, 530 | $columnValue, 531 | function ($oldRolesBitmask) use ($role) { 532 | return $oldRolesBitmask & ~$role; 533 | } 534 | ); 535 | } 536 | 537 | /** 538 | * Signs in as the user for which the column with the specified name has the given value 539 | * 540 | * You must never pass untrusted input to the parameter that takes the column name 541 | * 542 | * @param string $columnName the name of the column to filter by 543 | * @param mixed $columnValue the value to look for in the selected column 544 | * @return int the number of matched users (where only a value of one means that the login may have been successful) 545 | * @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet 546 | * @throws AuthError if an internal problem occurred (do *not* catch) 547 | */ 548 | private function logInAsUserByColumnValue($columnName, $columnValue) { 549 | try { 550 | $users = $this->db->select( 551 | 'SELECT verified, id, email, username, status, roles_mask FROM ' . $this->makeTableName('users') . ' WHERE ' . $columnName . ' = ? LIMIT 2 OFFSET 0', 552 | [ $columnValue ] 553 | ); 554 | } 555 | catch (Error $e) { 556 | throw new DatabaseError($e->getMessage()); 557 | } 558 | 559 | $numberOfMatchingUsers = ($users !== null) ? \count($users) : 0; 560 | 561 | if ($numberOfMatchingUsers === 1) { 562 | $user = $users[0]; 563 | 564 | if ((int) $user['verified'] === 1) { 565 | $this->onLoginSuccessful($user['id'], $user['email'], $user['username'], $user['status'], $user['roles_mask'], \PHP_INT_MAX, false); 566 | } 567 | else { 568 | throw new EmailNotVerifiedException(); 569 | } 570 | } 571 | 572 | return $numberOfMatchingUsers; 573 | } 574 | 575 | } 576 | -------------------------------------------------------------------------------- /tests/index.php: -------------------------------------------------------------------------------- 1 | check()) { 44 | \showAuthenticatedUserForm($auth); 45 | } 46 | else { 47 | \showGuestUserForm(); 48 | } 49 | 50 | function processRequestData(\Comet\Auth $auth) { 51 | if (isset($_POST)) { 52 | if (isset($_POST['action'])) { 53 | if ($_POST['action'] === 'login') { 54 | if ($_POST['remember'] == 1) { 55 | // keep logged in for one year 56 | $rememberDuration = (int) (60 * 60 * 24 * 365.25); 57 | } 58 | else { 59 | // do not keep logged in after session ends 60 | $rememberDuration = null; 61 | } 62 | 63 | try { 64 | if (isset($_POST['email'])) { 65 | $auth->login($_POST['email'], $_POST['password'], $rememberDuration); 66 | } 67 | elseif (isset($_POST['username'])) { 68 | $auth->loginWithUsername($_POST['username'], $_POST['password'], $rememberDuration); 69 | } 70 | else { 71 | return 'either email address or username required'; 72 | } 73 | 74 | return 'ok'; 75 | } 76 | catch (\Auth\InvalidEmailException $e) { 77 | return 'wrong email address'; 78 | } 79 | catch (\Auth\UnknownUsernameException $e) { 80 | return 'unknown username'; 81 | } 82 | catch (\Auth\AmbiguousUsernameException $e) { 83 | return 'ambiguous username'; 84 | } 85 | catch (\Auth\InvalidPasswordException $e) { 86 | return 'wrong password'; 87 | } 88 | catch (\Auth\EmailNotVerifiedException $e) { 89 | return 'email address not verified'; 90 | } 91 | catch (\Auth\TooManyRequestsException $e) { 92 | return 'too many requests'; 93 | } 94 | } 95 | else if ($_POST['action'] === 'register') { 96 | try { 97 | if ($_POST['require_verification'] == 1) { 98 | $callback = function ($selector, $token) { 99 | echo '
';
 100 | 							echo 'Email confirmation';
 101 | 							echo "\n";
 102 | 							echo '  >  Selector';
 103 | 							echo "\t\t\t\t";
 104 | 							echo \htmlspecialchars($selector);
 105 | 							echo "\n";
 106 | 							echo '  >  Token';
 107 | 							echo "\t\t\t\t";
 108 | 							echo \htmlspecialchars($token);
 109 | 							echo '
'; 110 | }; 111 | } 112 | else { 113 | $callback = null; 114 | } 115 | 116 | if (!isset($_POST['require_unique_username'])) { 117 | $_POST['require_unique_username'] = '0'; 118 | } 119 | 120 | if ($_POST['require_unique_username'] == 0) { 121 | return $auth->register($_POST['email'], $_POST['password'], $_POST['username'], $callback); 122 | } 123 | else { 124 | return $auth->registerWithUniqueUsername($_POST['email'], $_POST['password'], $_POST['username'], $callback); 125 | } 126 | } 127 | catch (\Auth\InvalidEmailException $e) { 128 | return 'invalid email address'; 129 | } 130 | catch (\Auth\InvalidPasswordException $e) { 131 | return 'invalid password'; 132 | } 133 | catch (\Auth\UserAlreadyExistsException $e) { 134 | return 'email address already exists'; 135 | } 136 | catch (\Auth\DuplicateUsernameException $e) { 137 | return 'username already exists'; 138 | } 139 | catch (\Auth\TooManyRequestsException $e) { 140 | return 'too many requests'; 141 | } 142 | } 143 | else if ($_POST['action'] === 'confirmEmail') { 144 | try { 145 | if (isset($_POST['login']) && $_POST['login'] > 0) { 146 | if ($_POST['login'] == 2) { 147 | // keep logged in for one year 148 | $rememberDuration = (int) (60 * 60 * 24 * 365.25); 149 | } 150 | else { 151 | // do not keep logged in after session ends 152 | $rememberDuration = null; 153 | } 154 | 155 | return $auth->confirmEmailAndSignIn($_POST['selector'], $_POST['token'], $rememberDuration); 156 | } 157 | else { 158 | return $auth->confirmEmail($_POST['selector'], $_POST['token']); 159 | } 160 | } 161 | catch (\Auth\InvalidSelectorTokenPairException $e) { 162 | return 'invalid token'; 163 | } 164 | catch (\Auth\TokenExpiredException $e) { 165 | return 'token expired'; 166 | } 167 | catch (\Auth\UserAlreadyExistsException $e) { 168 | return 'email address already exists'; 169 | } 170 | catch (\Auth\TooManyRequestsException $e) { 171 | return 'too many requests'; 172 | } 173 | } 174 | else if ($_POST['action'] === 'resendConfirmationForEmail') { 175 | try { 176 | $auth->resendConfirmationForEmail($_POST['email'], function ($selector, $token) { 177 | echo '
';
 178 | 						echo 'Email confirmation';
 179 | 						echo "\n";
 180 | 						echo '  >  Selector';
 181 | 						echo "\t\t\t\t";
 182 | 						echo \htmlspecialchars($selector);
 183 | 						echo "\n";
 184 | 						echo '  >  Token';
 185 | 						echo "\t\t\t\t";
 186 | 						echo \htmlspecialchars($token);
 187 | 						echo '
'; 188 | }); 189 | 190 | return 'ok'; 191 | } 192 | catch (\Auth\ConfirmationRequestNotFound $e) { 193 | return 'no request found'; 194 | } 195 | catch (\Auth\TooManyRequestsException $e) { 196 | return 'too many requests'; 197 | } 198 | } 199 | else if ($_POST['action'] === 'resendConfirmationForUserId') { 200 | try { 201 | $auth->resendConfirmationForUserId($_POST['userId'], function ($selector, $token) { 202 | echo '
';
 203 | 						echo 'Email confirmation';
 204 | 						echo "\n";
 205 | 						echo '  >  Selector';
 206 | 						echo "\t\t\t\t";
 207 | 						echo \htmlspecialchars($selector);
 208 | 						echo "\n";
 209 | 						echo '  >  Token';
 210 | 						echo "\t\t\t\t";
 211 | 						echo \htmlspecialchars($token);
 212 | 						echo '
'; 213 | }); 214 | 215 | return 'ok'; 216 | } 217 | catch (\Auth\ConfirmationRequestNotFound $e) { 218 | return 'no request found'; 219 | } 220 | catch (\Auth\TooManyRequestsException $e) { 221 | return 'too many requests'; 222 | } 223 | } 224 | else if ($_POST['action'] === 'forgotPassword') { 225 | try { 226 | $auth->forgotPassword($_POST['email'], function ($selector, $token) { 227 | echo '
';
 228 | 						echo 'Password reset';
 229 | 						echo "\n";
 230 | 						echo '  >  Selector';
 231 | 						echo "\t\t\t\t";
 232 | 						echo \htmlspecialchars($selector);
 233 | 						echo "\n";
 234 | 						echo '  >  Token';
 235 | 						echo "\t\t\t\t";
 236 | 						echo \htmlspecialchars($token);
 237 | 						echo '
'; 238 | }); 239 | 240 | return 'ok'; 241 | } 242 | catch (\Auth\InvalidEmailException $e) { 243 | return 'invalid email address'; 244 | } 245 | catch (\Auth\EmailNotVerifiedException $e) { 246 | return 'email address not verified'; 247 | } 248 | catch (\Auth\ResetDisabledException $e) { 249 | return 'password reset is disabled'; 250 | } 251 | catch (\Auth\TooManyRequestsException $e) { 252 | return 'too many requests'; 253 | } 254 | } 255 | else if ($_POST['action'] === 'resetPassword') { 256 | try { 257 | if (isset($_POST['login']) && $_POST['login'] > 0) { 258 | if ($_POST['login'] == 2) { 259 | // keep logged in for one year 260 | $rememberDuration = (int) (60 * 60 * 24 * 365.25); 261 | } 262 | else { 263 | // do not keep logged in after session ends 264 | $rememberDuration = null; 265 | } 266 | 267 | return $auth->resetPasswordAndSignIn($_POST['selector'], $_POST['token'], $_POST['password'], $rememberDuration); 268 | } 269 | else { 270 | return $auth->resetPassword($_POST['selector'], $_POST['token'], $_POST['password']); 271 | } 272 | } 273 | catch (\Auth\InvalidSelectorTokenPairException $e) { 274 | return 'invalid token'; 275 | } 276 | catch (\Auth\TokenExpiredException $e) { 277 | return 'token expired'; 278 | } 279 | catch (\Auth\ResetDisabledException $e) { 280 | return 'password reset is disabled'; 281 | } 282 | catch (\Auth\InvalidPasswordException $e) { 283 | return 'invalid password'; 284 | } 285 | catch (\Auth\TooManyRequestsException $e) { 286 | return 'too many requests'; 287 | } 288 | } 289 | else if ($_POST['action'] === 'canResetPassword') { 290 | try { 291 | $auth->canResetPasswordOrThrow($_POST['selector'], $_POST['token']); 292 | 293 | return 'yes'; 294 | } 295 | catch (\Auth\InvalidSelectorTokenPairException $e) { 296 | return 'invalid token'; 297 | } 298 | catch (\Auth\TokenExpiredException $e) { 299 | return 'token expired'; 300 | } 301 | catch (\Auth\ResetDisabledException $e) { 302 | return 'password reset is disabled'; 303 | } 304 | catch (\Auth\TooManyRequestsException $e) { 305 | return 'too many requests'; 306 | } 307 | } 308 | else if ($_POST['action'] === 'reconfirmPassword') { 309 | try { 310 | return $auth->reconfirmPassword($_POST['password']) ? 'correct' : 'wrong'; 311 | } 312 | catch (\Auth\NotLoggedInException $e) { 313 | return 'not logged in'; 314 | } 315 | catch (\Auth\TooManyRequestsException $e) { 316 | return 'too many requests'; 317 | } 318 | } 319 | else if ($_POST['action'] === 'changePassword') { 320 | try { 321 | $auth->changePassword($_POST['oldPassword'], $_POST['newPassword']); 322 | 323 | return 'ok'; 324 | } 325 | catch (\Auth\NotLoggedInException $e) { 326 | return 'not logged in'; 327 | } 328 | catch (\Auth\InvalidPasswordException $e) { 329 | return 'invalid password(s)'; 330 | } 331 | catch (\Auth\TooManyRequestsException $e) { 332 | return 'too many requests'; 333 | } 334 | } 335 | else if ($_POST['action'] === 'changePasswordWithoutOldPassword') { 336 | try { 337 | $auth->changePasswordWithoutOldPassword($_POST['newPassword']); 338 | 339 | return 'ok'; 340 | } 341 | catch (\Auth\NotLoggedInException $e) { 342 | return 'not logged in'; 343 | } 344 | catch (\Auth\InvalidPasswordException $e) { 345 | return 'invalid password'; 346 | } 347 | } 348 | else if ($_POST['action'] === 'changeEmail') { 349 | try { 350 | $auth->changeEmail($_POST['newEmail'], function ($selector, $token) { 351 | echo '
';
 352 | 						echo 'Email confirmation';
 353 | 						echo "\n";
 354 | 						echo '  >  Selector';
 355 | 						echo "\t\t\t\t";
 356 | 						echo \htmlspecialchars($selector);
 357 | 						echo "\n";
 358 | 						echo '  >  Token';
 359 | 						echo "\t\t\t\t";
 360 | 						echo \htmlspecialchars($token);
 361 | 						echo '
'; 362 | }); 363 | 364 | return 'ok'; 365 | } 366 | catch (\Auth\InvalidEmailException $e) { 367 | return 'invalid email address'; 368 | } 369 | catch (\Auth\UserAlreadyExistsException $e) { 370 | return 'email address already exists'; 371 | } 372 | catch (\Auth\EmailNotVerifiedException $e) { 373 | return 'account not verified'; 374 | } 375 | catch (\Auth\NotLoggedInException $e) { 376 | return 'not logged in'; 377 | } 378 | catch (\Auth\TooManyRequestsException $e) { 379 | return 'too many requests'; 380 | } 381 | } 382 | else if ($_POST['action'] === 'setPasswordResetEnabled') { 383 | try { 384 | $auth->setPasswordResetEnabled($_POST['enabled'] == 1); 385 | 386 | return 'ok'; 387 | } 388 | catch (\Auth\NotLoggedInException $e) { 389 | return 'not logged in'; 390 | } 391 | } 392 | else if ($_POST['action'] === 'logOut') { 393 | $auth->logOut(); 394 | 395 | return 'ok'; 396 | } 397 | else if ($_POST['action'] === 'logOutEverywhereElse') { 398 | try { 399 | $auth->logOutEverywhereElse(); 400 | } 401 | catch (\Auth\NotLoggedInException $e) { 402 | return 'not logged in'; 403 | } 404 | 405 | return 'ok'; 406 | } 407 | else if ($_POST['action'] === 'logOutEverywhere') { 408 | try { 409 | $auth->logOutEverywhere(); 410 | } 411 | catch (\Auth\NotLoggedInException $e) { 412 | return 'not logged in'; 413 | } 414 | 415 | return 'ok'; 416 | } 417 | else if ($_POST['action'] === 'destroySession') { 418 | $auth->destroySession(); 419 | 420 | return 'ok'; 421 | } 422 | else if ($_POST['action'] === 'admin.createUser') { 423 | try { 424 | if (!isset($_POST['require_unique_username'])) { 425 | $_POST['require_unique_username'] = '0'; 426 | } 427 | 428 | if ($_POST['require_unique_username'] == 0) { 429 | return $auth->admin()->createUser($_POST['email'], $_POST['password'], $_POST['username']); 430 | } 431 | else { 432 | return $auth->admin()->createUserWithUniqueUsername($_POST['email'], $_POST['password'], $_POST['username']); 433 | } 434 | } 435 | catch (\Auth\InvalidEmailException $e) { 436 | return 'invalid email address'; 437 | } 438 | catch (\Auth\InvalidPasswordException $e) { 439 | return 'invalid password'; 440 | } 441 | catch (\Auth\UserAlreadyExistsException $e) { 442 | return 'email address already exists'; 443 | } 444 | catch (\Auth\DuplicateUsernameException $e) { 445 | return 'username already exists'; 446 | } 447 | } 448 | else if ($_POST['action'] === 'admin.deleteUser') { 449 | if (isset($_POST['id'])) { 450 | try { 451 | $auth->admin()->deleteUserById($_POST['id']); 452 | } 453 | catch (\Auth\UnknownIdException $e) { 454 | return 'unknown ID'; 455 | } 456 | } 457 | elseif (isset($_POST['email'])) { 458 | try { 459 | $auth->admin()->deleteUserByEmail($_POST['email']); 460 | } 461 | catch (\Auth\InvalidEmailException $e) { 462 | return 'unknown email address'; 463 | } 464 | } 465 | elseif (isset($_POST['username'])) { 466 | try { 467 | $auth->admin()->deleteUserByUsername($_POST['username']); 468 | } 469 | catch (\Auth\UnknownUsernameException $e) { 470 | return 'unknown username'; 471 | } 472 | catch (\Auth\AmbiguousUsernameException $e) { 473 | return 'ambiguous username'; 474 | } 475 | } 476 | else { 477 | return 'either ID, email address or username required'; 478 | } 479 | 480 | return 'ok'; 481 | } 482 | else if ($_POST['action'] === 'admin.addRole') { 483 | if (isset($_POST['role'])) { 484 | if (isset($_POST['id'])) { 485 | try { 486 | $auth->admin()->addRoleForUserById($_POST['id'], $_POST['role']); 487 | } 488 | catch (\Auth\UnknownIdException $e) { 489 | return 'unknown ID'; 490 | } 491 | } 492 | elseif (isset($_POST['email'])) { 493 | try { 494 | $auth->admin()->addRoleForUserByEmail($_POST['email'], $_POST['role']); 495 | } 496 | catch (\Auth\InvalidEmailException $e) { 497 | return 'unknown email address'; 498 | } 499 | } 500 | elseif (isset($_POST['username'])) { 501 | try { 502 | $auth->admin()->addRoleForUserByUsername($_POST['username'], $_POST['role']); 503 | } 504 | catch (\Auth\UnknownUsernameException $e) { 505 | return 'unknown username'; 506 | } 507 | catch (\Auth\AmbiguousUsernameException $e) { 508 | return 'ambiguous username'; 509 | } 510 | } 511 | else { 512 | return 'either ID, email address or username required'; 513 | } 514 | } 515 | else { 516 | return 'role required'; 517 | } 518 | 519 | return 'ok'; 520 | } 521 | else if ($_POST['action'] === 'admin.removeRole') { 522 | if (isset($_POST['role'])) { 523 | if (isset($_POST['id'])) { 524 | try { 525 | $auth->admin()->removeRoleForUserById($_POST['id'], $_POST['role']); 526 | } 527 | catch (\Auth\UnknownIdException $e) { 528 | return 'unknown ID'; 529 | } 530 | } 531 | elseif (isset($_POST['email'])) { 532 | try { 533 | $auth->admin()->removeRoleForUserByEmail($_POST['email'], $_POST['role']); 534 | } 535 | catch (\Auth\InvalidEmailException $e) { 536 | return 'unknown email address'; 537 | } 538 | } 539 | elseif (isset($_POST['username'])) { 540 | try { 541 | $auth->admin()->removeRoleForUserByUsername($_POST['username'], $_POST['role']); 542 | } 543 | catch (\Auth\UnknownUsernameException $e) { 544 | return 'unknown username'; 545 | } 546 | catch (\Auth\AmbiguousUsernameException $e) { 547 | return 'ambiguous username'; 548 | } 549 | } 550 | else { 551 | return 'either ID, email address or username required'; 552 | } 553 | } 554 | else { 555 | return 'role required'; 556 | } 557 | 558 | return 'ok'; 559 | } 560 | else if ($_POST['action'] === 'admin.hasRole') { 561 | if (isset($_POST['id'])) { 562 | if (isset($_POST['role'])) { 563 | try { 564 | return $auth->admin()->doesUserHaveRole($_POST['id'], $_POST['role']) ? 'yes' : 'no'; 565 | } 566 | catch (\Auth\UnknownIdException $e) { 567 | return 'unknown ID'; 568 | } 569 | } 570 | else { 571 | return 'role required'; 572 | } 573 | } 574 | else { 575 | return 'ID required'; 576 | } 577 | } 578 | else if ($_POST['action'] === 'admin.getRoles') { 579 | if (isset($_POST['id'])) { 580 | try { 581 | return $auth->admin()->getRolesForUserById($_POST['id']); 582 | } 583 | catch (\Auth\UnknownIdException $e) { 584 | return 'unknown ID'; 585 | } 586 | } 587 | else { 588 | return 'ID required'; 589 | } 590 | } 591 | else if ($_POST['action'] === 'admin.logInAsUserById') { 592 | if (isset($_POST['id'])) { 593 | try { 594 | $auth->admin()->logInAsUserById($_POST['id']); 595 | 596 | return 'ok'; 597 | } 598 | catch (\Auth\UnknownIdException $e) { 599 | return 'unknown ID'; 600 | } 601 | catch (\Auth\EmailNotVerifiedException $e) { 602 | return 'email address not verified'; 603 | } 604 | } 605 | else { 606 | return 'ID required'; 607 | } 608 | } 609 | else if ($_POST['action'] === 'admin.logInAsUserByEmail') { 610 | if (isset($_POST['email'])) { 611 | try { 612 | $auth->admin()->logInAsUserByEmail($_POST['email']); 613 | 614 | return 'ok'; 615 | } 616 | catch (\Auth\InvalidEmailException $e) { 617 | return 'unknown email address'; 618 | } 619 | catch (\Auth\EmailNotVerifiedException $e) { 620 | return 'email address not verified'; 621 | } 622 | } 623 | else { 624 | return 'Email address required'; 625 | } 626 | } 627 | else if ($_POST['action'] === 'admin.logInAsUserByUsername') { 628 | if (isset($_POST['username'])) { 629 | try { 630 | $auth->admin()->logInAsUserByUsername($_POST['username']); 631 | 632 | return 'ok'; 633 | } 634 | catch (\Auth\UnknownUsernameException $e) { 635 | return 'unknown username'; 636 | } 637 | catch (\Auth\AmbiguousUsernameException $e) { 638 | return 'ambiguous username'; 639 | } 640 | catch (\Auth\EmailNotVerifiedException $e) { 641 | return 'email address not verified'; 642 | } 643 | } 644 | else { 645 | return 'Username required'; 646 | } 647 | } 648 | else if ($_POST['action'] === 'admin.changePasswordForUser') { 649 | if (isset($_POST['newPassword'])) { 650 | if (isset($_POST['id'])) { 651 | try { 652 | $auth->admin()->changePasswordForUserById($_POST['id'], $_POST['newPassword']); 653 | } 654 | catch (\Auth\UnknownIdException $e) { 655 | return 'unknown ID'; 656 | } 657 | catch (\Auth\InvalidPasswordException $e) { 658 | return 'invalid password'; 659 | } 660 | } 661 | elseif (isset($_POST['username'])) { 662 | try { 663 | $auth->admin()->changePasswordForUserByUsername($_POST['username'], $_POST['newPassword']); 664 | } 665 | catch (\Auth\UnknownUsernameException $e) { 666 | return 'unknown username'; 667 | } 668 | catch (\Auth\AmbiguousUsernameException $e) { 669 | return 'ambiguous username'; 670 | } 671 | catch (\Auth\InvalidPasswordException $e) { 672 | return 'invalid password'; 673 | } 674 | } 675 | else { 676 | return 'either ID or username required'; 677 | } 678 | } 679 | else { 680 | return 'new password required'; 681 | } 682 | 683 | return 'ok'; 684 | } 685 | else { 686 | throw new Exception('Unexpected action: ' . $_POST['action']); 687 | } 688 | } 689 | } 690 | 691 | return null; 692 | } 693 | 694 | function showDebugData(\Comet\Auth $auth, $result) { 695 | echo '
';
 696 | 
 697 | 	echo 'Last operation' . "\t\t\t\t";
 698 | 	\var_dump($result);
 699 | 	echo 'Session ID' . "\t\t\t\t";
 700 | 	\var_dump(\session_id());
 701 | 	echo "\n";
 702 | 
 703 | 	echo '$auth->isLoggedIn()' . "\t\t\t";
 704 | 	\var_dump($auth->isLoggedIn());
 705 | 	echo '$auth->check()' . "\t\t\t\t";
 706 | 	\var_dump($auth->check());
 707 | 	echo "\n";
 708 | 
 709 | 	echo '$auth->getUserId()' . "\t\t\t";
 710 | 	\var_dump($auth->getUserId());
 711 | 	echo '$auth->id()' . "\t\t\t\t";
 712 | 	\var_dump($auth->id());
 713 | 	echo "\n";
 714 | 
 715 | 	echo '$auth->getEmail()' . "\t\t\t";
 716 | 	\var_dump($auth->getEmail());
 717 | 	echo '$auth->getUsername()' . "\t\t\t";
 718 | 	\var_dump($auth->getUsername());
 719 | 
 720 | 	echo '$auth->getStatus()' . "\t\t\t";
 721 | 	echo \convertStatusToText($auth);
 722 | 	echo ' / ';
 723 | 	\var_dump($auth->getStatus());
 724 | 
 725 | 	echo "\n";
 726 | 
 727 | 	echo 'Roles (super moderator)' . "\t\t\t";
 728 | 	\var_dump($auth->hasRole(\Auth\Role::SUPER_MODERATOR));
 729 | 
 730 | 	echo 'Roles (developer *or* manager)' . "\t\t";
 731 | 	\var_dump($auth->hasAnyRole(\Auth\Role::DEVELOPER, \Auth\Role::MANAGER));
 732 | 
 733 | 	echo 'Roles (developer *and* manager)' . "\t\t";
 734 | 	\var_dump($auth->hasAllRoles(\Auth\Role::DEVELOPER, \Auth\Role::MANAGER));
 735 | 
 736 | 	echo 'Roles' . "\t\t\t\t\t";
 737 | 	echo \json_encode($auth->getRoles()) . "\n";
 738 | 
 739 | 	echo "\n";
 740 | 
 741 | 	echo '$auth->isRemembered()' . "\t\t\t";
 742 | 	\var_dump($auth->isRemembered());
 743 | 	echo '$auth->getIpAddress()' . "\t\t\t";
 744 | 	\var_dump($auth->getIpAddress());
 745 | 	echo "\n";
 746 | 
 747 | 	echo 'Session name' . "\t\t\t\t";
 748 | 	\var_dump(\session_name());
 749 | 	echo 'Auth::createRememberCookieName()' . "\t";
 750 | 	\var_dump(\Comet\Auth::createRememberCookieName());
 751 | 	echo "\n";
 752 | 
 753 | 	echo 'Auth::createCookieName(\'session\')' . "\t";
 754 | 	\var_dump(\Comet\Auth::createCookieName('session'));
 755 | 	echo 'Auth::createRandomString()' . "\t\t";
 756 | 	\var_dump(\Comet\Auth::createRandomString());
 757 | 	echo 'Auth::createUuid()' . "\t\t\t";
 758 | 	\var_dump(\Comet\Auth::createUuid());
 759 | 
 760 | 	echo '
'; 761 | } 762 | 763 | function convertStatusToText(\Comet\Auth $auth) { 764 | if ($auth->isLoggedIn() === true) { 765 | if ($auth->getStatus() === \Auth\Status::NORMAL && $auth->isNormal()) { 766 | return 'normal'; 767 | } 768 | elseif ($auth->getStatus() === \Auth\Status::ARCHIVED && $auth->isArchived()) { 769 | return 'archived'; 770 | } 771 | elseif ($auth->getStatus() === \Auth\Status::BANNED && $auth->isBanned()) { 772 | return 'banned'; 773 | } 774 | elseif ($auth->getStatus() === \Auth\Status::LOCKED && $auth->isLocked()) { 775 | return 'locked'; 776 | } 777 | elseif ($auth->getStatus() === \Auth\Status::PENDING_REVIEW && $auth->isPendingReview()) { 778 | return 'pending review'; 779 | } 780 | elseif ($auth->getStatus() === \Auth\Status::SUSPENDED && $auth->isSuspended()) { 781 | return 'suspended'; 782 | } 783 | } 784 | elseif ($auth->isLoggedIn() === false) { 785 | if ($auth->getStatus() === null) { 786 | return 'none'; 787 | } 788 | } 789 | 790 | throw new Exception('Invalid status `' . $auth->getStatus() . '`'); 791 | } 792 | 793 | function showGeneralForm() { 794 | echo '
'; 795 | echo ''; 796 | echo '
'; 797 | } 798 | 799 | function showAuthenticatedUserForm(\Comet\Auth $auth) { 800 | echo '
'; 801 | echo ''; 802 | echo ' '; 803 | echo ''; 804 | echo '
'; 805 | 806 | echo '
'; 807 | echo ''; 808 | echo ' '; 809 | echo ' '; 810 | echo ''; 811 | echo '
'; 812 | 813 | echo '
'; 814 | echo ''; 815 | echo ' '; 816 | echo ''; 817 | echo '
'; 818 | 819 | echo '
'; 820 | echo ''; 821 | echo ' '; 822 | echo ''; 823 | echo '
'; 824 | 825 | \showConfirmEmailForm(); 826 | 827 | echo '
'; 828 | echo ''; 829 | echo ' '; 833 | echo ''; 834 | echo '
'; 835 | 836 | echo '
'; 837 | echo ''; 838 | echo ''; 839 | echo '
'; 840 | 841 | echo '
'; 842 | echo ''; 843 | echo ''; 844 | echo '
'; 845 | 846 | echo '
'; 847 | echo ''; 848 | echo ''; 849 | echo '
'; 850 | 851 | \showDestroySessionForm(); 852 | } 853 | 854 | function showGuestUserForm() { 855 | echo '

Public

'; 856 | 857 | echo '
'; 858 | echo ''; 859 | echo ' '; 860 | echo ' '; 861 | echo ' '; 865 | echo ''; 866 | echo '
'; 867 | 868 | echo '
'; 869 | echo ''; 870 | echo ' '; 871 | echo ' '; 872 | echo ' '; 876 | echo ''; 877 | echo '
'; 878 | 879 | echo '
'; 880 | echo ''; 881 | echo ' '; 882 | echo ' '; 883 | echo ' '; 884 | echo ' '; 888 | echo ' '; 892 | echo ''; 893 | echo '
'; 894 | 895 | \showConfirmEmailForm(); 896 | 897 | echo '
'; 898 | echo ''; 899 | echo ' '; 900 | echo ''; 901 | echo '
'; 902 | 903 | echo '
'; 904 | echo ''; 905 | echo ' '; 906 | echo ' '; 907 | echo ' '; 908 | echo ' '; 913 | echo ''; 914 | echo '
'; 915 | 916 | echo '
'; 917 | echo ''; 918 | echo ' '; 919 | echo ' '; 920 | echo ''; 921 | echo '
'; 922 | 923 | \showDestroySessionForm(); 924 | 925 | echo '

Administration

'; 926 | 927 | echo '
'; 928 | echo ''; 929 | echo ' '; 930 | echo ' '; 931 | echo ' '; 932 | echo ' '; 936 | echo ''; 937 | echo '
'; 938 | 939 | echo '
'; 940 | echo ''; 941 | echo ' '; 942 | echo ''; 943 | echo '
'; 944 | 945 | echo '
'; 946 | echo ''; 947 | echo ' '; 948 | echo ''; 949 | echo '
'; 950 | 951 | echo '
'; 952 | echo ''; 953 | echo ' '; 954 | echo ''; 955 | echo '
'; 956 | 957 | echo '
'; 958 | echo ''; 959 | echo ' '; 960 | echo ''; 961 | echo ''; 962 | echo '
'; 963 | 964 | echo '
'; 965 | echo ''; 966 | echo ' '; 967 | echo ''; 968 | echo ''; 969 | echo '
'; 970 | 971 | echo '
'; 972 | echo ''; 973 | echo ' '; 974 | echo ''; 975 | echo ''; 976 | echo '
'; 977 | 978 | echo '
'; 979 | echo ''; 980 | echo ' '; 981 | echo ''; 982 | echo ''; 983 | echo '
'; 984 | 985 | echo '
'; 986 | echo ''; 987 | echo ' '; 988 | echo ''; 989 | echo ''; 990 | echo '
'; 991 | 992 | echo '
'; 993 | echo ''; 994 | echo ' '; 995 | echo ''; 996 | echo ''; 997 | echo '
'; 998 | 999 | echo '
'; 1000 | echo ''; 1001 | echo ' '; 1002 | echo ''; 1003 | echo ''; 1004 | echo '
'; 1005 | 1006 | echo '
'; 1007 | echo ''; 1008 | echo ' '; 1009 | echo ''; 1010 | echo '
'; 1011 | 1012 | echo '
'; 1013 | echo ''; 1014 | echo ' '; 1015 | echo ''; 1016 | echo '
'; 1017 | 1018 | echo '
'; 1019 | echo ''; 1020 | echo ' '; 1021 | echo ''; 1022 | echo '
'; 1023 | 1024 | echo '
'; 1025 | echo ''; 1026 | echo ' '; 1027 | echo ''; 1028 | echo '
'; 1029 | 1030 | echo '
'; 1031 | echo ''; 1032 | echo ' '; 1033 | echo ' '; 1034 | echo ''; 1035 | echo '
'; 1036 | 1037 | echo '
'; 1038 | echo ''; 1039 | echo ' '; 1040 | echo ' '; 1041 | echo ''; 1042 | echo '
'; 1043 | } 1044 | 1045 | function showConfirmEmailForm() { 1046 | echo '
'; 1047 | echo ''; 1048 | echo ' '; 1049 | echo ' '; 1050 | echo ' '; 1055 | echo ''; 1056 | echo '
'; 1057 | 1058 | echo '
'; 1059 | echo ''; 1060 | echo ' '; 1061 | echo ''; 1062 | echo '
'; 1063 | 1064 | echo '
'; 1065 | echo ''; 1066 | echo ' '; 1067 | echo ''; 1068 | echo '
'; 1069 | } 1070 | 1071 | function showDestroySessionForm() { 1072 | echo '
'; 1073 | echo ''; 1074 | echo ''; 1075 | echo '
'; 1076 | } 1077 | 1078 | function createRolesOptions() { 1079 | $out = ''; 1080 | 1081 | foreach (\Auth\Role::getMap() as $roleValue => $roleName) { 1082 | $out .= ''; 1083 | } 1084 | 1085 | return $out; 1086 | } 1087 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Comet Auth 2 | 3 | **PSR compatible authentication for PHP.** Based on [PHP-Auth](https://github.com/delight-im/PHP-Auth) 4 | 5 | Written once, to be used everywhere. Completely framework-agnostic and database-agnostic. 6 | 7 | It's better to use it with [Comet](https://github.com/gotzmann/comet) PHP framework 8 | 9 | ## Why do I need this? 10 | 11 | * 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. 12 | * Re-implementing a new authentication system for every PHP project is *not* a good idea. 13 | * Building your own authentication classes piece by piece, and copying it to every project, is *not* recommended, either. 14 | * A secure authentication system with an easy-to-use API should be thoroughly designed and planned. 15 | * Peer-review for your critical infrastructure is *a must*. 16 | 17 | ## Requirements 18 | 19 | * PHP 7.2.0+ 20 | * PDO (PHP Data Objects) extension (`pdo`) 21 | * MySQL Native Driver (`mysqlnd`) **or** PostgreSQL driver (`pgsql`) **or** SQLite driver (`sqlite`) 22 | * OpenSSL extension (`openssl`) 23 | * MySQL 5.5.3+ **or** MariaDB 5.5.23+ **or** PostgreSQL 9.5.10+ **or** SQLite 3.14.1+ **or** [other SQL databases](Database) 24 | 25 | ## Installation 26 | 27 | 1. Include the library via Composer 28 | 29 | ``` 30 | $ composer require gotzmann/auth 31 | ``` 32 | 33 | 1. Include the Composer autoloader: 34 | 35 | ```php 36 | require __DIR__ . '/vendor/autoload.php'; 37 | ``` 38 | 39 | 1. Set up a database and create the required tables: 40 | 41 | * [MariaDB](Database/MySQL.sql) 42 | * [MySQL](Database/MySQL.sql) 43 | * [PostgreSQL](Database/PostgreSQL.sql) 44 | * [SQLite](Database/SQLite.sql) 45 | 46 | ## Usage 47 | 48 | * [Creating a new instance](#creating-a-new-instance) 49 | * [Registration (sign up)](#registration-sign-up) 50 | * [Login (sign in)](#login-sign-in) 51 | * [Email verification](#email-verification) 52 | * [Keeping the user logged in](#keeping-the-user-logged-in) 53 | * [Password reset (“forgot password”)](#password-reset-forgot-password) 54 | * [Initiating the request](#step-1-of-3-initiating-the-request) 55 | * [Verifying an attempt](#step-2-of-3-verifying-an-attempt) 56 | * [Updating the password](#step-3-of-3-updating-the-password) 57 | * [Changing the current user’s password](#changing-the-current-users-password) 58 | * [Changing the current user’s email address](#changing-the-current-users-email-address) 59 | * [Re-sending confirmation requests](#re-sending-confirmation-requests) 60 | * [Logout](#logout) 61 | * [Accessing user information](#accessing-user-information) 62 | * [Login state](#login-state) 63 | * [User ID](#user-id) 64 | * [Email address](#email-address) 65 | * [Display name](#display-name) 66 | * [Status information](#status-information) 67 | * [Checking whether the user was “remembered”](#checking-whether-the-user-was-remembered) 68 | * [IP address](#ip-address) 69 | * [Additional user information](#additional-user-information) 70 | * [Reconfirming the user’s password](#reconfirming-the-users-password) 71 | * [Roles (or groups)](#roles-or-groups) 72 | * [Checking roles](#checking-roles) 73 | * [Available roles](#available-roles) 74 | * [Permissions (or access rights, privileges or capabilities)](#permissions-or-access-rights-privileges-or-capabilities) 75 | * [Custom role names](#custom-role-names) 76 | * [Enabling or disabling password resets](#enabling-or-disabling-password-resets) 77 | * [Throttling or rate limiting](#throttling-or-rate-limiting) 78 | * [Administration (managing users)](#administration-managing-users) 79 | * [Creating new users](#creating-new-users) 80 | * [Deleting users](#deleting-users) 81 | * [Assigning roles to users](#assigning-roles-to-users) 82 | * [Taking roles away from users](#taking-roles-away-from-users) 83 | * [Checking roles](#checking-roles-1) 84 | * [Impersonating users (logging in as user)](#impersonating-users-logging-in-as-user) 85 | * [Changing a user’s password](#changing-a-users-password) 86 | * [Cookies](#cookies) 87 | * [Renaming the library’s cookies](#renaming-the-librarys-cookies) 88 | * [Defining the domain scope for cookies](#defining-the-domain-scope-for-cookies) 89 | * [Restricting the path where cookies are available](#restricting-the-path-where-cookies-are-available) 90 | * [Controlling client-side script access to cookies](#controlling-client-side-script-access-to-cookies) 91 | * [Configuring transport security for cookies](#configuring-transport-security-for-cookies) 92 | * [Utilities](#utilities) 93 | * [Creating a random string](#creating-a-random-string) 94 | * [Creating a UUID v4 as per RFC 4122](#creating-a-uuid-v4-as-per-rfc-4122) 95 | * [Reading and writing session data](#reading-and-writing-session-data) 96 | 97 | ### Creating a new instance 98 | 99 | ```php 100 | // $db = new \PDO('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password'); 101 | // or 102 | // $db = new \PDO('pgsql:dbname=my-database;host=localhost;port=5432', 'my-username', 'my-password'); 103 | // or 104 | // $db = new \PDO('sqlite:../Databases/my-database.sqlite'); 105 | 106 | $auth = new \Comet\Auth($db, $session, $params); 107 | ``` 108 | 109 | If you have an open `PDO` connection already, just re-use it. The database user (e.g. `my-username`) needs at least the privileges `SELECT`, `INSERT`, `UPDATE` and `DELETE` for the tables used by this library (or their parent database). 110 | 111 | You must pass the user’s real IP address to the constructor in the third argument, $params['REMOTE_ADDR'] to use throttling and rate limiting features. 112 | 113 | Should your database tables for this library need a common prefix, e.g. `my_users` instead of `users` (and likewise for the other tables), pass the prefix (e.g. `my_`) as DB_TABLE_PREFIX key in $params. This is optional and the prefix is empty by default. 114 | 115 | During development, you may want to disable the request limiting or throttling performed by this library. To do so, pass `false` to the constructor as the THROTTLING key of $params. The feature is enabled by default. 116 | 117 | During the lifetime of a session, some user data may be changed remotely, either by a client in another session or by an administrator. That means this information must be regularly resynchronized with its authoritative source in the database, which this library does automatically. By default, this happens every five minutes. If you want to change this interval, pass a custom interval in seconds to the constructor as the $params entry which is named SESSION_RESYNK_INTERVAL. 118 | 119 | 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, which is named DB_SCHEMA. 120 | 121 | ### Registration (sign up) 122 | 123 | ```php 124 | try { 125 | $userId = $auth->register($_POST['email'], $_POST['password'], $_POST['username'], function ($selector, $token) { 126 | echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)'; 127 | }); 128 | 129 | echo 'We have signed up a new user with the ID ' . $userId; 130 | } 131 | catch (\Comet\InvalidEmailException $e) { 132 | die('Invalid email address'); 133 | } 134 | catch (\Comet\InvalidPasswordException $e) { 135 | die('Invalid password'); 136 | } 137 | catch (\Comet\UserAlreadyExistsException $e) { 138 | die('User already exists'); 139 | } 140 | catch (\Comet\TooManyRequestsException $e) { 141 | die('Too many requests'); 142 | } 143 | ``` 144 | 145 | **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. 146 | 147 | The username in the third parameter is optional. You can pass `null` there if you don’t want to manage usernames. 148 | 149 | If you want to enforce unique usernames, on the other hand, simply call `registerWithUniqueUsername` instead of `register`, and be prepared to catch the `DuplicateUsernameException`. 150 | 151 | **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: 152 | 153 | ```php 154 | if (\preg_match('/[\x00-\x1f\x7f\/:\\\\]/', $username) === 0) { 155 | // ... 156 | } 157 | ``` 158 | 159 | For email verification, you should build an URL with the selector and token and send it to the user, e.g.: 160 | 161 | ```php 162 | $url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector) . '&token=' . \urlencode($token); 163 | ``` 164 | 165 | 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. 166 | 167 | Need to store additional user information? Read on [here](#additional-user-information). 168 | 169 | **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. 170 | 171 | ### Login (sign in) 172 | 173 | ```php 174 | try { 175 | $auth->login($_POST['email'], $_POST['password']); 176 | 177 | echo 'User is logged in'; 178 | } 179 | catch (\Comet\InvalidEmailException $e) { 180 | die('Wrong email address'); 181 | } 182 | catch (\Comet\InvalidPasswordException $e) { 183 | die('Wrong password'); 184 | } 185 | catch (\Comet\EmailNotVerifiedException $e) { 186 | die('Email not verified'); 187 | } 188 | catch (\Comet\TooManyRequestsException $e) { 189 | die('Too many requests'); 190 | } 191 | ``` 192 | 193 | If you want to sign in with usernames on the other hand, either in addition to the login via email address or as a replacement, that’s possible as well. Simply call the method `loginWithUsername` instead of method `login`. Then, instead of catching `InvalidEmailException`, make sure to catch both `UnknownUsernameException` and `AmbiguousUsernameException`. You may also want to read the notes about the uniqueness of usernames in the section that explains how to [sign up new users](#registration-sign-up). 194 | 195 | ### Email verification 196 | 197 | Extract the selector and token from the URL that the user clicked on in the verification email. 198 | 199 | ```php 200 | try { 201 | $auth->confirmEmail($_GET['selector'], $_GET['token']); 202 | 203 | echo 'Email address has been verified'; 204 | } 205 | catch (\Comet\InvalidSelectorTokenPairException $e) { 206 | die('Invalid token'); 207 | } 208 | catch (\Comet\TokenExpiredException $e) { 209 | die('Token expired'); 210 | } 211 | catch (\Comet\UserAlreadyExistsException $e) { 212 | die('Email address already exists'); 213 | } 214 | catch (\Comet\TooManyRequestsException $e) { 215 | die('Too many requests'); 216 | } 217 | ``` 218 | 219 | 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. 220 | 221 | 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. 222 | 223 | ### Password reset (“forgot password”) 224 | 225 | #### Step 1 of 3: Initiating the request 226 | 227 | ```php 228 | try { 229 | $auth->forgotPassword($_POST['email'], function ($selector, $token) { 230 | echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)'; 231 | }); 232 | 233 | echo 'Request has been generated'; 234 | } 235 | catch (\Comet\InvalidEmailException $e) { 236 | die('Invalid email address'); 237 | } 238 | catch (\Comet\EmailNotVerifiedException $e) { 239 | die('Email not verified'); 240 | } 241 | catch (\Comet\ResetDisabledException $e) { 242 | die('Password reset is disabled'); 243 | } 244 | catch (\Comet\TooManyRequestsException $e) { 245 | die('Too many requests'); 246 | } 247 | ``` 248 | 249 | **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. 250 | 251 | You should build an URL with the selector and token and send it to the user, e.g.: 252 | 253 | ```php 254 | $url = 'https://www.example.com/reset_password?selector=' . \urlencode($selector) . '&token=' . \urlencode($token); 255 | ``` 256 | 257 | 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. 258 | 259 | #### Step 2 of 3: Verifying an attempt 260 | 261 | As the next step, users will click on the link that they received. Extract the selector and token from the URL. 262 | 263 | If the selector/token pair is valid, let the user choose a new password: 264 | 265 | ```php 266 | try { 267 | $auth->canResetPasswordOrThrow($_GET['selector'], $_GET['token']); 268 | 269 | echo 'Put the selector into a "hidden" field (or keep it in the URL)'; 270 | echo 'Put the token into a "hidden" field (or keep it in the URL)'; 271 | 272 | echo 'Ask the user for their new password'; 273 | } 274 | catch (\Comet\InvalidSelectorTokenPairException $e) { 275 | die('Invalid token'); 276 | } 277 | catch (\Comet\TokenExpiredException $e) { 278 | die('Token expired'); 279 | } 280 | catch (\Comet\ResetDisabledException $e) { 281 | die('Password reset is disabled'); 282 | } 283 | catch (\Comet\TooManyRequestsException $e) { 284 | die('Too many requests'); 285 | } 286 | ``` 287 | 288 | Alternatively, if you don’t need any error messages but only want to check the validity, you can use the slightly simpler version: 289 | 290 | ```php 291 | if ($auth->canResetPassword($_GET['selector'], $_GET['token'])) { 292 | echo 'Put the selector into a "hidden" field (or keep it in the URL)'; 293 | echo 'Put the token into a "hidden" field (or keep it in the URL)'; 294 | 295 | echo 'Ask the user for their new password'; 296 | } 297 | ``` 298 | 299 | #### Step 3 of 3: Updating the password 300 | 301 | Now when you have the new password for the user (and still have the other two pieces of information), you can reset the password: 302 | 303 | ```php 304 | try { 305 | $auth->resetPassword($_POST['selector'], $_POST['token'], $_POST['password']); 306 | 307 | echo 'Password has been reset'; 308 | } 309 | catch (\Comet\InvalidSelectorTokenPairException $e) { 310 | die('Invalid token'); 311 | } 312 | catch (\Comet\TokenExpiredException $e) { 313 | die('Token expired'); 314 | } 315 | catch (\Comet\ResetDisabledException $e) { 316 | die('Password reset is disabled'); 317 | } 318 | catch (\Comet\InvalidPasswordException $e) { 319 | die('Invalid password'); 320 | } 321 | catch (\Comet\TooManyRequestsException $e) { 322 | die('Too many requests'); 323 | } 324 | ``` 325 | 326 | 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. 327 | 328 | 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`. 329 | 330 | ### Changing the current user’s password 331 | 332 | If a user is currently logged in, they may change their password. 333 | 334 | ```php 335 | try { 336 | $auth->changePassword($_POST['oldPassword'], $_POST['newPassword']); 337 | 338 | echo 'Password has been changed'; 339 | } 340 | catch (\Comet\NotLoggedInException $e) { 341 | die('Not logged in'); 342 | } 343 | catch (\Comet\InvalidPasswordException $e) { 344 | die('Invalid password(s)'); 345 | } 346 | catch (\Comet\TooManyRequestsException $e) { 347 | die('Too many requests'); 348 | } 349 | ``` 350 | 351 | Asking the user for their current (and soon *old*) password and requiring it for verification is the recommended way to handle password changes. This is shown above. 352 | 353 | If you’re sure that you don’t need that confirmation, however, you may call `changePasswordWithoutOldPassword` instead of `changePassword` and drop the first parameter from that method call (which would otherwise contain the old password). 354 | 355 | In any case, after the user’s password has been changed, you should send an email to their account’s primary email address as an out-of-band notification informing the account owner about this critical change. 356 | 357 | ### Changing the current user’s email address 358 | 359 | If a user is currently logged in, they may change their email address. 360 | 361 | ```php 362 | try { 363 | if ($auth->reconfirmPassword($_POST['password'])) { 364 | $auth->changeEmail($_POST['newEmail'], function ($selector, $token) { 365 | echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email to the *new* address)'; 366 | }); 367 | 368 | echo 'The change will take effect as soon as the new email address has been confirmed'; 369 | } 370 | else { 371 | echo 'We can\'t say if the user is who they claim to be'; 372 | } 373 | } 374 | catch (\Comet\InvalidEmailException $e) { 375 | die('Invalid email address'); 376 | } 377 | catch (\Comet\UserAlreadyExistsException $e) { 378 | die('Email address already exists'); 379 | } 380 | catch (\Comet\EmailNotVerifiedException $e) { 381 | die('Account not verified'); 382 | } 383 | catch (\Comet\NotLoggedInException $e) { 384 | die('Not logged in'); 385 | } 386 | catch (\Comet\TooManyRequestsException $e) { 387 | die('Too many requests'); 388 | } 389 | ``` 390 | 391 | **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. 392 | 393 | For email verification, you should build an URL with the selector and token and send it to the user, e.g.: 394 | 395 | ```php 396 | $url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector) . '&token=' . \urlencode($token); 397 | ``` 398 | 399 | **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. 400 | 401 | 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. 402 | 403 | **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`. 404 | 405 | ### Re-sending confirmation requests 406 | 407 | If an earlier confirmation request could not be delivered to the user, or if the user missed that request, or if they just don’t want to wait any longer, you may re-send an earlier request like this: 408 | 409 | ```php 410 | try { 411 | $auth->resendConfirmationForEmail($_POST['email'], function ($selector, $token) { 412 | echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)'; 413 | }); 414 | 415 | echo 'The user may now respond to the confirmation request (usually by clicking a link)'; 416 | } 417 | catch (\Comet\ConfirmationRequestNotFound $e) { 418 | die('No earlier request found that could be re-sent'); 419 | } 420 | catch (\Comet\TooManyRequestsException $e) { 421 | die('There have been too many requests -- try again later'); 422 | } 423 | ``` 424 | 425 | If you want to specify the user by their ID instead of by their email address, this is possible as well: 426 | 427 | ```php 428 | try { 429 | $auth->resendConfirmationForUserId($_POST['userId'], function ($selector, $token) { 430 | echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)'; 431 | }); 432 | 433 | echo 'The user may now respond to the confirmation request (usually by clicking a link)'; 434 | } 435 | catch (\Comet\ConfirmationRequestNotFound $e) { 436 | die('No earlier request found that could be re-sent'); 437 | } 438 | catch (\Comet\TooManyRequestsException $e) { 439 | die('There have been too many requests -- try again later'); 440 | } 441 | ``` 442 | 443 | **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. 444 | 445 | Usually, you should build an URL with the selector and token and send it to the user, e.g. as follows: 446 | 447 | ```php 448 | $url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector) . '&token=' . \urlencode($token); 449 | ``` 450 | 451 | **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. 452 | 453 | ### Logout 454 | 455 | ```php 456 | $auth->logOut(); 457 | 458 | // or 459 | 460 | try { 461 | $auth->logOutEverywhereElse(); 462 | } 463 | catch (\Comet\NotLoggedInException $e) { 464 | die('Not logged in'); 465 | } 466 | 467 | // or 468 | 469 | try { 470 | $auth->logOutEverywhere(); 471 | } 472 | catch (\Comet\NotLoggedInException $e) { 473 | die('Not logged in'); 474 | } 475 | ``` 476 | 477 | Additionally, if you store custom information in the session as well, and if you want that information to be deleted, you can destroy the entire session by calling a second method: 478 | 479 | ```php 480 | $auth->destroySession(); 481 | ``` 482 | 483 | **Note:** Global logouts 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`. 484 | 485 | ### Accessing user information 486 | 487 | #### Login state 488 | 489 | ```php 490 | if ($auth->isLoggedIn()) { 491 | echo 'User is signed in'; 492 | } 493 | else { 494 | echo 'User is not signed in yet'; 495 | } 496 | ``` 497 | 498 | A shorthand/alias for this method is `$auth->check()`. 499 | 500 | #### User ID 501 | 502 | ```php 503 | $id = $auth->getUserId(); 504 | ``` 505 | 506 | If the user is not currently signed in, this returns `null`. 507 | 508 | A shorthand/alias for this method is `$auth->id()`. 509 | 510 | #### Email address 511 | 512 | ```php 513 | $email = $auth->getEmail(); 514 | ``` 515 | 516 | If the user is not currently signed in, this returns `null`. 517 | 518 | #### Display name 519 | 520 | ```php 521 | $username = $auth->getUsername(); 522 | ``` 523 | 524 | Remember that usernames are optional and there is only a username if you supplied it during registration. 525 | 526 | If the user is not currently signed in, this returns `null`. 527 | 528 | #### Status information 529 | 530 | ```php 531 | if ($auth->isNormal()) { 532 | echo 'User is in default state'; 533 | } 534 | 535 | if ($auth->isArchived()) { 536 | echo 'User has been archived'; 537 | } 538 | 539 | if ($auth->isBanned()) { 540 | echo 'User has been banned'; 541 | } 542 | 543 | if ($auth->isLocked()) { 544 | echo 'User has been locked'; 545 | } 546 | 547 | if ($auth->isPendingReview()) { 548 | echo 'User is pending review'; 549 | } 550 | 551 | if ($auth->isSuspended()) { 552 | echo 'User has been suspended'; 553 | } 554 | ``` 555 | 556 | #### Checking whether the user was “remembered” 557 | 558 | ```php 559 | if ($auth->isRemembered()) { 560 | echo 'User did not sign in but was logged in through their long-lived cookie'; 561 | } 562 | else { 563 | echo 'User signed in manually'; 564 | } 565 | ``` 566 | 567 | If the user is not currently signed in, this returns `null`. 568 | 569 | #### IP address 570 | 571 | ```php 572 | $ip = $auth->getIpAddress(); 573 | ``` 574 | 575 | #### Additional user information 576 | 577 | In order to preserve this library’s suitability for all purposes as well as its full re-usability, it doesn’t come with additional bundled columns for user information. But you don’t have to do without additional user information, of course: 578 | 579 | Here’s how to use this library with your own tables for custom user information in a maintainable and re-usable way: 580 | 581 | 1. Add any number of custom database tables where you store custom user information, e.g. a table named `profiles`. 582 | 1. Whenever you call the `register` method (which returns the new user’s ID), add your own logic afterwards that fills your custom database tables. 583 | 1. If you need the custom user information only rarely, you may just retrieve it as needed. If you need it more frequently, however, you’d probably want to have it in your session data. The following method is how you can load and access your data in a reliable way: 584 | 585 | ```php 586 | function getUserInfo(\Comet\Auth $auth) { 587 | if (!$auth->isLoggedIn()) { 588 | return null; 589 | } 590 | 591 | if (!isset($_SESSION['_internal_user_info'])) { 592 | // TODO: load your custom user information and assign it to the session variable below 593 | // $_SESSION['_internal_user_info'] = ... 594 | } 595 | 596 | return $_SESSION['_internal_user_info']; 597 | } 598 | ``` 599 | 600 | ### Reconfirming the user’s password 601 | 602 | Whenever you want to confirm the user’s identity again, e.g. before the user is allowed to perform some “dangerous” action, you should verify their password again to confirm that they actually are who they claim to be. 603 | 604 | For example, when a user has been remembered by a long-lived cookie and thus `Auth#isRemembered` returns `true`, this means that the user probably has not entered their password for quite some time anymore. You may want to reconfirm their password in that case. 605 | 606 | ```php 607 | try { 608 | if ($auth->reconfirmPassword($_POST['password'])) { 609 | echo 'The user really seems to be who they claim to be'; 610 | } 611 | else { 612 | echo 'We can\'t say if the user is who they claim to be'; 613 | } 614 | } 615 | catch (\Comet\NotLoggedInException $e) { 616 | die('The user is not signed in'); 617 | } 618 | catch (\Comet\TooManyRequestsException $e) { 619 | die('Too many requests'); 620 | } 621 | ``` 622 | 623 | ### Roles (or groups) 624 | 625 | Every user can have any number of roles, which you can use to implement authorization and to refine your access controls. 626 | 627 | Users may have no role at all (which they do by default), exactly one role, or any arbitrary combination of roles. 628 | 629 | #### Checking roles 630 | 631 | ```php 632 | if ($auth->hasRole(\Comet\Role::SUPER_MODERATOR)) { 633 | echo 'The user is a super moderator'; 634 | } 635 | 636 | // or 637 | 638 | if ($auth->hasAnyRole(\Comet\Role::DEVELOPER, \Comet\Auth\Role::MANAGER)) { 639 | echo 'The user is either a developer, or a manager, or both'; 640 | } 641 | 642 | // or 643 | 644 | if ($auth->hasAllRoles(\Comet\Role::DEVELOPER, \Comet\Auth\Role::MANAGER)) { 645 | echo 'The user is both a developer and a manager'; 646 | } 647 | ``` 648 | 649 | While the method `hasRole` takes exactly one role as its argument, the two methods `hasAnyRole` and `hasAllRoles` can take any number of roles that you would like to check for. 650 | 651 | Alternatively, you can get a list of all the roles that have been assigned to the user: 652 | 653 | ```php 654 | $auth->getRoles(); 655 | ``` 656 | 657 | #### Available roles 658 | 659 | ```php 660 | \Comet\Role::ADMIN; 661 | \Comet\Role::AUTHOR; 662 | \Comet\Role::COLLABORATOR; 663 | \Comet\Role::CONSULTANT; 664 | \Comet\Role::CONSUMER; 665 | \Comet\Role::CONTRIBUTOR; 666 | \Comet\Role::COORDINATOR; 667 | \Comet\Role::CREATOR; 668 | \Comet\Role::DEVELOPER; 669 | \Comet\Role::DIRECTOR; 670 | \Comet\Role::EDITOR; 671 | \Comet\Role::EMPLOYEE; 672 | \Comet\Role::MAINTAINER; 673 | \Comet\Role::MANAGER; 674 | \Comet\Role::MODERATOR; 675 | \Comet\Role::PUBLISHER; 676 | \Comet\Role::REVIEWER; 677 | \Comet\Role::SUBSCRIBER; 678 | \Comet\Role::SUPER_ADMIN; 679 | \Comet\Role::SUPER_EDITOR; 680 | \Comet\Role::SUPER_MODERATOR; 681 | \Comet\Role::TRANSLATOR; 682 | ``` 683 | 684 | You can use any of these roles and ignore those that you don’t need. The list above can also be retrieved programmatically, in one of three formats: 685 | 686 | ```php 687 | \Comet\Role::getMap(); 688 | // or 689 | \Comet\Role::getNames(); 690 | // or 691 | \Comet\Role::getValues(); 692 | ``` 693 | 694 | #### Permissions (or access rights, privileges or capabilities) 695 | 696 | The permissions of each user are encoded in the way that role requirements are specified throughout your code base. If those requirements are evaluated with a specific user’s set of roles, implicitly checked permissions are the result. 697 | 698 | For larger projects, it is often recommended to maintain the definition of permissions in a single place. You then don’t check for *roles* in your business logic, but you check for *individual permissions*. You could implement that concept as follows: 699 | 700 | ```php 701 | function canEditArticle(\Comet\Auth\Auth $auth) { 702 | return $auth->hasAnyRole( 703 | \Comet\Role::MODERATOR, 704 | \Comet\Role::SUPER_MODERATOR, 705 | \Comet\Role::ADMIN, 706 | \Comet\Role::SUPER_ADMIN 707 | ); 708 | } 709 | 710 | // ... 711 | 712 | if (canEditArticle($auth)) { 713 | echo 'The user can edit articles here'; 714 | } 715 | 716 | // ... 717 | 718 | if (canEditArticle($auth)) { 719 | echo '... and here'; 720 | } 721 | 722 | // ... 723 | 724 | if (canEditArticle($auth)) { 725 | echo '... and here'; 726 | } 727 | ``` 728 | 729 | As you can see, the permission of whether a certain user can edit an article is stored at a central location. This implementation has two major advantages: 730 | 731 | If you *want to know* which users can edit articles, you don’t have to check your business logic in various places, but you only have to look where the specific permission is defined. And if you want to *change* who can edit an article, you only have to do this in one single place as well, not throughout your whole code base. 732 | 733 | But this also comes with slightly more overhead when implementing the access restrictions for the first time, which may or may not be worth it for your project. 734 | 735 | #### Custom role names 736 | 737 | If the names of the included roles don’t work for you, you can alias any number of roles using your own identifiers, e.g. like this: 738 | 739 | ```php 740 | namespace My\Namespace; 741 | 742 | final class MyRole { 743 | 744 | const CUSTOMER_SERVICE_AGENT = \Comet\Role::REVIEWER; 745 | const FINANCIAL_DIRECTOR = \Comet\Role::COORDINATOR; 746 | 747 | private function __construct() {} 748 | 749 | } 750 | ``` 751 | 752 | The example above would allow you to use 753 | 754 | ```php 755 | \My\Namespace\MyRole::CUSTOMER_SERVICE_AGENT; 756 | // and 757 | \My\Namespace\MyRole::FINANCIAL_DIRECTOR; 758 | ``` 759 | 760 | instead of 761 | 762 | ```php 763 | \Comet\Role::REVIEWER; 764 | // and 765 | \Comet\Role::COORDINATOR; 766 | ``` 767 | 768 | Just remember *not* to alias a *single* included role to *multiple* roles with custom names. 769 | 770 | ### Enabling or disabling password resets 771 | 772 | While password resets via email are a convenient feature that most users find helpful from time to time, the availability of this feature implies that accounts on your service are only ever as secure as the user’s associated email account. 773 | 774 | You may provide security-conscious (and experienced) users with the possibility to disable password resets for their accounts (and to enable them again later) for enhanced security: 775 | 776 | ```php 777 | try { 778 | if ($auth->reconfirmPassword($_POST['password'])) { 779 | $auth->setPasswordResetEnabled($_POST['enabled'] == 1); 780 | 781 | echo 'The setting has been changed'; 782 | } 783 | else { 784 | echo 'We can\'t say if the user is who they claim to be'; 785 | } 786 | } 787 | catch (\Comet\NotLoggedInException $e) { 788 | die('The user is not signed in'); 789 | } 790 | catch (\Comet\TooManyRequestsException $e) { 791 | die('Too many requests'); 792 | } 793 | ``` 794 | 795 | In order to check the current value of this setting, use the return value from 796 | 797 | ```php 798 | $auth->isPasswordResetEnabled(); 799 | ``` 800 | 801 | for the correct default option in your user interface. You don’t need to check this value for restrictions of the feature, which are enforced automatically. 802 | 803 | ### Throttling or rate limiting 804 | 805 | All methods provided by this library are *automatically* protected against excessive numbers of requests from clients. 806 | 807 | 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: 808 | 809 | ```php 810 | try { 811 | // throttle the specified resource or feature to *3* requests per *60* seconds 812 | $auth->throttle([ 'my-resource-name' ], 3, 60); 813 | 814 | echo 'Do something with the resource or feature'; 815 | } 816 | catch (\Comet\TooManyRequestsException $e) { 817 | // operation cancelled 818 | 819 | \http_response_code(429); 820 | exit; 821 | } 822 | ``` 823 | 824 | If the protection of the resource or feature should additionally depend on another attribute, e.g. to track something separately per IP address, just add more data to the resource description, such as: 825 | 826 | ```php 827 | [ 'my-resource-name', $_SERVER['REMOTE_ADDR'] ] 828 | // instead of 829 | // [ 'my-resource-name' ] 830 | ``` 831 | 832 | Allowing short bursts of activity during peak demand is possible by specifying a burst factor as the fourth argument. A value of `5`, for example, would permit temporary bursts of fivefold activity, compared to the generally accepted level. 833 | 834 | 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. 835 | 836 | ### Administration (managing users) 837 | 838 | The administrative interface is available via `$auth->admin()`. You can call various method on this interface, as documented below. 839 | 840 | Do not forget to implement secure access control before exposing access to this interface. For example, you may provide access to this interface to logged in users with the administrator role only, or use the interface in private scripts only. 841 | 842 | #### Creating new users 843 | 844 | ```php 845 | try { 846 | $userId = $auth->admin()->createUser($_POST['email'], $_POST['password'], $_POST['username']); 847 | 848 | echo 'We have signed up a new user with the ID ' . $userId; 849 | } 850 | catch (\Comet\InvalidEmailException $e) { 851 | die('Invalid email address'); 852 | } 853 | catch (\Comet\InvalidPasswordException $e) { 854 | die('Invalid password'); 855 | } 856 | catch (\Comet\UserAlreadyExistsException $e) { 857 | die('User already exists'); 858 | } 859 | ``` 860 | 861 | The username in the third parameter is optional. You can pass `null` there if you don’t want to manage usernames. 862 | 863 | If you want to enforce unique usernames, on the other hand, simply call `createUserWithUniqueUsername` instead of `createUser`, and be prepared to catch the `DuplicateUsernameException`. 864 | 865 | #### Deleting users 866 | 867 | Deleting users by their ID: 868 | 869 | ```php 870 | try { 871 | $auth->admin()->deleteUserById($_POST['id']); 872 | } 873 | catch (\Comet\UnknownIdException $e) { 874 | die('Unknown ID'); 875 | } 876 | ``` 877 | 878 | Deleting users by their email address: 879 | 880 | ```php 881 | try { 882 | $auth->admin()->deleteUserByEmail($_POST['email']); 883 | } 884 | catch (\Comet\InvalidEmailException $e) { 885 | die('Unknown email address'); 886 | } 887 | ``` 888 | 889 | Deleting users by their username: 890 | 891 | ```php 892 | try { 893 | $auth->admin()->deleteUserByUsername($_POST['username']); 894 | } 895 | catch (\Comet\UnknownUsernameException $e) { 896 | die('Unknown username'); 897 | } 898 | catch (\Comet\AmbiguousUsernameException $e) { 899 | die('Ambiguous username'); 900 | } 901 | ``` 902 | 903 | #### Retrieving a list of registered users 904 | 905 | 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). 906 | 907 | That’s why it’s easier to use a single custom SQL query. Start with the following: 908 | 909 | ```sql 910 | SELECT id, email, username, status, verified, roles_mask, registered, last_login FROM users; 911 | ``` 912 | 913 | #### Assigning roles to users 914 | 915 | ```php 916 | try { 917 | $auth->admin()->addRoleForUserById($userId, \Comet\Auth\Role::ADMIN); 918 | } 919 | catch (\Comet\UnknownIdException $e) { 920 | die('Unknown user ID'); 921 | } 922 | 923 | // or 924 | 925 | try { 926 | $auth->admin()->addRoleForUserByEmail($userEmail, \Comet\Auth\Role::ADMIN); 927 | } 928 | catch (\Comet\InvalidEmailException $e) { 929 | die('Unknown email address'); 930 | } 931 | 932 | // or 933 | 934 | try { 935 | $auth->admin()->addRoleForUserByUsername($username, \Comet\Auth\Role::ADMIN); 936 | } 937 | catch (\Comet\UnknownUsernameException $e) { 938 | die('Unknown username'); 939 | } 940 | catch (\Comet\AmbiguousUsernameException $e) { 941 | die('Ambiguous username'); 942 | } 943 | ``` 944 | 945 | **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`. 946 | 947 | #### Taking roles away from users 948 | 949 | ```php 950 | try { 951 | $auth->admin()->removeRoleForUserById($userId, \Comet\Auth\Role::ADMIN); 952 | } 953 | catch (\Comet\UnknownIdException $e) { 954 | die('Unknown user ID'); 955 | } 956 | 957 | // or 958 | 959 | try { 960 | $auth->admin()->removeRoleForUserByEmail($userEmail, \Comet\Auth\Role::ADMIN); 961 | } 962 | catch (\Comet\InvalidEmailException $e) { 963 | die('Unknown email address'); 964 | } 965 | 966 | // or 967 | 968 | try { 969 | $auth->admin()->removeRoleForUserByUsername($username, \Comet\Auth\Role::ADMIN); 970 | } 971 | catch (\Comet\UnknownUsernameException $e) { 972 | die('Unknown username'); 973 | } 974 | catch (\Comet\AmbiguousUsernameException $e) { 975 | die('Ambiguous username'); 976 | } 977 | ``` 978 | 979 | **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`. 980 | 981 | #### Checking roles 982 | 983 | ```php 984 | try { 985 | if ($auth->admin()->doesUserHaveRole($userId, \Comet\Role::ADMIN)) { 986 | echo 'The specified user is an administrator'; 987 | } 988 | else { 989 | echo 'The specified user is not an administrator'; 990 | } 991 | } 992 | catch (\Comet\UnknownIdException $e) { 993 | die('Unknown user ID'); 994 | } 995 | ``` 996 | 997 | Alternatively, you can get a list of all the roles that have been assigned to the user: 998 | 999 | ```php 1000 | $auth->admin()->getRolesForUserById($userId); 1001 | ``` 1002 | 1003 | #### Impersonating users (logging in as user) 1004 | 1005 | ```php 1006 | try { 1007 | $auth->admin()->logInAsUserById($_POST['id']); 1008 | } 1009 | catch (\Comet\UnknownIdException $e) { 1010 | die('Unknown ID'); 1011 | } 1012 | catch (\Comet\EmailNotVerifiedException $e) { 1013 | die('Email address not verified'); 1014 | } 1015 | 1016 | // or 1017 | 1018 | try { 1019 | $auth->admin()->logInAsUserByEmail($_POST['email']); 1020 | } 1021 | catch (\Comet\InvalidEmailException $e) { 1022 | die('Unknown email address'); 1023 | } 1024 | catch (\Comet\EmailNotVerifiedException $e) { 1025 | die('Email address not verified'); 1026 | } 1027 | 1028 | // or 1029 | 1030 | try { 1031 | $auth->admin()->logInAsUserByUsername($_POST['username']); 1032 | } 1033 | catch (\Comet\UnknownUsernameException $e) { 1034 | die('Unknown username'); 1035 | } 1036 | catch (\Comet\AmbiguousUsernameException $e) { 1037 | die('Ambiguous username'); 1038 | } 1039 | catch (\Comet\EmailNotVerifiedException $e) { 1040 | die('Email address not verified'); 1041 | } 1042 | ``` 1043 | 1044 | #### Changing a user’s password 1045 | 1046 | ```php 1047 | try { 1048 | $auth->admin()->changePasswordForUserById($_POST['id'], $_POST['newPassword']); 1049 | } 1050 | catch (\Comet\UnknownIdException $e) { 1051 | die('Unknown ID'); 1052 | } 1053 | catch (\Comet\InvalidPasswordException $e) { 1054 | die('Invalid password'); 1055 | } 1056 | 1057 | // or 1058 | 1059 | try { 1060 | $auth->admin()->changePasswordForUserByUsername($_POST['username'], $_POST['newPassword']); 1061 | } 1062 | catch (\Comet\UnknownUsernameException $e) { 1063 | die('Unknown username'); 1064 | } 1065 | catch (\Comet\AmbiguousUsernameException $e) { 1066 | die('Ambiguous username'); 1067 | } 1068 | catch (\Comet\InvalidPasswordException $e) { 1069 | die('Invalid password'); 1070 | } 1071 | ``` 1072 | 1073 | ### Cookies 1074 | 1075 | This library uses two cookies to keep state on the client: The first, whose name you can retrieve using 1076 | 1077 | ```php 1078 | \session_name(); 1079 | ``` 1080 | 1081 | is the general (mandatory) session cookie. The second (optional) cookie is only used for [persistent logins](#keeping-the-user-logged-in) and its name can be retrieved as follows: 1082 | 1083 | ```php 1084 | \Comet\Auth::createRememberCookieName(); 1085 | ``` 1086 | 1087 | #### Renaming the library’s cookies 1088 | 1089 | You can rename the session cookie used by this library through one of the following means, in order of recommendation: 1090 | 1091 | * 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: 1092 | 1093 | ``` 1094 | session.name = session_v1 1095 | ``` 1096 | 1097 | * As early as possible in your application, and before you create the `Auth` instance, call `\ini_set` to change `session.name` to something like `session_v1`, as in: 1098 | 1099 | ```php 1100 | \ini_set('session.name', 'session_v1'); 1101 | ``` 1102 | 1103 | 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`). 1104 | 1105 | * 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: 1106 | 1107 | ```php 1108 | \session_name('session_v1'); 1109 | ``` 1110 | 1111 | 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`). 1112 | 1113 | 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. 1114 | 1115 | #### Defining the domain scope for cookies 1116 | 1117 | A cookie’s `domain` attribute controls which domain (and which subdomains) the cookie will be valid for, and thus where the user’s session and authentication state will be available. 1118 | 1119 | The recommended default is an empty string, which means that the cookie will only be valid for the *exact* current host, *excluding* any subdomains that may exist. You should only use a different value if you need to share cookies between different subdomains. Often, you’ll want to share cookies between the bare domain and the `www` subdomain, but you might also want to share them between any other set of subdomains. 1120 | 1121 | Whatever set of subdomains you choose, you should set the cookie’s attribute to the *most specific* domain name that still includes all your required subdomains. For example, to share cookies between `example.com` and `www.example.com`, you would set the attribute to `example.com`. But if you wanted to share cookies between `sub1.app.example.com` and `sub2.app.example.com`, you should set the attribute to `app.example.com`. Any explicitly specified domain name will always *include* all subdomains that may exist. 1122 | 1123 | You can change the attribute through one of the following means, in order of recommendation: 1124 | 1125 | * 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.: 1126 | 1127 | ``` 1128 | session.cookie_domain = example.com 1129 | ``` 1130 | 1131 | * As early as possible in your application, and before you create the `Auth` instance, call `\ini_set` to change the value of the `session.cookie_domain` directive as desired, e.g.: 1132 | 1133 | ```php 1134 | \ini_set('session.cookie_domain', 'example.com'); 1135 | ``` 1136 | 1137 | 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`). 1138 | 1139 | #### Restricting the path where cookies are available 1140 | 1141 | A cookie’s `path` attribute controls which directories (and subdirectories) the cookie will be valid for, and thus where the user’s session and authentication state will be available. 1142 | 1143 | In most cases, you’ll want to make cookies available for all paths, i.e. any directory and file, starting in the root directory. That is what a value of `/` for the attribute does, which is also the recommended default. You should only change this attribute to a different value, e.g. `/path/to/subfolder`, if you want to restrict which directories your cookies will be available in, e.g. to host multiple applications side-by-side, in different directories, under the same domain name. 1144 | 1145 | You can change the attribute through one of the following means, in order of recommendation: 1146 | 1147 | * 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.: 1148 | 1149 | ``` 1150 | session.cookie_path = / 1151 | ``` 1152 | 1153 | * As early as possible in your application, and before you create the `Auth` instance, call `\ini_set` to change the value of the `session.cookie_path` directive as desired, e.g.: 1154 | 1155 | ```php 1156 | \ini_set('session.cookie_path', '/'); 1157 | ``` 1158 | 1159 | 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`). 1160 | 1161 | #### Controlling client-side script access to cookies 1162 | 1163 | Using the `httponly` attribute, you can control whether client-side scripts, i.e. JavaScript, should be able to access your cookies or not. For security reasons, it is best to *deny* script access to your cookies, which reduces the damage that successful XSS attacks against your application could do, for example. 1164 | 1165 | Thus, you should always set `httponly` to `1`, except for the rare cases where you really need access to your cookies from JavaScript and can’t find any better solution. In those cases, set the attribute to `0`, but be aware of the consequences. 1166 | 1167 | You can change the attribute through one of the following means, in order of recommendation: 1168 | 1169 | * 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.: 1170 | 1171 | ``` 1172 | session.cookie_httponly = 1 1173 | ``` 1174 | 1175 | * As early as possible in your application, and before you create the `Auth` instance, call `\ini_set` to change the value of the `session.cookie_httponly` directive as desired, e.g.: 1176 | 1177 | ```php 1178 | \ini_set('session.cookie_httponly', 1); 1179 | ``` 1180 | 1181 | 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`). 1182 | 1183 | #### Configuring transport security for cookies 1184 | 1185 | Using the `secure` attribute, you can control whether cookies should be sent over *any* connection, including plain HTTP, or whether a secure connection, i.e. HTTPS (with SSL/TLS), should be required. The former (less secure) mode can be chosen by setting the attribute to `0`, and the latter (more secure) mode can be chosen by setting the attribute to `1`. 1186 | 1187 | Obviously, this solely depends on whether you are able to serve *all* pages exclusively via HTTPS. If you can, you should set the attribute to `1` and possibly combine it with HTTP redirects to the secure protocol and HTTP Strict Transport Security (HSTS). Otherwise, you may have to keep the attribute set to `0`. 1188 | 1189 | You can change the attribute through one of the following means, in order of recommendation: 1190 | 1191 | * 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.: 1192 | 1193 | ``` 1194 | session.cookie_secure = 1 1195 | ``` 1196 | 1197 | * As early as possible in your application, and before you create the `Auth` instance, call `\ini_set` to change the value of the `session.cookie_secure` directive as desired, e.g.: 1198 | 1199 | ```php 1200 | \ini_set('session.cookie_secure', 1); 1201 | ``` 1202 | 1203 | 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`). 1204 | 1205 | ### Utilities 1206 | 1207 | #### Creating a random string 1208 | 1209 | ```php 1210 | $length = 24; 1211 | $randomStr = \Comet\Auth::createRandomString($length); 1212 | ``` 1213 | 1214 | #### Creating a UUID v4 as per RFC 4122 1215 | 1216 | ```php 1217 | $uuid = \Comet\Auth::createUuid(); 1218 | ``` 1219 | 1220 | ### Reading and writing session data 1221 | 1222 | 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#reading-and-writing-session-data), which is included by default. 1223 | 1224 | ## Frequently asked questions 1225 | 1226 | ### What about password hashing? 1227 | 1228 | Any password or authentication token is automatically hashed using the [“bcrypt”](https://en.wikipedia.org/wiki/Bcrypt) function, which is based on the [“Blowfish” cipher](https://en.wikipedia.org/wiki/Blowfish_(cipher)) and (still) considered one of the strongest password hash functions today. “bcrypt” is used with 1,024 iterations, i.e. a “cost” factor of 10. A random [“salt”](https://en.wikipedia.org/wiki/Salt_(cryptography)) is applied automatically as well. 1229 | 1230 | You can verify this configuration by looking at the hashes in your database table `users`. If the above is true with your setup, all password hashes in your `users` table should start with the prefix `$2$10$`, `$2a$10$` or `$2y$10$`. 1231 | 1232 | When new algorithms (such as [Argon2](https://en.wikipedia.org/wiki/Argon2)) may be introduced in the future, this library will automatically take care of “upgrading” your existing password hashes whenever a user signs in or changes their password. 1233 | 1234 | ### How can I implement custom password requirements? 1235 | 1236 | Enforcing a minimum length for passwords is usually a good idea. Apart from that, you may want to look up whether a potential password is in some blacklist, which you could manage in a database or in a file, in order to prevent dictionary words or commonly used passwords from being used in your application. 1237 | 1238 | To allow for maximum flexibility and ease of use, this library has been designed so that it does *not* contain any further checks for password requirements itself, but instead allows you to wrap your own checks around the relevant calls to library methods. Example: 1239 | 1240 | ```php 1241 | function isPasswordAllowed($password) { 1242 | if (\strlen($password) < 8) { 1243 | return false; 1244 | } 1245 | 1246 | $blacklist = [ 'password1', '123456', 'qwerty' ]; 1247 | 1248 | if (\in_array($password, $blacklist)) { 1249 | return false; 1250 | } 1251 | 1252 | return true; 1253 | } 1254 | 1255 | if (isPasswordAllowed($password)) { 1256 | $auth->register($email, $password); 1257 | } 1258 | ``` 1259 | 1260 | ### Why are there problems when using other libraries that work with sessions? 1261 | 1262 | You might try loading this library first, and creating the `Auth` instance first, *before* loading the other libraries. Apart from that, there’s probably not much we can do here. 1263 | 1264 | ### Why are other sites not able to frame or embed my site? 1265 | 1266 | If you want to let others include your site in a ``, `