├── .gitignore ├── .gitattributes ├── renovate.json ├── src ├── DatabaseError.php ├── MissingCallbackError.php ├── UnknownIdException.php ├── NotLoggedInException.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 └── Auth.php ├── composer.json ├── loader.php ├── Database ├── PostgreSQL.sql ├── SQLite.sql └── MySQL.sql └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | /vendor 2 | composer.phar 3 | composer.lock 4 | /.github 5 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:base" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /src/DatabaseError.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/MissingCallbackError.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/UnknownIdException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/NotLoggedInException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/HeadersAlreadySentError.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/InvalidEmailException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/ResetDisabledException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/TokenExpiredException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/AttemptCancelledException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/EmailNotVerifiedException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/InvalidPasswordException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/TooManyRequestsException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/UnknownUsernameException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/AmbiguousUsernameException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/ConfirmationRequestNotFound.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/DuplicateUsernameException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/EmailOrUsernameRequiredError.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/UserAlreadyExistsException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/AuthError.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/InvalidSelectorTokenPairException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/AuthException.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/Status.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "devinow/auth", 3 | "description": "Devinow Framework Auth Library,Authentication, Simple, lightweight and secure.", 4 | "type": "library", 5 | "license": "MIT", 6 | "keywords": [ "auth", "authentication", "login", "security" ], 7 | "require": { 8 | "php": ">=8.1.0", 9 | "devinow/base64": "*", 10 | "devinow/cookie": "*", 11 | "devinow/database": "*" 12 | }, 13 | "authors": [ 14 | { 15 | "name": "Devinow", 16 | "email": "info@devinow.xyz", 17 | "homepage": "https://devinow.xyz", 18 | "role": "Developer" 19 | } 20 | ], 21 | "repositories": [ 22 | { 23 | "type": "vcs", 24 | "url": "https://github.com/devinow/auth" 25 | } 26 | ], 27 | "support": { 28 | "email": "info@devinow.xyz" 29 | }, 30 | "minimum-stability": "stable", 31 | "prefer-stable": true, 32 | "autoload": { 33 | "psr-4": { 34 | "Devinow\\Auth\\": "/" 35 | }, 36 | "files": [ 37 | "loader.php" 38 | ] 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /loader.php: -------------------------------------------------------------------------------- 1 | 37 | -------------------------------------------------------------------------------- /src/Role.php: -------------------------------------------------------------------------------- 1 | getConstants()); 51 | } 52 | 53 | /** 54 | * Returns the descriptive role names 55 | * 56 | * @return string[] 57 | */ 58 | public static function getNames() { 59 | $reflectionClass = new \ReflectionClass(static::class); 60 | 61 | return \array_keys($reflectionClass->getConstants()); 62 | } 63 | 64 | /** 65 | * Returns the numerical role values 66 | * 67 | * @return int[] 68 | */ 69 | public static function getValues() { 70 | $reflectionClass = new \ReflectionClass(static::class); 71 | 72 | return \array_values($reflectionClass->getConstants()); 73 | } 74 | 75 | private function __construct() {} 76 | 77 | } 78 | 79 | ?> 80 | -------------------------------------------------------------------------------- /Database/PostgreSQL.sql: -------------------------------------------------------------------------------- 1 | BEGIN; 2 | 3 | CREATE TABLE IF NOT EXISTS "users" ( 4 | "id" SERIAL PRIMARY KEY CHECK ("id" >= 0), 5 | "email" VARCHAR(249) UNIQUE NOT NULL, 6 | "password" VARCHAR(255) NOT NULL, 7 | "username" VARCHAR(100) DEFAULT NULL, 8 | "status" SMALLINT NOT NULL DEFAULT '0' CHECK ("status" >= 0), 9 | "verified" SMALLINT NOT NULL DEFAULT '0' CHECK ("verified" >= 0), 10 | "resettable" SMALLINT NOT NULL DEFAULT '1' CHECK ("resettable" >= 0), 11 | "roles_mask" INTEGER NOT NULL DEFAULT '0' CHECK ("roles_mask" >= 0), 12 | "registered" INTEGER NOT NULL CHECK ("registered" >= 0), 13 | "last_login" INTEGER DEFAULT NULL CHECK ("last_login" >= 0), 14 | "force_logout" INTEGER NOT NULL DEFAULT '0' CHECK ("force_logout" >= 0) 15 | ); 16 | 17 | CREATE TABLE IF NOT EXISTS "users_confirmations" ( 18 | "id" SERIAL PRIMARY KEY CHECK ("id" >= 0), 19 | "user_id" INTEGER NOT NULL CHECK ("user_id" >= 0), 20 | "email" VARCHAR(249) NOT NULL, 21 | "selector" VARCHAR(16) UNIQUE NOT NULL, 22 | "token" VARCHAR(255) NOT NULL, 23 | "expires" INTEGER NOT NULL CHECK ("expires" >= 0) 24 | ); 25 | CREATE INDEX IF NOT EXISTS "email_expires" ON "users_confirmations" ("email", "expires"); 26 | CREATE INDEX IF NOT EXISTS "user_id" ON "users_confirmations" ("user_id"); 27 | 28 | CREATE TABLE IF NOT EXISTS "users_remembered" ( 29 | "id" BIGSERIAL PRIMARY KEY CHECK ("id" >= 0), 30 | "user" INTEGER NOT NULL CHECK ("user" >= 0), 31 | "selector" VARCHAR(24) UNIQUE NOT NULL, 32 | "token" VARCHAR(255) NOT NULL, 33 | "expires" INTEGER NOT NULL CHECK ("expires" >= 0) 34 | ); 35 | CREATE INDEX IF NOT EXISTS "user" ON "users_remembered" ("user"); 36 | 37 | CREATE TABLE IF NOT EXISTS "users_resets" ( 38 | "id" BIGSERIAL PRIMARY KEY CHECK ("id" >= 0), 39 | "user" INTEGER NOT NULL CHECK ("user" >= 0), 40 | "selector" VARCHAR(20) UNIQUE NOT NULL, 41 | "token" VARCHAR(255) NOT NULL, 42 | "expires" INTEGER NOT NULL CHECK ("expires" >= 0) 43 | ); 44 | CREATE INDEX IF NOT EXISTS "user_expires" ON "users_resets" ("user", "expires"); 45 | 46 | CREATE TABLE IF NOT EXISTS "users_throttling" ( 47 | "bucket" VARCHAR(44) PRIMARY KEY, 48 | "tokens" REAL NOT NULL CHECK ("tokens" >= 0), 49 | "replenished_at" INTEGER NOT NULL CHECK ("replenished_at" >= 0), 50 | "expires_at" INTEGER NOT NULL CHECK ("expires_at" >= 0) 51 | ); 52 | CREATE INDEX IF NOT EXISTS "expires_at" ON "users_throttling" ("expires_at"); 53 | 54 | COMMIT; 55 | -------------------------------------------------------------------------------- /Database/SQLite.sql: -------------------------------------------------------------------------------- 1 | PRAGMA foreign_keys = OFF; 2 | 3 | CREATE TABLE "users" ( 4 | "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0), 5 | "email" VARCHAR(249) NOT NULL, 6 | "password" VARCHAR(255) NOT NULL, 7 | "username" VARCHAR(100) DEFAULT NULL, 8 | "status" INTEGER NOT NULL CHECK ("status" >= 0) DEFAULT "0", 9 | "verified" INTEGER NOT NULL CHECK ("verified" >= 0) DEFAULT "0", 10 | "resettable" INTEGER NOT NULL CHECK ("resettable" >= 0) DEFAULT "1", 11 | "roles_mask" INTEGER NOT NULL CHECK ("roles_mask" >= 0) DEFAULT "0", 12 | "registered" INTEGER NOT NULL CHECK ("registered" >= 0), 13 | "last_login" INTEGER CHECK ("last_login" >= 0) DEFAULT NULL, 14 | "force_logout" INTEGER NOT NULL CHECK ("force_logout" >= 0) DEFAULT "0", 15 | CONSTRAINT "email" UNIQUE ("email") 16 | ); 17 | 18 | CREATE TABLE "users_confirmations" ( 19 | "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0), 20 | "user_id" INTEGER NOT NULL CHECK ("user_id" >= 0), 21 | "email" VARCHAR(249) NOT NULL, 22 | "selector" VARCHAR(16) NOT NULL, 23 | "token" VARCHAR(255) NOT NULL, 24 | "expires" INTEGER NOT NULL CHECK ("expires" >= 0), 25 | CONSTRAINT "selector" UNIQUE ("selector") 26 | ); 27 | CREATE INDEX "users_confirmations.email_expires" ON "users_confirmations" ("email", "expires"); 28 | CREATE INDEX "users_confirmations.user_id" ON "users_confirmations" ("user_id"); 29 | 30 | CREATE TABLE "users_remembered" ( 31 | "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0), 32 | "user" INTEGER NOT NULL CHECK ("user" >= 0), 33 | "selector" VARCHAR(24) NOT NULL, 34 | "token" VARCHAR(255) NOT NULL, 35 | "expires" INTEGER NOT NULL CHECK ("expires" >= 0), 36 | CONSTRAINT "selector" UNIQUE ("selector") 37 | ); 38 | CREATE INDEX "users_remembered.user" ON "users_remembered" ("user"); 39 | 40 | CREATE TABLE "users_resets" ( 41 | "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK ("id" >= 0), 42 | "user" INTEGER NOT NULL CHECK ("user" >= 0), 43 | "selector" VARCHAR(20) NOT NULL, 44 | "token" VARCHAR(255) NOT NULL, 45 | "expires" INTEGER NOT NULL CHECK ("expires" >= 0), 46 | CONSTRAINT "selector" UNIQUE ("selector") 47 | ); 48 | CREATE INDEX "users_resets.user_expires" ON "users_resets" ("user", "expires"); 49 | 50 | CREATE TABLE "users_throttling" ( 51 | "bucket" VARCHAR(44) PRIMARY KEY NOT NULL, 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 "users_throttling.expires_at" ON "users_throttling" ("expires_at"); 57 | -------------------------------------------------------------------------------- /Database/MySQL.sql: -------------------------------------------------------------------------------- 1 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 2 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 3 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 4 | /*!40101 SET NAMES utf8mb4 */; 5 | 6 | CREATE TABLE IF NOT EXISTS `users` ( 7 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 8 | `email` varchar(249) COLLATE utf8mb4_unicode_ci NOT NULL, 9 | `password` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 10 | `username` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, 11 | `status` tinyint(2) unsigned NOT NULL DEFAULT '0', 12 | `verified` tinyint(1) unsigned NOT NULL DEFAULT '0', 13 | `resettable` tinyint(1) unsigned NOT NULL DEFAULT '1', 14 | `roles_mask` int(10) unsigned NOT NULL DEFAULT '0', 15 | `registered` int(10) unsigned NOT NULL, 16 | `last_login` int(10) unsigned DEFAULT NULL, 17 | `force_logout` mediumint(7) unsigned NOT NULL DEFAULT '0', 18 | PRIMARY KEY (`id`), 19 | UNIQUE KEY `email` (`email`) 20 | ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 21 | 22 | CREATE TABLE IF NOT EXISTS `users_confirmations` ( 23 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 24 | `user_id` int(10) unsigned NOT NULL, 25 | `email` varchar(249) COLLATE utf8mb4_unicode_ci NOT NULL, 26 | `selector` varchar(16) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 27 | `token` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 28 | `expires` int(10) unsigned NOT NULL, 29 | PRIMARY KEY (`id`), 30 | UNIQUE KEY `selector` (`selector`), 31 | KEY `email_expires` (`email`,`expires`), 32 | KEY `user_id` (`user_id`) 33 | ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 34 | 35 | CREATE TABLE IF NOT EXISTS `users_remembered` ( 36 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, 37 | `user` int(10) unsigned NOT NULL, 38 | `selector` varchar(24) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 39 | `token` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 40 | `expires` int(10) unsigned NOT NULL, 41 | PRIMARY KEY (`id`), 42 | UNIQUE KEY `selector` (`selector`), 43 | KEY `user` (`user`) 44 | ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 45 | 46 | CREATE TABLE IF NOT EXISTS `users_resets` ( 47 | `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, 48 | `user` int(10) unsigned NOT NULL, 49 | `selector` varchar(20) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 50 | `token` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 51 | `expires` int(10) unsigned NOT NULL, 52 | PRIMARY KEY (`id`), 53 | UNIQUE KEY `selector` (`selector`), 54 | KEY `user_expires` (`user`,`expires`) 55 | ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 56 | 57 | CREATE TABLE IF NOT EXISTS `users_throttling` ( 58 | `bucket` varchar(44) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, 59 | `tokens` float unsigned NOT NULL, 60 | `replenished_at` int(10) unsigned NOT NULL, 61 | `expires_at` int(10) unsigned NOT NULL, 62 | PRIMARY KEY (`bucket`), 63 | KEY `expires_at` (`expires_at`) 64 | ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 65 | 66 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 67 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 68 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 69 | -------------------------------------------------------------------------------- /src/UserManager.php: -------------------------------------------------------------------------------- 1 | db = $databaseConnection; 76 | } 77 | elseif ($databaseConnection instanceof PdoDsn) { 78 | $this->db = PdoDatabase::fromDsn($databaseConnection); 79 | } 80 | elseif ($databaseConnection instanceof \PDO) { 81 | $this->db = PdoDatabase::fromPdo($databaseConnection, true); 82 | } 83 | else { 84 | $this->db = null; 85 | 86 | throw new \InvalidArgumentException('The database connection must be an instance of either `PdoDatabase`, `PdoDsn` or `PDO`'); 87 | } 88 | 89 | $this->dbSchema = $dbSchema !== null ? (string) $dbSchema : null; 90 | $this->dbTablePrefix = (string) $dbTablePrefix; 91 | } 92 | 93 | /** 94 | * Creates a new user 95 | * 96 | * If you want the user's account to be activated by default, pass `null` as the callback 97 | * 98 | * If you want to make the user verify their email address first, pass an anonymous function as the callback 99 | * 100 | * The callback function must have the following signature: 101 | * 102 | * `function ($selector, $token)` 103 | * 104 | * Both pieces of information must be sent to the user, usually embedded in a link 105 | * 106 | * When the user wants to verify their email address as a next step, both pieces will be required again 107 | * 108 | * @param bool $requireUniqueUsername whether it must be ensured that the username is unique 109 | * @param string $email the email address to register 110 | * @param string $password the password for the new account 111 | * @param string|null $username (optional) the username that will be displayed 112 | * @param callable|null $callback (optional) the function that sends the confirmation email to the user 113 | * @return int the ID of the user that has been created (if any) 114 | * @throws InvalidEmailException if the email address has been invalid 115 | * @throws InvalidPasswordException if the password has been invalid 116 | * @throws UserAlreadyExistsException if a user with the specified email address already exists 117 | * @throws DuplicateUsernameException if it was specified that the username must be unique while it was *not* 118 | * @throws AuthError if an internal problem occurred (do *not* catch) 119 | * 120 | * @see confirmEmail 121 | * @see confirmEmailAndSignIn 122 | */ 123 | protected function createUserInternal($requireUniqueUsername, $email, $password, $username = null, callable $callback = null) { 124 | \ignore_user_abort(true); 125 | 126 | $email = self::validateEmailAddress($email); 127 | $password = self::validatePassword($password); 128 | 129 | $username = isset($username) ? \trim($username) : null; 130 | 131 | // if the supplied username is the empty string or has consisted of whitespace only 132 | if ($username === '') { 133 | // this actually means that there is no username 134 | $username = null; 135 | } 136 | 137 | // if the uniqueness of the username is to be ensured 138 | if ($requireUniqueUsername) { 139 | // if a username has actually been provided 140 | if ($username !== null) { 141 | // count the number of users who do already have that specified username 142 | $occurrencesOfUsername = $this->db->selectValue( 143 | 'SELECT COUNT(*) FROM ' . $this->makeTableName('users') . ' WHERE username = ?', 144 | [ $username ] 145 | ); 146 | 147 | // if any user with that username does already exist 148 | if ($occurrencesOfUsername > 0) { 149 | // cancel the operation and report the violation of this requirement 150 | throw new DuplicateUsernameException(); 151 | } 152 | } 153 | } 154 | 155 | $password = \password_hash($password, \PASSWORD_DEFAULT); 156 | $verified = \is_callable($callback) ? 0 : 1; 157 | 158 | try { 159 | $this->db->insert( 160 | $this->makeTableNameComponents('users'), 161 | [ 162 | 'email' => $email, 163 | 'password' => $password, 164 | 'username' => $username, 165 | 'verified' => $verified, 166 | 'registered' => \time() 167 | ] 168 | ); 169 | } 170 | // if we have a duplicate entry 171 | catch (IntegrityConstraintViolationException $e) { 172 | throw new UserAlreadyExistsException(); 173 | } 174 | catch (Error $e) { 175 | throw new DatabaseError($e->getMessage()); 176 | } 177 | 178 | $newUserId = (int) $this->db->getLastInsertId(); 179 | 180 | if ($verified === 0) { 181 | $this->createConfirmationRequest($newUserId, $email, $callback); 182 | } 183 | 184 | return $newUserId; 185 | } 186 | 187 | /** 188 | * Updates the given user's password by setting it to the new specified password 189 | * 190 | * @param int $userId the ID of the user whose password should be updated 191 | * @param string $newPassword the new password 192 | * @throws UnknownIdException if no user with the specified ID has been found 193 | * @throws AuthError if an internal problem occurred (do *not* catch) 194 | */ 195 | protected function updatePasswordInternal($userId, $newPassword) { 196 | $newPassword = \password_hash($newPassword, \PASSWORD_DEFAULT); 197 | 198 | try { 199 | $affected = $this->db->update( 200 | $this->makeTableNameComponents('users'), 201 | [ 'password' => $newPassword ], 202 | [ 'id' => $userId ] 203 | ); 204 | 205 | if ($affected === 0) { 206 | throw new UnknownIdException(); 207 | } 208 | } 209 | catch (Error $e) { 210 | throw new DatabaseError($e->getMessage()); 211 | } 212 | } 213 | 214 | /** 215 | * Called when a user has successfully logged in 216 | * 217 | * This may happen via the standard login, via the "remember me" feature, or due to impersonation by administrators 218 | * 219 | * @param int $userId the ID of the user 220 | * @param string $email the email address of the user 221 | * @param string $username the display name (if any) of the user 222 | * @param int $status the status of the user as one of the constants from the {@see Status} class 223 | * @param int $roles the roles of the user as a bitmask using constants from the {@see Role} class 224 | * @param int $forceLogout the counter that keeps track of forced logouts that need to be performed in the current session 225 | * @param bool $remembered whether the user has been remembered (instead of them having authenticated actively) 226 | * @throws AuthError if an internal problem occurred (do *not* catch) 227 | */ 228 | protected function onLoginSuccessful($userId, $email, $username, $status, $roles, $forceLogout, $remembered) { 229 | // re-generate the session ID to prevent session fixation attacks (requests a cookie to be written on the client) 230 | Session::regenerate(true); 231 | 232 | // save the user data in the session variables maintained by this library 233 | $_SESSION[self::SESSION_FIELD_LOGGED_IN] = true; 234 | $_SESSION[self::SESSION_FIELD_USER_ID] = (int) $userId; 235 | $_SESSION[self::SESSION_FIELD_EMAIL] = $email; 236 | $_SESSION[self::SESSION_FIELD_USERNAME] = $username; 237 | $_SESSION[self::SESSION_FIELD_STATUS] = (int) $status; 238 | $_SESSION[self::SESSION_FIELD_ROLES] = (int) $roles; 239 | $_SESSION[self::SESSION_FIELD_FORCE_LOGOUT] = (int) $forceLogout; 240 | $_SESSION[self::SESSION_FIELD_REMEMBERED] = $remembered; 241 | $_SESSION[self::SESSION_FIELD_LAST_RESYNC] = \time(); 242 | } 243 | 244 | /** 245 | * Returns the requested user data for the account with the specified username (if any) 246 | * 247 | * You must never pass untrusted input to the parameter that takes the column list 248 | * 249 | * @param string $username the username to look for 250 | * @param array $requestedColumns the columns to request from the user's record 251 | * @return array the user data (if an account was found unambiguously) 252 | * @throws UnknownUsernameException if no user with the specified username has been found 253 | * @throws AmbiguousUsernameException if multiple users with the specified username have been found 254 | * @throws AuthError if an internal problem occurred (do *not* catch) 255 | */ 256 | protected function getUserDataByUsername($username, array $requestedColumns) { 257 | try { 258 | $projection = \implode(', ', $requestedColumns); 259 | 260 | $users = $this->db->select( 261 | 'SELECT ' . $projection . ' FROM ' . $this->makeTableName('users') . ' WHERE username = ? LIMIT 2 OFFSET 0', 262 | [ $username ] 263 | ); 264 | } 265 | catch (Error $e) { 266 | throw new DatabaseError($e->getMessage()); 267 | } 268 | 269 | if (empty($users)) { 270 | throw new UnknownUsernameException(); 271 | } 272 | else { 273 | if (\count($users) === 1) { 274 | return $users[0]; 275 | } 276 | else { 277 | throw new AmbiguousUsernameException(); 278 | } 279 | } 280 | } 281 | 282 | /** 283 | * Validates an email address 284 | * 285 | * @param string $email the email address to validate 286 | * @return string the sanitized email address 287 | * @throws InvalidEmailException if the email address has been invalid 288 | */ 289 | protected static function validateEmailAddress($email) { 290 | if (empty($email)) { 291 | throw new InvalidEmailException(); 292 | } 293 | 294 | $email = \trim($email); 295 | 296 | if (!\filter_var($email, \FILTER_VALIDATE_EMAIL)) { 297 | throw new InvalidEmailException(); 298 | } 299 | 300 | return $email; 301 | } 302 | 303 | /** 304 | * Validates a password 305 | * 306 | * @param string $password the password to validate 307 | * @return string the sanitized password 308 | * @throws InvalidPasswordException if the password has been invalid 309 | */ 310 | protected static function validatePassword($password) { 311 | if (empty($password)) { 312 | throw new InvalidPasswordException(); 313 | } 314 | 315 | $password = \trim($password); 316 | 317 | if (\strlen($password) < 1) { 318 | throw new InvalidPasswordException(); 319 | } 320 | 321 | return $password; 322 | } 323 | 324 | /** 325 | * Creates a request for email confirmation 326 | * 327 | * The callback function must have the following signature: 328 | * 329 | * `function ($selector, $token)` 330 | * 331 | * Both pieces of information must be sent to the user, usually embedded in a link 332 | * 333 | * When the user wants to verify their email address as a next step, both pieces will be required again 334 | * 335 | * @param int $userId the user's ID 336 | * @param string $email the email address to verify 337 | * @param callable $callback the function that sends the confirmation email to the user 338 | * @throws AuthError if an internal problem occurred (do *not* catch) 339 | */ 340 | protected function createConfirmationRequest($userId, $email, callable $callback) { 341 | $selector = self::createRandomString(16); 342 | $token = self::createRandomString(16); 343 | $tokenHashed = \password_hash($token, \PASSWORD_DEFAULT); 344 | $expires = \time() + 60 * 60 * 24; 345 | 346 | try { 347 | $this->db->insert( 348 | $this->makeTableNameComponents('users_confirmations'), 349 | [ 350 | 'user_id' => (int) $userId, 351 | 'email' => $email, 352 | 'selector' => $selector, 353 | 'token' => $tokenHashed, 354 | 'expires' => $expires 355 | ] 356 | ); 357 | } 358 | catch (Error $e) { 359 | throw new DatabaseError($e->getMessage()); 360 | } 361 | 362 | if (\is_callable($callback)) { 363 | $callback($selector, $token); 364 | } 365 | else { 366 | throw new MissingCallbackError(); 367 | } 368 | } 369 | 370 | /** 371 | * Clears an existing directive that keeps the user logged in ("remember me") 372 | * 373 | * @param int $userId the ID of the user who shouldn't be kept signed in anymore 374 | * @param string $selector (optional) the selector which the deletion should be restricted to 375 | * @throws AuthError if an internal problem occurred (do *not* catch) 376 | */ 377 | protected function deleteRememberDirectiveForUserById($userId, $selector = null) { 378 | $whereMappings = []; 379 | 380 | if (isset($selector)) { 381 | $whereMappings['selector'] = (string) $selector; 382 | } 383 | 384 | $whereMappings['user'] = (int) $userId; 385 | 386 | try { 387 | $this->db->delete( 388 | $this->makeTableNameComponents('users_remembered'), 389 | $whereMappings 390 | ); 391 | } 392 | catch (Error $e) { 393 | throw new DatabaseError($e->getMessage()); 394 | } 395 | } 396 | 397 | /** 398 | * Triggers a forced logout in all sessions that belong to the specified user 399 | * 400 | * @param int $userId the ID of the user to sign out 401 | * @throws AuthError if an internal problem occurred (do *not* catch) 402 | */ 403 | protected function forceLogoutForUserById($userId) { 404 | $this->deleteRememberDirectiveForUserById($userId); 405 | $this->db->exec( 406 | 'UPDATE ' . $this->makeTableName('users') . ' SET force_logout = force_logout + 1 WHERE id = ?', 407 | [ $userId ] 408 | ); 409 | } 410 | 411 | /** 412 | * Builds a (qualified) full table name from an optional qualifier, an optional prefix, and the table name itself 413 | * 414 | * The optional qualifier may be a database name or a schema name, for example 415 | * 416 | * @param string $name the name of the table 417 | * @return string[] the components of the (qualified) full name of the table 418 | */ 419 | protected function makeTableNameComponents($name) { 420 | $components = []; 421 | 422 | if (!empty($this->dbSchema)) { 423 | $components[] = $this->dbSchema; 424 | } 425 | 426 | if (!empty($name)) { 427 | if (!empty($this->dbTablePrefix)) { 428 | $components[] = $this->dbTablePrefix . $name; 429 | } 430 | else { 431 | $components[] = $name; 432 | } 433 | } 434 | 435 | return $components; 436 | } 437 | 438 | /** 439 | * Builds a (qualified) full table name from an optional qualifier, an optional prefix, and the table name itself 440 | * 441 | * The optional qualifier may be a database name or a schema name, for example 442 | * 443 | * @param string $name the name of the table 444 | * @return string the (qualified) full name of the table 445 | */ 446 | protected function makeTableName($name) { 447 | $components = $this->makeTableNameComponents($name); 448 | 449 | return \implode('.', $components); 450 | } 451 | 452 | } 453 | 454 | ?> -------------------------------------------------------------------------------- /src/Administration.php: -------------------------------------------------------------------------------- 1 | createUserInternal(false, $email, $password, $username, null); 39 | } 40 | 41 | /** 42 | * Creates a new user while ensuring that the username is unique 43 | * 44 | * @param string $email the email address to register 45 | * @param string $password the password for the new account 46 | * @param string|null $username (optional) the username that will be displayed 47 | * @return int the ID of the user that has been created (if any) 48 | * @throws InvalidEmailException if the email address was invalid 49 | * @throws InvalidPasswordException if the password was invalid 50 | * @throws UserAlreadyExistsException if a user with the specified email address already exists 51 | * @throws DuplicateUsernameException if the specified username wasn't unique 52 | * @throws AuthError if an internal problem occurred (do *not* catch) 53 | */ 54 | public function createUserWithUniqueUsername($email, $password, $username = null) { 55 | return $this->createUserInternal(true, $email, $password, $username, null); 56 | } 57 | 58 | /** 59 | * Deletes the user with the specified ID 60 | * 61 | * This action cannot be undone 62 | * 63 | * @param int $id the ID of the user to delete 64 | * @throws UnknownIdException if no user with the specified ID has been found 65 | * @throws AuthError if an internal problem occurred (do *not* catch) 66 | */ 67 | public function deleteUserById($id) { 68 | $numberOfDeletedUsers = $this->deleteUsersByColumnValue('id', (int) $id); 69 | 70 | if ($numberOfDeletedUsers === 0) { 71 | throw new UnknownIdException(); 72 | } 73 | } 74 | 75 | /** 76 | * Deletes the user with the specified email address 77 | * 78 | * This action cannot be undone 79 | * 80 | * @param string $email the email address of the user to delete 81 | * @throws InvalidEmailException if no user with the specified email address has been found 82 | * @throws AuthError if an internal problem occurred (do *not* catch) 83 | */ 84 | public function deleteUserByEmail($email) { 85 | $email = self::validateEmailAddress($email); 86 | 87 | $numberOfDeletedUsers = $this->deleteUsersByColumnValue('email', $email); 88 | 89 | if ($numberOfDeletedUsers === 0) { 90 | throw new InvalidEmailException(); 91 | } 92 | } 93 | 94 | /** 95 | * Deletes the user with the specified username 96 | * 97 | * This action cannot be undone 98 | * 99 | * @param string $username the username of the user to delete 100 | * @throws UnknownUsernameException if no user with the specified username has been found 101 | * @throws AmbiguousUsernameException if multiple users with the specified username have been found 102 | * @throws AuthError if an internal problem occurred (do *not* catch) 103 | */ 104 | public function deleteUserByUsername($username) { 105 | $userData = $this->getUserDataByUsername( 106 | \trim($username), 107 | [ 'id' ] 108 | ); 109 | 110 | $this->deleteUsersByColumnValue('id', (int) $userData['id']); 111 | } 112 | 113 | /** 114 | * Assigns the specified role to the user with the given ID 115 | * 116 | * A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) 117 | * 118 | * @param int $userId the ID of the user to assign the role to 119 | * @param int $role the role as one of the constants from the {@see Role} class 120 | * @throws UnknownIdException if no user with the specified ID has been found 121 | * 122 | * @see Role 123 | */ 124 | public function addRoleForUserById($userId, $role) { 125 | $userFound = $this->addRoleForUserByColumnValue( 126 | 'id', 127 | (int) $userId, 128 | $role 129 | ); 130 | 131 | if ($userFound === false) { 132 | throw new UnknownIdException(); 133 | } 134 | } 135 | 136 | /** 137 | * Assigns the specified role to the user with the given email address 138 | * 139 | * A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) 140 | * 141 | * @param string $userEmail the email address of the user to assign the role to 142 | * @param int $role the role as one of the constants from the {@see Role} class 143 | * @throws InvalidEmailException if no user with the specified email address has been found 144 | * 145 | * @see Role 146 | */ 147 | public function addRoleForUserByEmail($userEmail, $role) { 148 | $userEmail = self::validateEmailAddress($userEmail); 149 | 150 | $userFound = $this->addRoleForUserByColumnValue( 151 | 'email', 152 | $userEmail, 153 | $role 154 | ); 155 | 156 | if ($userFound === false) { 157 | throw new InvalidEmailException(); 158 | } 159 | } 160 | 161 | /** 162 | * Assigns the specified role to the user with the given username 163 | * 164 | * A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) 165 | * 166 | * @param string $username the username of the user to assign the role to 167 | * @param int $role the role as one of the constants from the {@see Role} class 168 | * @throws UnknownUsernameException if no user with the specified username has been found 169 | * @throws AmbiguousUsernameException if multiple users with the specified username have been found 170 | * 171 | * @see Role 172 | */ 173 | public function addRoleForUserByUsername($username, $role) { 174 | $userData = $this->getUserDataByUsername( 175 | \trim($username), 176 | [ 'id' ] 177 | ); 178 | 179 | $this->addRoleForUserByColumnValue( 180 | 'id', 181 | (int) $userData['id'], 182 | $role 183 | ); 184 | } 185 | 186 | /** 187 | * Takes away the specified role from the user with the given ID 188 | * 189 | * A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) 190 | * 191 | * @param int $userId the ID of the user to take the role away from 192 | * @param int $role the role as one of the constants from the {@see Role} class 193 | * @throws UnknownIdException if no user with the specified ID has been found 194 | * 195 | * @see Role 196 | */ 197 | public function removeRoleForUserById($userId, $role) { 198 | $userFound = $this->removeRoleForUserByColumnValue( 199 | 'id', 200 | (int) $userId, 201 | $role 202 | ); 203 | 204 | if ($userFound === false) { 205 | throw new UnknownIdException(); 206 | } 207 | } 208 | 209 | /** 210 | * Takes away the specified role from the user with the given email address 211 | * 212 | * A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) 213 | * 214 | * @param string $userEmail the email address of the user to take the role away from 215 | * @param int $role the role as one of the constants from the {@see Role} class 216 | * @throws InvalidEmailException if no user with the specified email address has been found 217 | * 218 | * @see Role 219 | */ 220 | public function removeRoleForUserByEmail($userEmail, $role) { 221 | $userEmail = self::validateEmailAddress($userEmail); 222 | 223 | $userFound = $this->removeRoleForUserByColumnValue( 224 | 'email', 225 | $userEmail, 226 | $role 227 | ); 228 | 229 | if ($userFound === false) { 230 | throw new InvalidEmailException(); 231 | } 232 | } 233 | 234 | /** 235 | * Takes away the specified role from the user with the given username 236 | * 237 | * A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) 238 | * 239 | * @param string $username the username of the user to take the role away from 240 | * @param int $role the role as one of the constants from the {@see Role} class 241 | * @throws UnknownUsernameException if no user with the specified username has been found 242 | * @throws AmbiguousUsernameException if multiple users with the specified username have been found 243 | * 244 | * @see Role 245 | */ 246 | public function removeRoleForUserByUsername($username, $role) { 247 | $userData = $this->getUserDataByUsername( 248 | \trim($username), 249 | [ 'id' ] 250 | ); 251 | 252 | $this->removeRoleForUserByColumnValue( 253 | 'id', 254 | (int) $userData['id'], 255 | $role 256 | ); 257 | } 258 | 259 | /** 260 | * Returns whether the user with the given ID has the specified role 261 | * 262 | * @param int $userId the ID of the user to check the roles for 263 | * @param int $role the role as one of the constants from the {@see Role} class 264 | * @return bool 265 | * @throws UnknownIdException if no user with the specified ID has been found 266 | * 267 | * @see Role 268 | */ 269 | public function doesUserHaveRole($userId, $role) { 270 | if (empty($role) || !\is_numeric($role)) { 271 | return false; 272 | } 273 | 274 | $userId = (int) $userId; 275 | 276 | $rolesBitmask = $this->db->selectValue( 277 | 'SELECT roles_mask FROM ' . $this->makeTableName('users') . ' WHERE id = ?', 278 | [ $userId ] 279 | ); 280 | 281 | if ($rolesBitmask === null) { 282 | throw new UnknownIdException(); 283 | } 284 | 285 | $role = (int) $role; 286 | 287 | return ($rolesBitmask & $role) === $role; 288 | } 289 | 290 | /** 291 | * Returns the roles of the user with the given ID, mapping the numerical values to their descriptive names 292 | * 293 | * @param int $userId the ID of the user to return the roles for 294 | * @return array 295 | * @throws UnknownIdException if no user with the specified ID has been found 296 | * 297 | * @see Role 298 | */ 299 | public function getRolesForUserById($userId) { 300 | $userId = (int) $userId; 301 | 302 | $rolesBitmask = $this->db->selectValue( 303 | 'SELECT roles_mask FROM ' . $this->makeTableName('users') . ' WHERE id = ?', 304 | [ $userId ] 305 | ); 306 | 307 | if ($rolesBitmask === null) { 308 | throw new UnknownIdException(); 309 | } 310 | 311 | return \array_filter( 312 | Role::getMap(), 313 | function ($each) use ($rolesBitmask) { 314 | return ($rolesBitmask & $each) === $each; 315 | }, 316 | \ARRAY_FILTER_USE_KEY 317 | ); 318 | } 319 | 320 | /** 321 | * Signs in as the user with the specified ID 322 | * 323 | * @param int $id the ID of the user to sign in as 324 | * @throws UnknownIdException if no user with the specified ID has been found 325 | * @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet 326 | * @throws AuthError if an internal problem occurred (do *not* catch) 327 | */ 328 | public function logInAsUserById($id) { 329 | $numberOfMatchedUsers = $this->logInAsUserByColumnValue('id', (int) $id); 330 | 331 | if ($numberOfMatchedUsers === 0) { 332 | throw new UnknownIdException(); 333 | } 334 | } 335 | 336 | /** 337 | * Signs in as the user with the specified email address 338 | * 339 | * @param string $email the email address of the user to sign in as 340 | * @throws InvalidEmailException if no user with the specified email address has been found 341 | * @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet 342 | * @throws AuthError if an internal problem occurred (do *not* catch) 343 | */ 344 | public function logInAsUserByEmail($email) { 345 | $email = self::validateEmailAddress($email); 346 | 347 | $numberOfMatchedUsers = $this->logInAsUserByColumnValue('email', $email); 348 | 349 | if ($numberOfMatchedUsers === 0) { 350 | throw new InvalidEmailException(); 351 | } 352 | } 353 | 354 | /** 355 | * Signs in as the user with the specified display name 356 | * 357 | * @param string $username the display name of the user to sign in as 358 | * @throws UnknownUsernameException if no user with the specified username has been found 359 | * @throws AmbiguousUsernameException if multiple users with the specified username have been found 360 | * @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet 361 | * @throws AuthError if an internal problem occurred (do *not* catch) 362 | */ 363 | public function logInAsUserByUsername($username) { 364 | $numberOfMatchedUsers = $this->logInAsUserByColumnValue('username', \trim($username)); 365 | 366 | if ($numberOfMatchedUsers === 0) { 367 | throw new UnknownUsernameException(); 368 | } 369 | elseif ($numberOfMatchedUsers > 1) { 370 | throw new AmbiguousUsernameException(); 371 | } 372 | } 373 | 374 | /** 375 | * Changes the password for the user with the given ID 376 | * 377 | * @param int $userId the ID of the user whose password to change 378 | * @param string $newPassword the new password to set 379 | * @throws UnknownIdException if no user with the specified ID has been found 380 | * @throws InvalidPasswordException if the desired new password has been invalid 381 | * @throws AuthError if an internal problem occurred (do *not* catch) 382 | */ 383 | public function changePasswordForUserById($userId, $newPassword) { 384 | $userId = (int) $userId; 385 | $newPassword = self::validatePassword($newPassword); 386 | 387 | $this->updatePasswordInternal( 388 | $userId, 389 | $newPassword 390 | ); 391 | 392 | $this->forceLogoutForUserById($userId); 393 | } 394 | 395 | /** 396 | * Changes the password for the user with the given username 397 | * 398 | * @param string $username the username of the user whose password to change 399 | * @param string $newPassword the new password to set 400 | * @throws UnknownUsernameException if no user with the specified username has been found 401 | * @throws AmbiguousUsernameException if multiple users with the specified username have been found 402 | * @throws InvalidPasswordException if the desired new password has been invalid 403 | * @throws AuthError if an internal problem occurred (do *not* catch) 404 | */ 405 | public function changePasswordForUserByUsername($username, $newPassword) { 406 | $userData = $this->getUserDataByUsername( 407 | \trim($username), 408 | [ 'id' ] 409 | ); 410 | 411 | $this->changePasswordForUserById( 412 | (int) $userData['id'], 413 | $newPassword 414 | ); 415 | } 416 | 417 | /** 418 | * Deletes all existing users where the column with the specified name has the given value 419 | * 420 | * You must never pass untrusted input to the parameter that takes the column name 421 | * 422 | * @param string $columnName the name of the column to filter by 423 | * @param mixed $columnValue the value to look for in the selected column 424 | * @return int the number of deleted users 425 | * @throws AuthError if an internal problem occurred (do *not* catch) 426 | */ 427 | private function deleteUsersByColumnValue($columnName, $columnValue) { 428 | try { 429 | return $this->db->delete( 430 | $this->makeTableNameComponents('users'), 431 | [ 432 | $columnName => $columnValue 433 | ] 434 | ); 435 | } 436 | catch (Error $e) { 437 | throw new DatabaseError($e->getMessage()); 438 | } 439 | } 440 | 441 | /** 442 | * Modifies the roles for the user where the column with the specified name has the given value 443 | * 444 | * You must never pass untrusted input to the parameter that takes the column name 445 | * 446 | * @param string $columnName the name of the column to filter by 447 | * @param mixed $columnValue the value to look for in the selected column 448 | * @param callable $modification the modification to apply to the existing bitmask of roles 449 | * @return bool whether any user with the given column constraints has been found 450 | * @throws AuthError if an internal problem occurred (do *not* catch) 451 | * 452 | * @see Role 453 | */ 454 | private function modifyRolesForUserByColumnValue($columnName, $columnValue, callable $modification) { 455 | try { 456 | $userData = $this->db->selectRow( 457 | 'SELECT id, roles_mask FROM ' . $this->makeTableName('users') . ' WHERE ' . $columnName . ' = ?', 458 | [ $columnValue ] 459 | ); 460 | } 461 | catch (Error $e) { 462 | throw new DatabaseError($e->getMessage()); 463 | } 464 | 465 | if ($userData === null) { 466 | return false; 467 | } 468 | 469 | $newRolesBitmask = $modification($userData['roles_mask']); 470 | 471 | try { 472 | $this->db->exec( 473 | 'UPDATE ' . $this->makeTableName('users') . ' SET roles_mask = ? WHERE id = ?', 474 | [ 475 | $newRolesBitmask, 476 | (int) $userData['id'] 477 | ] 478 | ); 479 | 480 | return true; 481 | } 482 | catch (Error $e) { 483 | throw new DatabaseError($e->getMessage()); 484 | } 485 | } 486 | 487 | /** 488 | * Assigns the specified role to the user where the column with the specified name has the given value 489 | * 490 | * You must never pass untrusted input to the parameter that takes the column name 491 | * 492 | * @param string $columnName the name of the column to filter by 493 | * @param mixed $columnValue the value to look for in the selected column 494 | * @param int $role the role as one of the constants from the {@see Role} class 495 | * @return bool whether any user with the given column constraints has been found 496 | * 497 | * @see Role 498 | */ 499 | private function addRoleForUserByColumnValue($columnName, $columnValue, $role) { 500 | $role = (int) $role; 501 | 502 | return $this->modifyRolesForUserByColumnValue( 503 | $columnName, 504 | $columnValue, 505 | function ($oldRolesBitmask) use ($role) { 506 | return $oldRolesBitmask | $role; 507 | } 508 | ); 509 | } 510 | 511 | /** 512 | * Takes away the specified role from the user where the column with the specified name has the given value 513 | * 514 | * You must never pass untrusted input to the parameter that takes the column name 515 | * 516 | * @param string $columnName the name of the column to filter by 517 | * @param mixed $columnValue the value to look for in the selected column 518 | * @param int $role the role as one of the constants from the {@see Role} class 519 | * @return bool whether any user with the given column constraints has been found 520 | * 521 | * @see Role 522 | */ 523 | private function removeRoleForUserByColumnValue($columnName, $columnValue, $role) { 524 | $role = (int) $role; 525 | 526 | return $this->modifyRolesForUserByColumnValue( 527 | $columnName, 528 | $columnValue, 529 | function ($oldRolesBitmask) use ($role) { 530 | return $oldRolesBitmask & ~$role; 531 | } 532 | ); 533 | } 534 | 535 | /** 536 | * Signs in as the user for which the column with the specified name has the given value 537 | * 538 | * You must never pass untrusted input to the parameter that takes the column name 539 | * 540 | * @param string $columnName the name of the column to filter by 541 | * @param mixed $columnValue the value to look for in the selected column 542 | * @return int the number of matched users (where only a value of one means that the login may have been successful) 543 | * @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet 544 | * @throws AuthError if an internal problem occurred (do *not* catch) 545 | */ 546 | private function logInAsUserByColumnValue($columnName, $columnValue) { 547 | try { 548 | $users = $this->db->select( 549 | 'SELECT verified, id, email, username, status, roles_mask FROM ' . $this->makeTableName('users') . ' WHERE ' . $columnName . ' = ? LIMIT 2 OFFSET 0', 550 | [ $columnValue ] 551 | ); 552 | } 553 | catch (Error $e) { 554 | throw new DatabaseError($e->getMessage()); 555 | } 556 | 557 | $numberOfMatchingUsers = ($users !== null) ? \count($users) : 0; 558 | 559 | if ($numberOfMatchingUsers === 1) { 560 | $user = $users[0]; 561 | 562 | if ((int) $user['verified'] === 1) { 563 | $this->onLoginSuccessful($user['id'], $user['email'], $user['username'], $user['status'], $user['roles_mask'], \PHP_INT_MAX, false); 564 | } 565 | else { 566 | throw new EmailNotVerifiedException(); 567 | } 568 | } 569 | 570 | return $numberOfMatchingUsers; 571 | } 572 | 573 | } 574 | 575 | ?> -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Installation 2 | ``` 3 | composer require devinow/auth 4 | ``` 5 | 6 | Set up a database and create the required tables: 7 | 8 | * [MariaDB](Database/MySQL.sql) 9 | * [MySQL](Database/MySQL.sql) 10 | * [PostgreSQL](Database/PostgreSQL.sql) 11 | * [SQLite](Database/SQLite.sql) 12 | 13 | ## Usage 14 | 15 | * [Creating a new instance](#creating-a-new-instance) 16 | * [Registration (sign up)](#registration-sign-up) 17 | * [Login (sign in)](#login-sign-in) 18 | * [Email verification](#email-verification) 19 | * [Keeping the user logged in](#keeping-the-user-logged-in) 20 | * [Password reset (“forgot password”)](#password-reset-forgot-password) 21 | * [Initiating the request](#step-1-of-3-initiating-the-request) 22 | * [Verifying an attempt](#step-2-of-3-verifying-an-attempt) 23 | * [Updating the password](#step-3-of-3-updating-the-password) 24 | * [Changing the current user’s password](#changing-the-current-users-password) 25 | * [Changing the current user’s email address](#changing-the-current-users-email-address) 26 | * [Re-sending confirmation requests](#re-sending-confirmation-requests) 27 | * [Logout](#logout) 28 | * [Accessing user information](#accessing-user-information) 29 | * [Login state](#login-state) 30 | * [User ID](#user-id) 31 | * [Email address](#email-address) 32 | * [Display name](#display-name) 33 | * [Status information](#status-information) 34 | * [Checking whether the user was “remembered”](#checking-whether-the-user-was-remembered) 35 | * [IP address](#ip-address) 36 | * [Additional user information](#additional-user-information) 37 | * [Reconfirming the user’s password](#reconfirming-the-users-password) 38 | * [Roles (or groups)](#roles-or-groups) 39 | * [Checking roles](#checking-roles) 40 | * [Available roles](#available-roles) 41 | * [Permissions (or access rights, privileges or capabilities)](#permissions-or-access-rights-privileges-or-capabilities) 42 | * [Custom role names](#custom-role-names) 43 | * [Enabling or disabling password resets](#enabling-or-disabling-password-resets) 44 | * [Throttling or rate limiting](#throttling-or-rate-limiting) 45 | * [Administration (managing users)](#administration-managing-users) 46 | * [Creating new users](#creating-new-users) 47 | * [Deleting users](#deleting-users) 48 | * [Assigning roles to users](#assigning-roles-to-users) 49 | * [Taking roles away from users](#taking-roles-away-from-users) 50 | * [Checking roles](#checking-roles-1) 51 | * [Impersonating users (logging in as user)](#impersonating-users-logging-in-as-user) 52 | * [Changing a user’s password](#changing-a-users-password) 53 | * [Cookies](#cookies) 54 | * [Renaming the library’s cookies](#renaming-the-librarys-cookies) 55 | * [Defining the domain scope for cookies](#defining-the-domain-scope-for-cookies) 56 | * [Restricting the path where cookies are available](#restricting-the-path-where-cookies-are-available) 57 | * [Controlling client-side script access to cookies](#controlling-client-side-script-access-to-cookies) 58 | * [Configuring transport security for cookies](#configuring-transport-security-for-cookies) 59 | * [Utilities](#utilities) 60 | * [Creating a random string](#creating-a-random-string) 61 | * [Creating a UUID v4 as per RFC 4122](#creating-a-uuid-v4-as-per-rfc-4122) 62 | * [Reading and writing session data](#reading-and-writing-session-data) 63 | 64 | ### Creating a new instance 65 | 66 | ```php 67 | // $db = new \PDO('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password'); 68 | // or 69 | // $db = new \PDO('pgsql:dbname=my-database;host=localhost;port=5432', 'my-username', 'my-password'); 70 | // or 71 | // $db = new \PDO('sqlite:../Databases/my-database.sqlite'); 72 | 73 | // or 74 | 75 | // $db = \Devinow\Db\PdoDatabase::fromDsn(new \Devinow\Db\PdoDsn('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password')); 76 | // or 77 | // $db = \Devinow\Db\PdoDatabase::fromDsn(new \Devinow\Db\PdoDsn('pgsql:dbname=my-database;host=localhost;port=5432', 'my-username', 'my-password')); 78 | // or 79 | // $db = \Devinow\Db\PdoDatabase::fromDsn(new \Devinow\Db\PdoDsn('sqlite:../Databases/my-database.sqlite')); 80 | 81 | $auth = new \Devinow\Auth\Auth($db); 82 | ``` 83 | 84 | 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). 85 | 86 | If your web server is behind a proxy server and `$_SERVER['REMOTE_ADDR']` only contains the proxy’s IP address, you must pass the user’s real IP address to the constructor in the second argument, which is named `$ipAddress`. The default is the usual remote IP address received by PHP. 87 | 88 | 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 the third parameter to the constructor, which is named `$dbTablePrefix`. This is optional and the prefix is empty by default. 89 | 90 | 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 fourth argument, which is named `$throttling`. The feature is enabled by default. 91 | 92 | 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 fifth argument, which is named `$sessionResyncInterval`. 93 | 94 | If all your database tables need a common database name, schema name, or other qualifier that must be specified explicitly, you can optionally pass that qualifier to the constructor as the sixth parameter, which is named `$dbSchema`. 95 | 96 | 97 | ### Registration (sign up) 98 | 99 | ```php 100 | try { 101 | $userId = $auth->register($_POST['email'], $_POST['password'], $_POST['username'], function ($selector, $token) { 102 | echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)'; 103 | echo ' For emails, consider using the mail(...) function, Symfony Mailer, Swiftmailer, PHPMailer, etc.'; 104 | echo ' For SMS, consider using a third-party service and a compatible SDK'; 105 | }); 106 | 107 | echo 'We have signed up a new user with the ID ' . $userId; 108 | } 109 | catch (\Devinow\Auth\InvalidEmailException $e) { 110 | die('Invalid email address'); 111 | } 112 | catch (\Devinow\Auth\InvalidPasswordException $e) { 113 | die('Invalid password'); 114 | } 115 | catch (\Devinow\Auth\UserAlreadyExistsException $e) { 116 | die('User already exists'); 117 | } 118 | catch (\Devinow\Auth\TooManyRequestsException $e) { 119 | die('Too many requests'); 120 | } 121 | ``` 122 | 123 | **Note:** The anonymous callback function is a [closure](https://www.php.net/manual/functions.anonymous.php). Thus, besides its own parameters, only [superglobals](https://www.php.net/manual/language.variables.superglobals.php) like `$_GET`, `$_POST`, `$_COOKIE` and `$_SERVER` are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a `use` clause after the parameter list. 124 | 125 | The username in the third parameter is optional. You can pass `null` there if you don’t want to manage usernames. 126 | 127 | If you want to enforce unique usernames, on the other hand, simply call `registerWithUniqueUsername` instead of `register`, and be prepared to catch the `DuplicateUsernameException`. 128 | 129 | **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: 130 | 131 | ```php 132 | if (\preg_match('/[\x00-\x1f\x7f\/:\\\\]/', $username) === 0) { 133 | // ... 134 | } 135 | ``` 136 | 137 | For email verification, you should build an URL with the selector and token and send it to the user, e.g.: 138 | 139 | ```php 140 | $url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector) . '&token=' . \urlencode($token); 141 | ``` 142 | 143 | If you don’t want to perform email verification, just omit the last parameter to `Auth#register`, i.e. the [anonymous function or closure](https://www.php.net/manual/functions.anonymous.php). The new user will be active immediately, then. 144 | 145 | Need to store additional user information? Read on [here](#additional-user-information). 146 | 147 | **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. 148 | 149 | ### Login (sign in) 150 | 151 | ```php 152 | try { 153 | $auth->login($_POST['email'], $_POST['password']); 154 | 155 | echo 'User is logged in'; 156 | } 157 | catch (\Devinow\Auth\InvalidEmailException $e) { 158 | die('Wrong email address'); 159 | } 160 | catch (\Devinow\Auth\InvalidPasswordException $e) { 161 | die('Wrong password'); 162 | } 163 | catch (\Devinow\Auth\EmailNotVerifiedException $e) { 164 | die('Email not verified'); 165 | } 166 | catch (\Devinow\Auth\TooManyRequestsException $e) { 167 | die('Too many requests'); 168 | } 169 | ``` 170 | 171 | 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). 172 | 173 | ### Email verification 174 | 175 | Extract the selector and token from the URL that the user clicked on in the verification email. 176 | 177 | ```php 178 | try { 179 | $auth->confirmEmail($_GET['selector'], $_GET['token']); 180 | 181 | echo 'Email address has been verified'; 182 | } 183 | catch (\Devinow\Auth\InvalidSelectorTokenPairException $e) { 184 | die('Invalid token'); 185 | } 186 | catch (\Devinow\Auth\TokenExpiredException $e) { 187 | die('Token expired'); 188 | } 189 | catch (\Devinow\Auth\UserAlreadyExistsException $e) { 190 | die('Email address already exists'); 191 | } 192 | catch (\Devinow\Auth\TooManyRequestsException $e) { 193 | die('Too many requests'); 194 | } 195 | ``` 196 | 197 | 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. 198 | 199 | 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. 200 | 201 | ### Keeping the user logged in 202 | 203 | The third parameter to the `Auth#login` and `Auth#confirmEmailAndSignIn` methods controls whether the login is persistent with a long-lived cookie. With such a persistent login, users may stay authenticated for a long time, even when the browser session has already been closed and the session cookies have expired. Typically, you’ll want to keep the user logged in for weeks or months with this feature, which is known as “remember me” or “keep me logged in”. Many users will find this more convenient, but it may be less secure if they leave their devices unattended. 204 | 205 | ```php 206 | if ($_POST['remember'] == 1) { 207 | // keep logged in for one year 208 | $rememberDuration = (int) (60 * 60 * 24 * 365.25); 209 | } 210 | else { 211 | // do not keep logged in after session ends 212 | $rememberDuration = null; 213 | } 214 | 215 | // ... 216 | 217 | $auth->login($_POST['email'], $_POST['password'], $rememberDuration); 218 | 219 | // ... 220 | ``` 221 | 222 | *Without* the persistent login, which is the *default* behavior, a user will only stay logged in until they close their browser, or as long as configured via `session.cookie_lifetime` and `session.gc_maxlifetime` in PHP. 223 | 224 | Omit the third parameter or set it to `null` to disable the feature. Otherwise, you may ask the user whether they want to enable “remember me”. This is usually done with a checkbox in your user interface. Use the input from that checkbox to decide between `null` and a pre-defined duration in seconds here, e.g. `60 * 60 * 24 * 365.25` for one year. 225 | 226 | ### Password reset (“forgot password”) 227 | 228 | #### Step 1 of 3: Initiating the request 229 | 230 | ```php 231 | try { 232 | $auth->forgotPassword($_POST['email'], function ($selector, $token) { 233 | echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)'; 234 | echo ' For emails, consider using the mail(...) function, Symfony Mailer, Swiftmailer, PHPMailer, etc.'; 235 | echo ' For SMS, consider using a third-party service and a compatible SDK'; 236 | }); 237 | 238 | echo 'Request has been generated'; 239 | } 240 | catch (\Devinow\Auth\InvalidEmailException $e) { 241 | die('Invalid email address'); 242 | } 243 | catch (\Devinow\Auth\EmailNotVerifiedException $e) { 244 | die('Email not verified'); 245 | } 246 | catch (\Devinow\Auth\ResetDisabledException $e) { 247 | die('Password reset is disabled'); 248 | } 249 | catch (\Devinow\Auth\TooManyRequestsException $e) { 250 | die('Too many requests'); 251 | } 252 | ``` 253 | 254 | **Note:** The anonymous callback function is a [closure](https://www.php.net/manual/functions.anonymous.php). Thus, besides its own parameters, only [superglobals](https://www.php.net/manual/language.variables.superglobals.php) like `$_GET`, `$_POST`, `$_COOKIE` and `$_SERVER` are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a `use` clause after the parameter list. 255 | 256 | You should build an URL with the selector and token and send it to the user, e.g.: 257 | 258 | ```php 259 | $url = 'https://www.example.com/reset_password?selector=' . \urlencode($selector) . '&token=' . \urlencode($token); 260 | ``` 261 | 262 | 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. 263 | 264 | #### Step 2 of 3: Verifying an attempt 265 | 266 | As the next step, users will click on the link that they received. Extract the selector and token from the URL. 267 | 268 | If the selector/token pair is valid, let the user choose a new password: 269 | 270 | ```php 271 | try { 272 | $auth->canResetPasswordOrThrow($_GET['selector'], $_GET['token']); 273 | 274 | echo 'Put the selector into a "hidden" field (or keep it in the URL)'; 275 | echo 'Put the token into a "hidden" field (or keep it in the URL)'; 276 | 277 | echo 'Ask the user for their new password'; 278 | } 279 | catch (\Devinow\Auth\InvalidSelectorTokenPairException $e) { 280 | die('Invalid token'); 281 | } 282 | catch (\Devinow\Auth\TokenExpiredException $e) { 283 | die('Token expired'); 284 | } 285 | catch (\Devinow\Auth\ResetDisabledException $e) { 286 | die('Password reset is disabled'); 287 | } 288 | catch (\Devinow\Auth\TooManyRequestsException $e) { 289 | die('Too many requests'); 290 | } 291 | ``` 292 | 293 | Alternatively, if you don’t need any error messages but only want to check the validity, you can use the slightly simpler version: 294 | 295 | ```php 296 | if ($auth->canResetPassword($_GET['selector'], $_GET['token'])) { 297 | echo 'Put the selector into a "hidden" field (or keep it in the URL)'; 298 | echo 'Put the token into a "hidden" field (or keep it in the URL)'; 299 | 300 | echo 'Ask the user for their new password'; 301 | } 302 | ``` 303 | 304 | #### Step 3 of 3: Updating the password 305 | 306 | Now when you have the new password for the user (and still have the other two pieces of information), you can reset the password: 307 | 308 | ```php 309 | try { 310 | $auth->resetPassword($_POST['selector'], $_POST['token'], $_POST['password']); 311 | 312 | echo 'Password has been reset'; 313 | } 314 | catch (\Devinow\Auth\InvalidSelectorTokenPairException $e) { 315 | die('Invalid token'); 316 | } 317 | catch (\Devinow\Auth\TokenExpiredException $e) { 318 | die('Token expired'); 319 | } 320 | catch (\Devinow\Auth\ResetDisabledException $e) { 321 | die('Password reset is disabled'); 322 | } 323 | catch (\Devinow\Auth\InvalidPasswordException $e) { 324 | die('Invalid password'); 325 | } 326 | catch (\Devinow\Auth\TooManyRequestsException $e) { 327 | die('Too many requests'); 328 | } 329 | ``` 330 | 331 | 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. 332 | 333 | 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`. 334 | 335 | ### Changing the current user’s password 336 | 337 | If a user is currently logged in, they may change their password. 338 | 339 | ```php 340 | try { 341 | $auth->changePassword($_POST['oldPassword'], $_POST['newPassword']); 342 | 343 | echo 'Password has been changed'; 344 | } 345 | catch (\Devinow\Auth\NotLoggedInException $e) { 346 | die('Not logged in'); 347 | } 348 | catch (\Devinow\Auth\InvalidPasswordException $e) { 349 | die('Invalid password(s)'); 350 | } 351 | catch (\Devinow\Auth\TooManyRequestsException $e) { 352 | die('Too many requests'); 353 | } 354 | ``` 355 | 356 | 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. 357 | 358 | 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). 359 | 360 | 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. 361 | 362 | ### Changing the current user’s email address 363 | 364 | If a user is currently logged in, they may change their email address. 365 | 366 | ```php 367 | try { 368 | if ($auth->reconfirmPassword($_POST['password'])) { 369 | $auth->changeEmail($_POST['newEmail'], function ($selector, $token) { 370 | echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email to the *new* address)'; 371 | echo ' For emails, consider using the mail(...) function, Symfony Mailer, Swiftmailer, PHPMailer, etc.'; 372 | echo ' For SMS, consider using a third-party service and a compatible SDK'; 373 | }); 374 | 375 | echo 'The change will take effect as soon as the new email address has been confirmed'; 376 | } 377 | else { 378 | echo 'We can\'t say if the user is who they claim to be'; 379 | } 380 | } 381 | catch (\Devinow\Auth\InvalidEmailException $e) { 382 | die('Invalid email address'); 383 | } 384 | catch (\Devinow\Auth\UserAlreadyExistsException $e) { 385 | die('Email address already exists'); 386 | } 387 | catch (\Devinow\Auth\EmailNotVerifiedException $e) { 388 | die('Account not verified'); 389 | } 390 | catch (\Devinow\Auth\NotLoggedInException $e) { 391 | die('Not logged in'); 392 | } 393 | catch (\Devinow\Auth\TooManyRequestsException $e) { 394 | die('Too many requests'); 395 | } 396 | ``` 397 | 398 | **Note:** The anonymous callback function is a [closure](https://www.php.net/manual/functions.anonymous.php). Thus, besides its own parameters, only [superglobals](https://www.php.net/manual/language.variables.superglobals.php) like `$_GET`, `$_POST`, `$_COOKIE` and `$_SERVER` are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a `use` clause after the parameter list. 399 | 400 | For email verification, you should build an URL with the selector and token and send it to the user, e.g.: 401 | 402 | ```php 403 | $url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector) . '&token=' . \urlencode($token); 404 | ``` 405 | 406 | **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. 407 | 408 | 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. 409 | 410 | **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`. 411 | 412 | ### Re-sending confirmation requests 413 | 414 | 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: 415 | 416 | ```php 417 | try { 418 | $auth->resendConfirmationForEmail($_POST['email'], function ($selector, $token) { 419 | echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)'; 420 | echo ' For emails, consider using the mail(...) function, Symfony Mailer, Swiftmailer, PHPMailer, etc.'; 421 | echo ' For SMS, consider using a third-party service and a compatible SDK'; 422 | }); 423 | 424 | echo 'The user may now respond to the confirmation request (usually by clicking a link)'; 425 | } 426 | catch (\Devinow\Auth\ConfirmationRequestNotFound $e) { 427 | die('No earlier request found that could be re-sent'); 428 | } 429 | catch (\Devinow\Auth\TooManyRequestsException $e) { 430 | die('There have been too many requests -- try again later'); 431 | } 432 | ``` 433 | 434 | If you want to specify the user by their ID instead of by their email address, this is possible as well: 435 | 436 | ```php 437 | try { 438 | $auth->resendConfirmationForUserId($_POST['userId'], function ($selector, $token) { 439 | echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)'; 440 | echo ' For emails, consider using the mail(...) function, Symfony Mailer, Swiftmailer, PHPMailer, etc.'; 441 | echo ' For SMS, consider using a third-party service and a compatible SDK'; 442 | }); 443 | 444 | echo 'The user may now respond to the confirmation request (usually by clicking a link)'; 445 | } 446 | catch (\Devinow\Auth\ConfirmationRequestNotFound $e) { 447 | die('No earlier request found that could be re-sent'); 448 | } 449 | catch (\Devinow\Auth\TooManyRequestsException $e) { 450 | die('There have been too many requests -- try again later'); 451 | } 452 | ``` 453 | 454 | **Note:** The anonymous callback function is a [closure](https://www.php.net/manual/functions.anonymous.php). Thus, besides its own parameters, only [superglobals](https://www.php.net/manual/language.variables.superglobals.php) like `$_GET`, `$_POST`, `$_COOKIE` and `$_SERVER` are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a `use` clause after the parameter list. 455 | 456 | Usually, you should build an URL with the selector and token and send it to the user, e.g. as follows: 457 | 458 | ```php 459 | $url = 'https://www.example.com/verify_email?selector=' . \urlencode($selector) . '&token=' . \urlencode($token); 460 | ``` 461 | 462 | **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. 463 | 464 | ### Logout 465 | 466 | ```php 467 | $auth->logOut(); 468 | 469 | // or 470 | 471 | try { 472 | $auth->logOutEverywhereElse(); 473 | } 474 | catch (\Devinow\Auth\NotLoggedInException $e) { 475 | die('Not logged in'); 476 | } 477 | 478 | // or 479 | 480 | try { 481 | $auth->logOutEverywhere(); 482 | } 483 | catch (\Devinow\Auth\NotLoggedInException $e) { 484 | die('Not logged in'); 485 | } 486 | ``` 487 | 488 | 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: 489 | 490 | ```php 491 | $auth->destroySession(); 492 | ``` 493 | 494 | **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`. 495 | 496 | ### Accessing user information 497 | 498 | #### Login state 499 | 500 | ```php 501 | if ($auth->isLoggedIn()) { 502 | echo 'User is signed in'; 503 | } 504 | else { 505 | echo 'User is not signed in yet'; 506 | } 507 | ``` 508 | 509 | A shorthand/alias for this method is `$auth->check()`. 510 | 511 | #### User ID 512 | 513 | ```php 514 | $id = $auth->getUserId(); 515 | ``` 516 | 517 | If the user is not currently signed in, this returns `null`. 518 | 519 | A shorthand/alias for this method is `$auth->id()`. 520 | 521 | #### Email address 522 | 523 | ```php 524 | $email = $auth->getEmail(); 525 | ``` 526 | 527 | If the user is not currently signed in, this returns `null`. 528 | 529 | #### Display name 530 | 531 | ```php 532 | $username = $auth->getUsername(); 533 | ``` 534 | 535 | Remember that usernames are optional and there is only a username if you supplied it during registration. 536 | 537 | If the user is not currently signed in, this returns `null`. 538 | 539 | #### Status information 540 | 541 | ```php 542 | if ($auth->isNormal()) { 543 | echo 'User is in default state'; 544 | } 545 | 546 | if ($auth->isArchived()) { 547 | echo 'User has been archived'; 548 | } 549 | 550 | if ($auth->isBanned()) { 551 | echo 'User has been banned'; 552 | } 553 | 554 | if ($auth->isLocked()) { 555 | echo 'User has been locked'; 556 | } 557 | 558 | if ($auth->isPendingReview()) { 559 | echo 'User is pending review'; 560 | } 561 | 562 | if ($auth->isSuspended()) { 563 | echo 'User has been suspended'; 564 | } 565 | ``` 566 | 567 | #### Checking whether the user was “remembered” 568 | 569 | ```php 570 | if ($auth->isRemembered()) { 571 | echo 'User did not sign in but was logged in through their long-lived cookie'; 572 | } 573 | else { 574 | echo 'User signed in manually'; 575 | } 576 | ``` 577 | 578 | If the user is not currently signed in, this returns `null`. 579 | 580 | #### IP address 581 | 582 | ```php 583 | $ip = $auth->getIpAddress(); 584 | ``` 585 | 586 | #### Additional user information 587 | 588 | 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: 589 | 590 | Here’s how to use this library with your own tables for custom user information in a maintainable and re-usable way: 591 | 592 | 1. Add any number of custom database tables where you store custom user information, e.g. a table named `profiles`. 593 | 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. 594 | 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: 595 | 596 | ```php 597 | function getUserInfo(\Devinow\Auth\Auth $auth) { 598 | if (!$auth->isLoggedIn()) { 599 | return null; 600 | } 601 | 602 | if (!isset($_SESSION['_internal_user_info'])) { 603 | // TODO: load your custom user information and assign it to the session variable below 604 | // $_SESSION['_internal_user_info'] = ... 605 | } 606 | 607 | return $_SESSION['_internal_user_info']; 608 | } 609 | ``` 610 | 611 | ### Reconfirming the user’s password 612 | 613 | 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. 614 | 615 | 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. 616 | 617 | ```php 618 | try { 619 | if ($auth->reconfirmPassword($_POST['password'])) { 620 | echo 'The user really seems to be who they claim to be'; 621 | } 622 | else { 623 | echo 'We can\'t say if the user is who they claim to be'; 624 | } 625 | } 626 | catch (\Devinow\Auth\NotLoggedInException $e) { 627 | die('The user is not signed in'); 628 | } 629 | catch (\Devinow\Auth\TooManyRequestsException $e) { 630 | die('Too many requests'); 631 | } 632 | ``` 633 | 634 | ### Roles (or groups) 635 | 636 | Every user can have any number of roles, which you can use to implement authorization and to refine your access controls. 637 | 638 | Users may have no role at all (which they do by default), exactly one role, or any arbitrary combination of roles. 639 | 640 | #### Checking roles 641 | 642 | ```php 643 | if ($auth->hasRole(\Devinow\Auth\Role::SUPER_MODERATOR)) { 644 | echo 'The user is a super moderator'; 645 | } 646 | 647 | // or 648 | 649 | if ($auth->hasAnyRole(\Devinow\Auth\Role::DEVELOPER, \Devinow\Auth\Role::MANAGER)) { 650 | echo 'The user is either a developer, or a manager, or both'; 651 | } 652 | 653 | // or 654 | 655 | if ($auth->hasAllRoles(\Devinow\Auth\Role::DEVELOPER, \Devinow\Auth\Role::MANAGER)) { 656 | echo 'The user is both a developer and a manager'; 657 | } 658 | ``` 659 | 660 | 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. 661 | 662 | Alternatively, you can get a list of all the roles that have been assigned to the user: 663 | 664 | ```php 665 | $auth->getRoles(); 666 | ``` 667 | 668 | #### Available roles 669 | 670 | ```php 671 | \Devinow\Auth\Role::ADMIN; 672 | \Devinow\Auth\Role::AUTHOR; 673 | \Devinow\Auth\Role::COLLABORATOR; 674 | \Devinow\Auth\Role::CONSULTANT; 675 | \Devinow\Auth\Role::CONSUMER; 676 | \Devinow\Auth\Role::CONTRIBUTOR; 677 | \Devinow\Auth\Role::COORDINATOR; 678 | \Devinow\Auth\Role::CREATOR; 679 | \Devinow\Auth\Role::DEVELOPER; 680 | \Devinow\Auth\Role::DIRECTOR; 681 | \Devinow\Auth\Role::EDITOR; 682 | \Devinow\Auth\Role::EMPLOYEE; 683 | \Devinow\Auth\Role::MAINTAINER; 684 | \Devinow\Auth\Role::MANAGER; 685 | \Devinow\Auth\Role::MODERATOR; 686 | \Devinow\Auth\Role::PUBLISHER; 687 | \Devinow\Auth\Role::REVIEWER; 688 | \Devinow\Auth\Role::SUBSCRIBER; 689 | \Devinow\Auth\Role::SUPER_ADMIN; 690 | \Devinow\Auth\Role::SUPER_EDITOR; 691 | \Devinow\Auth\Role::SUPER_MODERATOR; 692 | \Devinow\Auth\Role::TRANSLATOR; 693 | ``` 694 | 695 | 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: 696 | 697 | ```php 698 | \Devinow\Auth\Role::getMap(); 699 | // or 700 | \Devinow\Auth\Role::getNames(); 701 | // or 702 | \Devinow\Auth\Role::getValues(); 703 | ``` 704 | 705 | #### Permissions (or access rights, privileges or capabilities) 706 | 707 | 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. 708 | 709 | 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: 710 | 711 | ```php 712 | function canEditArticle(\Devinow\Auth\Auth $auth) { 713 | return $auth->hasAnyRole( 714 | \Devinow\Auth\Role::MODERATOR, 715 | \Devinow\Auth\Role::SUPER_MODERATOR, 716 | \Devinow\Auth\Role::ADMIN, 717 | \Devinow\Auth\Role::SUPER_ADMIN 718 | ); 719 | } 720 | 721 | // ... 722 | 723 | if (canEditArticle($auth)) { 724 | echo 'The user can edit articles here'; 725 | } 726 | 727 | // ... 728 | 729 | if (canEditArticle($auth)) { 730 | echo '... and here'; 731 | } 732 | 733 | // ... 734 | 735 | if (canEditArticle($auth)) { 736 | echo '... and here'; 737 | } 738 | ``` 739 | 740 | 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: 741 | 742 | 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. 743 | 744 | 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. 745 | 746 | #### Custom role names 747 | 748 | 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: 749 | 750 | ```php 751 | namespace My\Namespace; 752 | 753 | final class MyRole { 754 | 755 | const CUSTOMER_SERVICE_AGENT = \Devinow\Auth\Role::REVIEWER; 756 | const FINANCIAL_DIRECTOR = \Devinow\Auth\Role::COORDINATOR; 757 | 758 | private function __construct() {} 759 | 760 | } 761 | ``` 762 | 763 | The example above would allow you to use 764 | 765 | ```php 766 | \My\Namespace\MyRole::CUSTOMER_SERVICE_AGENT; 767 | // and 768 | \My\Namespace\MyRole::FINANCIAL_DIRECTOR; 769 | ``` 770 | 771 | instead of 772 | 773 | ```php 774 | \Devinow\Auth\Role::REVIEWER; 775 | // and 776 | \Devinow\Auth\Role::COORDINATOR; 777 | ``` 778 | 779 | Just remember *not* to alias a *single* included role to *multiple* roles with custom names. 780 | 781 | ### Enabling or disabling password resets 782 | 783 | 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. 784 | 785 | 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: 786 | 787 | ```php 788 | try { 789 | if ($auth->reconfirmPassword($_POST['password'])) { 790 | $auth->setPasswordResetEnabled($_POST['enabled'] == 1); 791 | 792 | echo 'The setting has been changed'; 793 | } 794 | else { 795 | echo 'We can\'t say if the user is who they claim to be'; 796 | } 797 | } 798 | catch (\Devinow\Auth\NotLoggedInException $e) { 799 | die('The user is not signed in'); 800 | } 801 | catch (\Devinow\Auth\TooManyRequestsException $e) { 802 | die('Too many requests'); 803 | } 804 | ``` 805 | 806 | In order to check the current value of this setting, use the return value from 807 | 808 | ```php 809 | $auth->isPasswordResetEnabled(); 810 | ``` 811 | 812 | 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. 813 | 814 | ### Throttling or rate limiting 815 | 816 | All methods provided by this library are *automatically* protected against excessive numbers of requests from clients. If the need arises, you can (temporarily) disable this protection using the [`$throttling` parameter](#creating-a-new-instance) passed to the constructor. 817 | 818 | 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: 819 | 820 | ```php 821 | try { 822 | // throttle the specified resource or feature to *3* requests per *60* seconds 823 | $auth->throttle([ 'my-resource-name' ], 3, 60); 824 | 825 | echo 'Do something with the resource or feature'; 826 | } 827 | catch (\Devinow\Auth\TooManyRequestsException $e) { 828 | // operation cancelled 829 | 830 | \http_response_code(429); 831 | exit; 832 | } 833 | ``` 834 | 835 | 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: 836 | 837 | ```php 838 | [ 'my-resource-name', $_SERVER['REMOTE_ADDR'] ] 839 | // instead of 840 | // [ 'my-resource-name' ] 841 | ``` 842 | 843 | 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. 844 | 845 | 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. 846 | 847 | **Note:** When you disable throttling on the instance (using the [`$throttling` parameter](#creating-a-new-instance) passed to the constructor), this turns off both the automatic internal protection and the effect of any calls to `Auth#throttle` in your own application code – unless you also set the optional `$force` parameter to `true` in specific `Auth#throttle` calls. 848 | 849 | ### Administration (managing users) 850 | 851 | The administrative interface is available via `$auth->admin()`. You can call various method on this interface, as documented below. 852 | 853 | 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. 854 | 855 | #### Creating new users 856 | 857 | ```php 858 | try { 859 | $userId = $auth->admin()->createUser($_POST['email'], $_POST['password'], $_POST['username']); 860 | 861 | echo 'We have signed up a new user with the ID ' . $userId; 862 | } 863 | catch (\Devinow\Auth\InvalidEmailException $e) { 864 | die('Invalid email address'); 865 | } 866 | catch (\Devinow\Auth\InvalidPasswordException $e) { 867 | die('Invalid password'); 868 | } 869 | catch (\Devinow\Auth\UserAlreadyExistsException $e) { 870 | die('User already exists'); 871 | } 872 | ``` 873 | 874 | The username in the third parameter is optional. You can pass `null` there if you don’t want to manage usernames. 875 | 876 | If you want to enforce unique usernames, on the other hand, simply call `createUserWithUniqueUsername` instead of `createUser`, and be prepared to catch the `DuplicateUsernameException`. 877 | 878 | #### Deleting users 879 | 880 | Deleting users by their ID: 881 | 882 | ```php 883 | try { 884 | $auth->admin()->deleteUserById($_POST['id']); 885 | } 886 | catch (\Devinow\Auth\UnknownIdException $e) { 887 | die('Unknown ID'); 888 | } 889 | ``` 890 | 891 | Deleting users by their email address: 892 | 893 | ```php 894 | try { 895 | $auth->admin()->deleteUserByEmail($_POST['email']); 896 | } 897 | catch (\Devinow\Auth\InvalidEmailException $e) { 898 | die('Unknown email address'); 899 | } 900 | ``` 901 | 902 | Deleting users by their username: 903 | 904 | ```php 905 | try { 906 | $auth->admin()->deleteUserByUsername($_POST['username']); 907 | } 908 | catch (\Devinow\Auth\UnknownUsernameException $e) { 909 | die('Unknown username'); 910 | } 911 | catch (\Devinow\Auth\AmbiguousUsernameException $e) { 912 | die('Ambiguous username'); 913 | } 914 | ``` 915 | 916 | #### Retrieving a list of registered users 917 | 918 | 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). 919 | 920 | That’s why it’s easier to use a single custom SQL query. Start with the following: 921 | 922 | ```sql 923 | SELECT id, email, username, status, verified, roles_mask, registered, last_login FROM users; 924 | ``` 925 | 926 | #### Assigning roles to users 927 | 928 | ```php 929 | try { 930 | $auth->admin()->addRoleForUserById($userId, \Devinow\Auth\Role::ADMIN); 931 | } 932 | catch (\Devinow\Auth\UnknownIdException $e) { 933 | die('Unknown user ID'); 934 | } 935 | 936 | // or 937 | 938 | try { 939 | $auth->admin()->addRoleForUserByEmail($userEmail, \Devinow\Auth\Role::ADMIN); 940 | } 941 | catch (\Devinow\Auth\InvalidEmailException $e) { 942 | die('Unknown email address'); 943 | } 944 | 945 | // or 946 | 947 | try { 948 | $auth->admin()->addRoleForUserByUsername($username, \Devinow\Auth\Role::ADMIN); 949 | } 950 | catch (\Devinow\Auth\UnknownUsernameException $e) { 951 | die('Unknown username'); 952 | } 953 | catch (\Devinow\Auth\AmbiguousUsernameException $e) { 954 | die('Ambiguous username'); 955 | } 956 | ``` 957 | 958 | **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`. 959 | 960 | #### Taking roles away from users 961 | 962 | ```php 963 | try { 964 | $auth->admin()->removeRoleForUserById($userId, \Devinow\Auth\Role::ADMIN); 965 | } 966 | catch (\Devinow\Auth\UnknownIdException $e) { 967 | die('Unknown user ID'); 968 | } 969 | 970 | // or 971 | 972 | try { 973 | $auth->admin()->removeRoleForUserByEmail($userEmail, \Devinow\Auth\Role::ADMIN); 974 | } 975 | catch (\Devinow\Auth\InvalidEmailException $e) { 976 | die('Unknown email address'); 977 | } 978 | 979 | // or 980 | 981 | try { 982 | $auth->admin()->removeRoleForUserByUsername($username, \Devinow\Auth\Role::ADMIN); 983 | } 984 | catch (\Devinow\Auth\UnknownUsernameException $e) { 985 | die('Unknown username'); 986 | } 987 | catch (\Devinow\Auth\AmbiguousUsernameException $e) { 988 | die('Ambiguous username'); 989 | } 990 | ``` 991 | 992 | **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`. 993 | 994 | #### Checking roles 995 | 996 | ```php 997 | try { 998 | if ($auth->admin()->doesUserHaveRole($userId, \Devinow\Auth\Role::ADMIN)) { 999 | echo 'The specified user is an administrator'; 1000 | } 1001 | else { 1002 | echo 'The specified user is not an administrator'; 1003 | } 1004 | } 1005 | catch (\Devinow\Auth\UnknownIdException $e) { 1006 | die('Unknown user ID'); 1007 | } 1008 | ``` 1009 | 1010 | Alternatively, you can get a list of all the roles that have been assigned to the user: 1011 | 1012 | ```php 1013 | $auth->admin()->getRolesForUserById($userId); 1014 | ``` 1015 | 1016 | #### Impersonating users (logging in as user) 1017 | 1018 | ```php 1019 | try { 1020 | $auth->admin()->logInAsUserById($_POST['id']); 1021 | } 1022 | catch (\Devinow\Auth\UnknownIdException $e) { 1023 | die('Unknown ID'); 1024 | } 1025 | catch (\Devinow\Auth\EmailNotVerifiedException $e) { 1026 | die('Email address not verified'); 1027 | } 1028 | 1029 | // or 1030 | 1031 | try { 1032 | $auth->admin()->logInAsUserByEmail($_POST['email']); 1033 | } 1034 | catch (\Devinow\Auth\InvalidEmailException $e) { 1035 | die('Unknown email address'); 1036 | } 1037 | catch (\Devinow\Auth\EmailNotVerifiedException $e) { 1038 | die('Email address not verified'); 1039 | } 1040 | 1041 | // or 1042 | 1043 | try { 1044 | $auth->admin()->logInAsUserByUsername($_POST['username']); 1045 | } 1046 | catch (\Devinow\Auth\UnknownUsernameException $e) { 1047 | die('Unknown username'); 1048 | } 1049 | catch (\Devinow\Auth\AmbiguousUsernameException $e) { 1050 | die('Ambiguous username'); 1051 | } 1052 | catch (\Devinow\Auth\EmailNotVerifiedException $e) { 1053 | die('Email address not verified'); 1054 | } 1055 | ``` 1056 | 1057 | #### Changing a user’s password 1058 | 1059 | ```php 1060 | try { 1061 | $auth->admin()->changePasswordForUserById($_POST['id'], $_POST['newPassword']); 1062 | } 1063 | catch (\Devinow\Auth\UnknownIdException $e) { 1064 | die('Unknown ID'); 1065 | } 1066 | catch (\Devinow\Auth\InvalidPasswordException $e) { 1067 | die('Invalid password'); 1068 | } 1069 | 1070 | // or 1071 | 1072 | try { 1073 | $auth->admin()->changePasswordForUserByUsername($_POST['username'], $_POST['newPassword']); 1074 | } 1075 | catch (\Devinow\Auth\UnknownUsernameException $e) { 1076 | die('Unknown username'); 1077 | } 1078 | catch (\Devinow\Auth\AmbiguousUsernameException $e) { 1079 | die('Ambiguous username'); 1080 | } 1081 | catch (\Devinow\Auth\InvalidPasswordException $e) { 1082 | die('Invalid password'); 1083 | } 1084 | ``` 1085 | 1086 | ### Cookies 1087 | 1088 | This library uses two cookies to keep state on the client: The first, whose name you can retrieve using 1089 | 1090 | ```php 1091 | \session_name(); 1092 | ``` 1093 | 1094 | 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: 1095 | 1096 | ```php 1097 | \Devinow\Auth\Auth::createRememberCookieName(); 1098 | ``` 1099 | 1100 | #### Renaming the library’s cookies 1101 | 1102 | You can rename the session cookie used by this library through one of the following means, in order of recommendation: 1103 | 1104 | * In the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`), find the line with the `session.name` directive and change its value to something like `session_v1`, as in: 1105 | 1106 | ``` 1107 | session.name = session_v1 1108 | ``` 1109 | 1110 | * 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: 1111 | 1112 | ```php 1113 | \ini_set('session.name', 'session_v1'); 1114 | ``` 1115 | 1116 | For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`). 1117 | 1118 | * 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: 1119 | 1120 | ```php 1121 | \session_name('session_v1'); 1122 | ``` 1123 | 1124 | For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`). 1125 | 1126 | 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. 1127 | 1128 | #### Defining the domain scope for cookies 1129 | 1130 | 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. 1131 | 1132 | 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. 1133 | 1134 | 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. 1135 | 1136 | You can change the attribute through one of the following means, in order of recommendation: 1137 | 1138 | * In the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`), find the line with the `session.cookie_domain` directive and change its value as desired, e.g.: 1139 | 1140 | ``` 1141 | session.cookie_domain = example.com 1142 | ``` 1143 | 1144 | * 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.: 1145 | 1146 | ```php 1147 | \ini_set('session.cookie_domain', 'example.com'); 1148 | ``` 1149 | 1150 | For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`). 1151 | 1152 | #### Restricting the path where cookies are available 1153 | 1154 | 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. 1155 | 1156 | 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. 1157 | 1158 | You can change the attribute through one of the following means, in order of recommendation: 1159 | 1160 | * In the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`), find the line with the `session.cookie_path` directive and change its value as desired, e.g.: 1161 | 1162 | ``` 1163 | session.cookie_path = / 1164 | ``` 1165 | 1166 | * 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.: 1167 | 1168 | ```php 1169 | \ini_set('session.cookie_path', '/'); 1170 | ``` 1171 | 1172 | For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`). 1173 | 1174 | #### Controlling client-side script access to cookies 1175 | 1176 | 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. 1177 | 1178 | 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. 1179 | 1180 | You can change the attribute through one of the following means, in order of recommendation: 1181 | 1182 | * In the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`), find the line with the `session.cookie_httponly` directive and change its value as desired, e.g.: 1183 | 1184 | ``` 1185 | session.cookie_httponly = 1 1186 | ``` 1187 | 1188 | * 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.: 1189 | 1190 | ```php 1191 | \ini_set('session.cookie_httponly', 1); 1192 | ``` 1193 | 1194 | For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`). 1195 | 1196 | #### Configuring transport security for cookies 1197 | 1198 | 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`. 1199 | 1200 | 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`. 1201 | 1202 | You can change the attribute through one of the following means, in order of recommendation: 1203 | 1204 | * In the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`), find the line with the `session.cookie_secure` directive and change its value as desired, e.g.: 1205 | 1206 | ``` 1207 | session.cookie_secure = 1 1208 | ``` 1209 | 1210 | * 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.: 1211 | 1212 | ```php 1213 | \ini_set('session.cookie_secure', 1); 1214 | ``` 1215 | 1216 | For this to work, `session.auto_start` must be set to `0` in the [PHP configuration](https://www.php.net/manual/configuration.file.php) (`php.ini`). 1217 | 1218 | ### Utilities 1219 | 1220 | #### Creating a random string 1221 | 1222 | ```php 1223 | $length = 24; 1224 | $randomStr = \Devinow\Auth\Auth::createRandomString($length); 1225 | ``` 1226 | 1227 | #### Creating a UUID v4 as per RFC 4122 1228 | 1229 | ```php 1230 | $uuid = \Devinow\Auth\Auth::createUuid(); 1231 | ``` 1232 | 1233 | ### Reading and writing session data 1234 | 1235 | For detailed information on how to read and write session data conveniently, please refer to [the documentation of the session library](https://github.com/devinow/cookie#reading-and-writing-session-data), which is included by default. 1236 | 1237 | ## Frequently asked questions 1238 | 1239 | ### What about password hashing? 1240 | 1241 | 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. 1242 | 1243 | 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$`. 1244 | 1245 | 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. 1246 | 1247 | ### How can I implement custom password requirements? 1248 | 1249 | 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. 1250 | 1251 | 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: 1252 | 1253 | ```php 1254 | function isPasswordAllowed($password) { 1255 | if (\strlen($password) < 8) { 1256 | return false; 1257 | } 1258 | 1259 | $blacklist = [ 'password1', '123456', 'qwerty' ]; 1260 | 1261 | if (\in_array($password, $blacklist)) { 1262 | return false; 1263 | } 1264 | 1265 | return true; 1266 | } 1267 | 1268 | if (isPasswordAllowed($password)) { 1269 | $auth->register($email, $password); 1270 | } 1271 | ``` 1272 | 1273 | ### Why are there problems when using other libraries that work with sessions? 1274 | 1275 | 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. 1276 | 1277 | ### Why are other sites not able to frame or embed my site? 1278 | 1279 | If you want to let others include your site in a ``, `