### Prepare Email 2FA Setup Source: https://github.com/delight-im/php-auth/blob/master/README.md Initiates the setup for email-based two-factor authentication. It requires password reconfirmation and returns the user's email address and the OTP to be sent via email. Exceptions include mechanism already enabled, not logged in, and too many requests. ```php try { if ($auth->reconfirmPassword($_POST['password'])) { $emailAddressAndOtpValue = $auth->prepareTwoFactorViaEmail(); // To do: send the one-time password '$emailAddressAndOtpValue[1]' to email address '$emailAddressAndOtpValue[0]' // Consider using the 'mail' function, Symfony Mailer, Swiftmailer, PHPMailer, etc., to send the email ``` -------------------------------- ### Install PHP Auth Library via Composer Source: https://github.com/delight-im/php-auth/blob/master/README.md This code snippet demonstrates how to install the delight-im/auth library using Composer, a dependency manager for PHP. It pulls the library and its dependencies into your project, making it ready for use. Ensure Composer is installed and initialized in your project. ```bash $ composer require delight-im/auth ``` -------------------------------- ### Prepare TOTP 2FA Setup Source: https://github.com/delight-im/php-auth/blob/master/README.md Initiates the setup for Time-based One-Time Password (TOTP) two-factor authentication. It requires password reconfirmation and returns a key URI for QR code generation and a secret for manual input. Exceptions handled include mechanism already enabled, not logged in, and too many requests. ```php try { if ($auth->reconfirmPassword($_POST['password'])) { $keyUriAndSecret = $auth->prepareTwoFactorViaTotp('Example.com'); // To do: encode the key URI '$keyUriAndSecret[0]' as a QR code (preferably on the client side) and display the QR code to the user // and, additionally, show the secret string '$keyUriAndSecret[1]' to the user as a fallback for manual input } else { echo 'Please re-confirm your correct password'; } } catch (Delight\Auth\TwoFactorMechanismAlreadyEnabledException $e) { echo 'Two-factor authentication via TOTP has already been enabled'; } catch (Delight\Auth\NotLoggedInException $e) { echo 'Please sign in first'; } catch (Delight\Auth\TooManyRequestsException $e) { echo 'Please try again later'; } ``` -------------------------------- ### Enable Two-Factor Authentication Source: https://github.com/delight-im/php-auth/blob/master/README.md This section covers the process of enabling two-factor authentication (2FA) via TOTP, SMS, or email. It includes steps for preparing the setup, handling user input for one-time passwords, and managing potential exceptions during the process. Recovery codes are generated upon successful setup. ```APIDOC ## Enable Two-Factor Authentication ### Description This endpoint allows users to enable two-factor authentication via TOTP, SMS, or email by providing a one-time password. ### Method POST ### Endpoint `/enableTwoFactor` (Conceptual endpoint, actual implementation may vary) ### Parameters #### Request Body - **oneTimePassword** (string) - Required - The one-time password provided by the user. - **mechanism** (string) - Required - The 2FA mechanism to enable (e.g., 'totp', 'sms', 'email'). ### Request Example ```json { "oneTimePassword": "123456", "mechanism": "totp" } ``` ### Response #### Success Response (200) - **recoveryCodes** (array) - An array of recovery codes generated for the user. #### Response Example ```json { "recoveryCodes": [ "ABCDE12345", "FGHIJ67890" ] } ``` #### Error Responses - **InvalidOneTimePasswordException**: The provided one-time password was incorrect. - **TwoFactorMechanismNotInitializedException**: The setup for the chosen 2FA mechanism was not prepared. - **TwoFactorMechanismAlreadyEnabledException**: The chosen 2FA mechanism is already enabled. - **NotLoggedInException**: The user is not currently logged in. - **TooManyRequestsException**: Too many requests were made; please try again later. ``` -------------------------------- ### Prepare SMS 2FA Setup Source: https://github.com/delight-im/php-auth/blob/master/README.md Initiates the setup for SMS-based two-factor authentication. It requires password reconfirmation and the user's phone number, returning the phone number and the OTP to be sent via SMS. Exceptions include invalid phone numbers, mechanism already enabled, not logged in, and too many requests. ```php try { if ($auth->reconfirmPassword($_POST['password'])) { $phoneNumberAndOtpValue = $auth->prepareTwoFactorViaSms($_POST['phoneNumber']); // To do: send the one-time password '$phoneNumberAndOtpValue[1]' to (still unverified) phone number '$phoneNumberAndOtpValue[0]' // Consider using a third-party service and a compatible SDK to send the text message echo 'Please enter the initial one-time password that has been sent to you via text message'; } else { echo 'Please re-confirm your correct password'; } } catch (Delight\Auth\InvalidPhoneNumberException $e) { echo 'Please provide a valid phone number'; } catch (Delight\Auth\TwoFactorMechanismAlreadyEnabledException $e) { echo 'Two-factor authentication via SMS has already been enabled'; } catch (Delight\Auth\NotLoggedInException $e) { echo 'Please sign in first'; } catch (Delight\Auth\TooManyRequestsException $e) { echo 'Please try again later'; } ``` -------------------------------- ### PHP - Instantiate Authentication with PDO Source: https://github.com/delight-im/php-auth/blob/master/README.md This snippet demonstrates how to create a new instance of the Auth class using an existing PDO connection. It shows examples for MySQL, PostgreSQL, and SQLite. The database user requires SELECT, INSERT, UPDATE, and DELETE privileges. ```php // $db = new \PDO('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password'); // or // $db = new \PDO('pgsql:dbname=my-database;host=localhost;port=5432', 'my-username', 'my-password'); // or // $db = new \PDO('sqlite:../Databases/my-database.sqlite'); // $db = \Delight\Db\PdoDatabase::fromDsn(new \Delight\Db\PdoDsn('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password')); // or // $db = \Delight\Db\PdoDatabase::fromDsn(new \Delight\Db\PdoDsn('pgsql:dbname=my-database;host=localhost;port=5432', 'my-username', 'my-password')); // or // $db = \Delight\Db\PdoDatabase::fromDsn(new \Delight\Db\PdoDsn('sqlite:../Databases/my-database.sqlite')); $auth = new \Delight\Auth\Auth($db); ``` -------------------------------- ### Prepare and Enable Two-Factor Authentication (TOTP) in PHP Source: https://context7.com/delight-im/php-auth/llms.txt This snippet demonstrates how to set up and enable Time-based One-Time Password (TOTP) two-factor authentication. It includes preparing the 2FA setup by generating a secret key and QR code, and then enabling it by verifying an initial OTP. It also shows how to check if TOTP is enabled and how to disable it. Requires the DelightAuth library. ```php reconfirmPassword($_POST['password'])) { list($keyUri, $secret) = $auth->prepareTwoFactorViaTotp('MyApp'); // Display QR code to user (encode $keyUri as QR) echo ''; echo 'Manual entry code: ' . $secret; $_SESSION['setup_2fa'] = true; } } catch (Delight\Auth\TwoFactorMechanismAlreadyEnabledException $e) { die('TOTP 2FA already enabled'); } catch (Delight\Auth\NotLoggedInException $e) { die('Please log in'); } // Step 2: Enable 2FA by verifying initial OTP try { $recoveryCodes = $auth->enableTwoFactorViaTotp($_POST['otp']); echo 'Two-factor authentication enabled! Save these recovery codes:'; foreach ($recoveryCodes as $code) { echo $code . "\n"; } } catch (Delight\Auth\InvalidOneTimePasswordException $e) { die('Invalid verification code'); } catch (Delight\Auth\TwoFactorMechanismNotInitializedException $e) { die('Please complete setup first'); } // Check if 2FA is enabled if ($auth->hasTwoFactorViaTotp()) { echo 'TOTP 2FA is enabled'; } // Disable 2FA $auth->disableTwoFactorViaTotp(); ?> ``` -------------------------------- ### PHP: User Registration (Sign Up) with Delight-Auth Source: https://github.com/delight-im/php-auth/blob/master/README.md This code snippet shows how to register a new user using the Delight-Auth library. It handles potential exceptions such as invalid email, invalid password, user already exists, and too many requests. The example includes a callback function for sending verification emails. ```php ```php try { $userId = $auth->register($_POST['email'], $_POST['password'], $_POST['username'], function ($selector, $token) { echo 'Send ' . $selector . ' and ' . $token . ' to the user (e.g. via email)'; echo ' For emails, consider using the mail(...) function, Symfony Mailer, Swiftmailer, PHPMailer, etc.'; echo ' For SMS, consider using a third-party service and a compatible SDK'; }); echo 'We have signed up a new user with the ID ' . $userId; } catch (\Delight\Auth\InvalidEmailException $e) { die('Invalid email address'); } catch (\Delight\Auth\InvalidPasswordException $e) { die('Invalid password'); } catch (\Delight\Auth\UserAlreadyExistsException $e) { die('User already exists'); } catch (\Delight\Auth\TooManyRequestsException $e) { die('Too many requests'); } ``` ``` -------------------------------- ### Get All User Roles (PHP) Source: https://github.com/delight-im/php-auth/blob/master/README.md Retrieves a list of all roles assigned to the current user. This can be used for further processing or display of the user's permissions. ```php $auth->getRoles(); ``` -------------------------------- ### Implement custom password requirements Source: https://github.com/delight-im/php-auth/blob/master/README.md Allows for custom validation of passwords before they are used with the authentication library. This example checks for minimum length and a blacklist of common passwords. ```php function isPasswordAllowed($password) { if (\strlen($password) < 8) { return false; } $blacklist = [ 'password1', '123456', 'qwerty' ]; if (\in_array($password, $blacklist)) { return false; } return true; } if (isPasswordAllowed($password)) { $auth->register($email, $password); } ``` -------------------------------- ### Two-Factor Authentication (TOTP) Source: https://context7.com/delight-im/php-auth/llms.txt Guides users through enabling and managing Time-based One-Time Password (TOTP) authentication using authenticator apps. ```APIDOC ## Two-Factor Authentication (TOTP) ### Description Enable time-based one-time passwords using authenticator apps. ### Method POST (Implicit for setup and enabling) ### Endpoint Not explicitly defined, operations are performed within the PHP script. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **password** (string) - Required - The user's current password for reconfirmation. - **otp** (string) - Required - The One-Time Password from the authenticator app for enabling 2FA. ### Request Example ```php // Step 1: Prepare 2FA setup try { if ($auth->reconfirmPassword($_POST['password'])) { list($keyUri, $secret) = $auth->prepareTwoFactorViaTotp('MyApp'); // Display QR code to user (encode $keyUri as QR) echo ''; echo 'Manual entry code: ' . $secret; $_SESSION['setup_2fa'] = true; } } catch (Delight\Auth\TwoFactorMechanismAlreadyEnabledException $e) { die('TOTP 2FA already enabled'); } catch (Delight\Auth\NotLoggedInException $e) { die('Please log in'); } // Step 2: Enable 2FA by verifying initial OTP try { $recoveryCodes = $auth->enableTwoFactorViaTotp($_POST['otp']); echo 'Two-factor authentication enabled! Save these recovery codes:'; foreach ($recoveryCodes as $code) { echo $code . "\n"; } } catch (Delight\Auth\InvalidOneTimePasswordException $e) { die('Invalid verification code'); } catch (Delight\Auth\TwoFactorMechanismNotInitializedException $e) { die('Please complete setup first'); } // Check if 2FA is enabled if ($auth->hasTwoFactorViaTotp()) { echo 'TOTP 2FA is enabled'; } // Disable 2FA $auth->disableTwoFactorViaTotp(); ``` ### Response #### Success Response (200) - **recoveryCodes** (array) - An array of recovery codes for the user. #### Response Example ```json { "recoveryCodes": [ "ABC123XYZ", "DEF456UVW" ] } ``` **Note**: The PHP code directly outputs messages or headers. The JSON example is illustrative for recovery codes. ``` -------------------------------- ### Get Available Roles Names (PHP) Source: https://github.com/delight-im/php-auth/blob/master/README.md Retrieves an array containing the names of all available roles. This can be used for displaying role options or for validation purposes. ```php \Delight\Auth\Role::getNames(); ``` -------------------------------- ### Get Available Roles Map (PHP) Source: https://github.com/delight-im/php-auth/blob/master/README.md Retrieves a map of all available roles, including their names and values. This is useful for understanding the full set of roles supported by the library and for dynamic role management. ```php \Delight\Auth\Role::getMap(); ``` -------------------------------- ### Change Email and Username in PHP Source: https://context7.com/delight-im/php-auth/llms.txt Provides PHP code examples for updating a user's email address and username using the PHP-Auth library. Email changes require confirmation via a link sent to the new address. Username changes can include uniqueness checks. Handles exceptions like InvalidEmailException, UserAlreadyExistsException, NotLoggedInException, and DuplicateUsernameException. ```php reconfirmPassword($_POST['password'])) { $auth->changeEmail($_POST['newEmail'], function ($selector, $token) { $url = 'https://example.com/verify?selector=' . urlencode($selector) . '&token=' . urlencode($token); // Send to NEW email address mail($_POST['newEmail'], 'Confirm email change', "Confirm: $url"); }); echo 'Confirmation email sent. Change will take effect after verification.'; // Notify old email mail($auth->getEmail(), 'Email change requested', 'Your email is being changed.'); } } catch (Delight\Auth\InvalidEmailException $e) { die('Invalid email'); } catch (Delight\Auth\UserAlreadyExistsException $e) { die('Email already in use'); } catch (Delight\Auth\NotLoggedInException $e) { die('Please log in'); } // Change username try { $auth->changeUsername($_POST['newUsername']); echo 'Username changed to: ' . $auth->getUsername(); } catch (Delight\Auth\NotLoggedInException $e) { die('Not logged in'); } catch (Delight\Auth\TooManyRequestsException $e) { die('Too many username changes'); } // Change username with uniqueness check try { $auth->changeUsername($_POST['newUsername'], true); } catch (Delight\Auth\DuplicateUsernameException $e) { die('Username already taken'); } ?> ``` -------------------------------- ### Construct Password Reset URL in PHP Source: https://github.com/delight-im/php-auth/blob/master/README.md This example demonstrates how to construct a password reset URL using the selector and token provided by the `forgotPassword` method. The `urlencode` function is used to ensure that the selector and token are properly encoded for inclusion in a URL. This URL would typically be sent to the user via email or SMS. ```php $url = 'https://www.example.com/reset_password?selector=' . \urlencode($selector) . '&token=' . \urlencode($token); ``` -------------------------------- ### Change User Password by ID or Username in PHP Source: https://github.com/delight-im/php-auth/blob/master/README.md Provides examples for changing a user's password either by their unique ID or by their username. Includes error handling for unknown IDs, invalid passwords, and ambiguous usernames. This operation requires administrative access. ```php try { $auth->admin()->changePasswordForUserById($_POST['id'], $_POST['newPassword']); } catch (Delight\Auth\UnknownIdException $e) { die('Unknown ID'); } catch (Delight\Auth\InvalidPasswordException $e) { die('Invalid password'); } // or try { $auth->admin()->changePasswordForUserByUsername($_POST['username'], $_POST['newPassword']); } catch (Delight\Auth\UnknownUsernameException $e) { die('Unknown username'); } catch (Delight\Auth\AmbiguousUsernameException $e) { die('Ambiguous username'); } catch (Delight\Auth\InvalidPasswordException $e) { die('Invalid password'); } ``` -------------------------------- ### Implement Rate Limiting/Throttling in PHP Source: https://context7.com/delight-im/php-auth/llms.txt Demonstrates how to implement custom throttling for features using the PHP-Auth library. It covers basic request limits, IP-based throttling, and burst traffic allowance. It also shows how to check remaining requests without consuming them. Exceptions like TooManyRequestsException are handled. ```php throttle(['download-report'], 3, 60); // Generate and serve report generateReport(); } catch (Delight\Auth\TooManyRequestsException $e) { http_response_code(429); die('Too many requests. Try again in ' . $e->getMessage() . ' seconds.'); } // Throttle per IP address try { $auth->throttle(['api-call', $_SERVER['REMOTE_ADDR']], 100, 3600); // Process API request handleApiRequest(); } catch (Delight\Auth\TooManyRequestsException $e) { http_response_code(429); exit('Rate limit exceeded'); } // Allow burst traffic (burst factor of 5) try { // 10 requests per minute normally, 50 during bursts $auth->throttle(['search'], 10, 60, 5); performSearch(); } catch (Delight\Auth\TooManyRequestsException $e) { die('Search rate limit exceeded'); } // Simulate throttling check without consuming resources $remaining = $auth->throttle(['action'], 5, 60, null, true); echo "Remaining requests: $remaining"; ?> ``` -------------------------------- ### Get User Roles with php-auth Source: https://github.com/delight-im/php-auth/blob/master/README.md Retrieves a list of all roles assigned to a user identified by their ID. This function returns an array of roles. ```php $auth->admin()->getRolesForUserById($userId); ``` -------------------------------- ### Register New User with Email Verification in PHP Source: https://context7.com/delight-im/php-auth/llms.txt Registers a new user with their email, password, and username. It includes a callback function to send a verification email, containing a unique selector and token. Error handling is provided for invalid inputs, existing users, and excessive requests. ```php register($_POST['email'], $_POST['password'], $_POST['username'], function ($selector, $token) { // Build verification URL $url = 'https://example.com/verify?selector=' . urlencode($selector) . '&token=' . urlencode($token); // Send email to user mail($_POST['email'], 'Verify your account', "Click to verify: $url"); }); echo "User registered with ID: $userId. Check email for verification link."; } catch (\Delight\Auth\InvalidEmailException $e) { die('Invalid email address'); } catch (\Delight\Auth\InvalidPasswordException $e) { die('Password must not be empty'); } catch (\Delight\Auth\UserAlreadyExistsException $e) { die('User with this email already exists'); } catch (\Delight\Auth\TooManyRequestsException $e) { die('Too many registration attempts. Please try again later.'); } ``` -------------------------------- ### Get User IP Address (PHP) Source: https://github.com/delight-im/php-auth/blob/master/README.md Retrieves the IP address of the currently logged-in user. This function is straightforward and does not require any specific input parameters. ```php $ip = $auth->getIpAddress(); ``` -------------------------------- ### Get User Email Source: https://github.com/delight-im/php-auth/blob/master/README.md Retrieves the email address of the currently logged-in user. Returns null if the user is not logged in. This method requires the email to have been provided during registration. ```php $email = $auth->getEmail(); ``` -------------------------------- ### User Registration API Source: https://context7.com/delight-im/php-auth/llms.txt Registers new users and sends an email verification link. Handles various exceptions like invalid email/password and user already exists. ```APIDOC ## User Registration ### Description Registers new users and optionally sends an email verification link. This endpoint handles various exceptions related to invalid credentials, existing users, and request throttling. ### Method POST ### Endpoint `/register` (Conceptual endpoint, actual implementation is a function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's desired password. - **username** (string) - Optional - The user's chosen username. ### Request Example ```json { "email": "user@example.com", "password": "securepassword123", "username": "testuser" } ``` ### Response #### Success Response (200) - **userId** (integer) - The ID of the newly registered user. #### Response Example ```json { "message": "User registered with ID: 123. Check email for verification link." } ``` #### Error Responses - **InvalidEmailException**: If the email address is invalid. - **InvalidPasswordException**: If the password is empty. - **UserAlreadyExistsException**: If a user with the given email already exists. - **TooManyRequestsException**: If there have been too many registration attempts recently. ``` -------------------------------- ### Initialize Auth Instance in PHP Source: https://context7.com/delight-im/php-auth/llms.txt Initializes the PHP-Auth authentication system by providing a PDO database connection. It can optionally accept a custom IP address for proxy configurations and allows for table prefixes. Throttling can be disabled for development purposes. ```php id()` is available for this method. ```php $id = $auth->getUserId(); ``` -------------------------------- ### Login with Second Factor Source: https://github.com/delight-im/php-auth/blob/master/README.md This section outlines the process for handling login attempts when a second factor (2FA) is required. It details how to check for different 2FA options (TOTP, SMS, Email) and how to complete the authentication by providing the one-time password. ```APIDOC ## Login with Second Factor ### Description This endpoint handles the second step of the login process when two-factor authentication is required. It prompts the user for a one-time password based on the available 2FA options. ### Method POST ### Endpoint `/provideSecondFactor` (Conceptual endpoint, actual implementation may vary) ### Parameters #### Request Body - **oneTimePassword** (string) - Required - The one-time password entered by the user. ### Request Example ```json { "oneTimePassword": "987654" } ``` ### Response #### Success Response (200) - **message** (string) - A success message indicating the user is signed in. #### Response Example ```json { "message": "You are now signed in" } ``` #### Error Responses - **SecondFactorRequiredException**: This exception is caught during login methods like `Auth#login` when 2FA is needed. The exception object provides information about available 2FA options (TOTP, SMS, Email) and recipient details if applicable. - `hasTotpOption()`: Checks if TOTP is an available option. - `hasSmsOption()`: Checks if SMS is an available option. - `hasEmailOption()`: Checks if Email is an available option. - `getSmsRecipientMasked()`: Returns the masked SMS recipient number. - `getEmailRecipientMasked()`: Returns the masked Email recipient address. - **NotLoggedInException**: The user is not currently logged in. - **TooManyRequestsException**: Too many requests were made; please try again later. ``` -------------------------------- ### Get Available Roles Values (PHP) Source: https://github.com/delight-im/php-auth/blob/master/README.md Retrieves an array containing the numerical values of all available roles. This is useful for internal checks or when interacting with a database that stores roles as numerical IDs. ```php \Delight\Auth\Role::getValues(); ``` -------------------------------- ### Create New User with php-auth Source: https://github.com/delight-im/php-auth/blob/master/README.md Creates a new user with the provided email, password, and an optional username. It handles exceptions for invalid email, invalid password, and existing users. The username parameter is optional. ```php try { $userId = $auth->admin()->createUser($_POST['email'], $_POST['password'], $_POST['username']); echo 'We have signed up a new user with the ID ' . $userId; } catch (Delight\Auth\InvalidEmailException $e) { die('Invalid email address'); } catch (Delight\Auth\InvalidPasswordException $e) { die('Invalid password'); } catch (Delight\Auth\UserAlreadyExistsException $e) { die('User already exists'); } ``` -------------------------------- ### Retrieve All Users SQL Query Source: https://github.com/delight-im/php-auth/blob/master/README.md A basic SQL query to retrieve a list of all registered users from the 'users' table. This query fetches common user attributes like ID, email, username, status, registration time, and last login. ```sql SELECT id, email, username, status, verified, roles_mask, registered, last_login FROM users; ``` -------------------------------- ### Get User Display Name Source: https://github.com/delight-im/php-auth/blob/master/README.md Retrieves the display name (username) of the currently logged-in user. Usernames are optional and only available if provided during registration. Returns null if the user is not logged in or if no username was set. ```php $username = $auth->getUsername(); ``` -------------------------------- ### Impersonate User by ID, Email, or Username in PHP Source: https://github.com/delight-im/php-auth/blob/master/README.md Demonstrates how to log in as a user by their ID, email, or username using the admin interface. Includes error handling for unknown IDs, unverified emails, unknown or ambiguous usernames. This functionality requires admin privileges. ```php try { $auth->admin()->logInAsUserById($_POST['id']); } catch (Delight\Auth\UnknownIdException $e) { die('Unknown ID'); } catch (Delight\Auth\EmailNotVerifiedException $e) { die('Email address not verified'); } // or try { $auth->admin()->logInAsUserByEmail($_POST['email']); } catch (Delight\Auth\InvalidEmailException $e) { die('Unknown email address'); } catch (Delight\Auth\EmailNotVerifiedException $e) { die('Email address not verified'); } // or try { $auth->admin()->logInAsUserByUsername($_POST['username']); } catch (Delight\Auth\UnknownUsernameException $e) { die('Unknown username'); } catch (Delight\Auth\AmbiguousUsernameException $e) { die('Ambiguous username'); } catch (Delight\Auth\EmailNotVerifiedException $e) { die('Email address not verified'); } ``` -------------------------------- ### Update Database Schema for PHP Auth v7.x.x to v8.x.x (SQLite) Source: https://github.com/delight-im/php-auth/blob/master/Migration.md This SQL statement is used to update the SQLite database schema by adding the 'force_logout' column to the 'users' table, which was a change introduced between versions 7.x.x and 8.x.x of the PHP Auth library. ```sql ALTER TABLE users ADD COLUMN "force_logout" INTEGER NOT NULL CHECK ("force_logout" >= 0) DEFAULT "0"; ``` -------------------------------- ### Handle Two-Factor Authentication Exceptions in PHP Source: https://github.com/delight-im/php-auth/blob/master/README.md This snippet demonstrates how to catch and handle various exceptions that may occur during two-factor authentication operations in PHP. It covers scenarios like missing login, too many requests, and specific 2FA mechanism errors. ```php catch (\Delight\Auth\TwoFactorMechanismAlreadyEnabledException $e) { echo 'Two-factor authentication via email has already been enabled'; } catch (\Delight\Auth\NotLoggedInException $e) { echo 'Please sign in first'; } catch (\Delight\Auth\TooManyRequestsException $e) { echo 'Please try again later'; } ``` -------------------------------- ### Handle Two-Factor Authentication (2FA) during Login in PHP Source: https://context7.com/delight-im/php-auth/llms.txt This PHP code snippet illustrates how to manage the two-factor authentication process during user login. It handles cases where a user might require a second factor (TOTP, SMS, or email) after a successful initial login. It also shows how to verify the provided one-time password to complete the login. Requires the Delight\Auth library. ```php login($_POST['email'], $_POST['password']); // Login successful without 2FA header('Location: /dashboard.php'); } catch (Delight\Auth\SecondFactorRequiredException $e) { // User has 2FA enabled - show OTP input form if ($e->hasTotpOption()) { echo '
'; echo ''; echo '
'; } if ($e->hasSmsOption()) { // Send OTP via SMS sendSms($e->getSmsRecipient(), 'Your code: ' . $e->getSmsOtpValue()); echo 'Code sent to ' . $e->getSmsRecipientMasked(); } if ($e->hasEmailOption()) { // Send OTP via email mail($e->getEmailRecipient(), 'Login code', 'Your code: ' . $e->getEmailOtpValue()); echo 'Code sent to ' . $e->getEmailRecipientMasked(); } } // Verify 2FA code (on /verify-2fa.php) try { $auth->provideOneTimePasswordAsSecondFactor($_POST['otp']); echo 'Login successful!'; header('Location: /dashboard.php'); } catch (Delight\Auth\InvalidOneTimePasswordException $e) { die('Invalid verification code'); } catch (Delight\Auth\NotLoggedInException $e) { die('Please complete first factor first'); } ?> ``` -------------------------------- ### Update Database Schema for PHP Auth v7.x.x to v8.x.x (PostgreSQL) Source: https://github.com/delight-im/php-auth/blob/master/Migration.md This SQL statement is used to update the PostgreSQL database schema by adding the 'force_logout' column to the 'users' table, which was a change introduced between versions 7.x.x and 8.x.x of the PHP Auth library. ```sql ALTER TABLE users ADD COLUMN "force_logout" INTEGER NOT NULL DEFAULT '0' CHECK ("force_logout" >= 0); ``` -------------------------------- ### Update Database Schema for PHP Auth v7.x.x to v8.x.x (MySQL) Source: https://github.com/delight-im/php-auth/blob/master/Migration.md This SQL statement is used to update the MySQL database schema by adding the 'force_logout' column to the 'users' table, which was a change introduced between versions 7.x.x and 8.x.x of the PHP Auth library. ```sql ALTER TABLE users ADD COLUMN `force_logout` mediumint(7) unsigned NOT NULL DEFAULT '0' AFTER `last_login`; ``` -------------------------------- ### Persistent Login Management Source: https://github.com/delight-im/php-auth/blob/master/README.md Demonstrates how to manage persistent logins (remember me functionality) using a duration in seconds. ```APIDOC ## Persistent Login Management ### Description Controls the duration of a user's login session, allowing them to stay authenticated for extended periods. ### Method POST ### Endpoint `/login` (Example endpoint for login) ### Parameters #### Request Body - **email** (string) - Required - User's email address. - **password** (string) - Required - User's password. - **remember_me** (integer) - Optional - If set to `1`, enables persistent login for a default duration (e.g., one year). Otherwise, uses session-based login. ### Request Example ```json { "email": "user@example.com", "password": "securepassword", "remember_me": 1 } ``` ### Response #### Success Response (200) Indicates successful login. #### Response Example ```json { "message": "Login successful" } ``` #### Error Responses - **401 Unauthorized**: Invalid credentials. - **429 Too Many Requests**: Rate limit exceeded. ``` -------------------------------- ### Role Management API Source: https://github.com/delight-im/php-auth/blob/master/README.md Endpoints for assigning, removing, and checking roles for users. ```APIDOC ## POST /api/users/{userId}/roles ### Description Assigns a specific role to a user identified by their ID, email, or username. ### Method POST ### Endpoint /api/users/{userId}/roles ### Parameters #### Path Parameters - **userId** (integer) - Required - The ID of the user to whom the role will be assigned. #### Request Body - **role** (string) - Required - The role to assign (e.g., "ADMIN"). ### Request Example ```json { "role": "ADMIN" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message of role assignment. #### Response Example ```json { "message": "Role ADMIN assigned successfully." } ``` ## DELETE /api/users/{userId}/roles ### Description Removes a specific role from a user identified by their ID, email, or username. ### Method DELETE ### Endpoint /api/users/{userId}/roles ### Parameters #### Path Parameters - **userId** (integer) - Required - The ID of the user from whom the role will be removed. #### Request Body - **role** (string) - Required - The role to remove (e.g., "ADMIN"). ### Request Example ```json { "role": "ADMIN" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message of role removal. #### Response Example ```json { "message": "Role ADMIN removed successfully." } ``` ## GET /api/users/{userId}/roles/check ### Description Checks if a user has a specific role assigned. ### Method GET ### Endpoint /api/users/{userId}/roles/check ### Parameters #### Path Parameters - **userId** (integer) - Required - The ID of the user to check. #### Query Parameters - **role** (string) - Required - The role to check for (e.g., "ADMIN"). ### Request Example ``` GET /api/users/123/roles/check?role=ADMIN ``` ### Response #### Success Response (200) - **hasRole** (boolean) - True if the user has the specified role, false otherwise. #### Response Example ```json { "hasRole": true } ``` ## GET /api/users/{userId}/roles ### Description Retrieves a list of all roles assigned to a specific user. ### Method GET ### Endpoint /api/users/{userId}/roles ### Parameters #### Path Parameters - **userId** (integer) - Required - The ID of the user whose roles are to be retrieved. ### Request Example ``` GET /api/users/123/roles ``` ### Response #### Success Response (200) - **roles** (array) - A list of roles assigned to the user. #### Response Example ```json { "roles": ["ADMIN", "EDITOR"] } ``` ``` -------------------------------- ### Check Session Cookie Path Directive in PHP Source: https://github.com/delight-im/php-auth/blob/master/Migration.md This snippet demonstrates how to check the current value of the 'session.cookie_path' directive in PHP's configuration. It uses the built-in `ini_get` function to retrieve the setting and `var_dump` to display it. This is useful for debugging session cookie behavior. ```php \var_dump( \ini_get('session.cookie_path') ); ``` -------------------------------- ### PHP: User Login (Sign In) with Delight-Auth Source: https://github.com/delight-im/php-auth/blob/master/README.md This code snippet demonstrates user login using the Delight-Auth library. It attempts to log in a user with provided email and password. It includes error handling for invalid email, invalid password, email not verified, and too many requests. ```php ```php try { $auth->login($_POST['email'], $_POST['password']); echo 'User is logged in'; } catch (\Delight\Auth\InvalidEmailException $e) { die('Wrong email address'); } catch (\Delight\Auth\InvalidPasswordException $e) { die('Wrong password'); } catch (\Delight\Auth\EmailNotVerifiedException $e) { die('Email not verified'); } catch (\Delight\Auth\TooManyRequestsException $e) { die('Too many requests'); } ``` ``` -------------------------------- ### PHP Auth: Check Session Cookie Domain Directive Source: https://github.com/delight-im/php-auth/blob/master/Migration.md This PHP code snippet shows how to retrieve the current value of the `session.cookie_domain` directive. This is useful for diagnosing issues related to cookie scoping changes in the PHP Auth library v7.x.x, especially when migrating from older versions. ```php \var_dump(\ini_get('session.cookie_domain')); ``` -------------------------------- ### Update MySQL Schema to utf8mb4 - SQL Source: https://github.com/delight-im/php-auth/blob/master/Migration.md These SQL statements are used to update the MySQL database schema for the PHP Auth project. They change the character set from `utf8` to `utf8mb4` and the collation from `utf8_general_ci` to `utf8mb4_unicode_ci`. The commands also include statements to repair and optimize tables after the schema changes. ```sql ALTER TABLE `users` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL; ALTER TABLE `users_confirmations` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL; -- ALTER DATABASE `` CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci; ALTER TABLE `users` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; ALTER TABLE `users_confirmations` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; ALTER TABLE `users_remembered` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; ALTER TABLE `users_resets` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; ALTER TABLE `users_throttling` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; ALTER TABLE `users` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL; ALTER TABLE `users` CHANGE `username` `username` VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL; ALTER TABLE `users_confirmations` CHANGE `email` `email` VARCHAR(249) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL; ALTER TABLE `users_throttling` CHANGE `action_type` `action_type` ENUM('login','register','confirm_email') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL; REPAIR TABLE users; OPTIMIZE TABLE users; REPAIR TABLE users_confirmations; OPTIMIZE TABLE users_confirmations; REPAIR TABLE users_remembered; OPTIMIZE TABLE users_remembered; REPAIR TABLE users_resets; OPTIMIZE TABLE users_resets; REPAIR TABLE users_throttling; OPTIMIZE TABLE users_throttling; ``` -------------------------------- ### Administrative User Management in PHP Source: https://context7.com/delight-im/php-auth/llms.txt This PHP snippet outlines administrative functions for managing users within the DelightAuth system. It covers creating new users, deleting existing users by ID, assigning and removing roles (like MODERATOR or ADMIN), checking user roles, impersonating users, and changing another user's password. Access to these functions should be restricted to administrative interfaces. Requires the Delight\Auth library. ```php admin(); // Create new user try { $userId = $admin->createUser('user@example.com', 'securePassword123', 'johndoe'); echo 'Created user with ID: ' . $userId; } catch (Delight\Auth\InvalidEmailException $e) { die('Invalid email'); } catch (Delight\Auth\UserAlreadyExistsException $e) { die('User exists'); } // Delete user try { $admin->deleteUserById(42); echo 'User deleted'; } catch (Delight\Auth\UnknownIdException $e) { die('User not found'); } // Assign roles try { $admin->addRoleForUserById(42, \Delight\Auth\Role::MODERATOR); // Or by email $admin->addRoleForUserByEmail('user@example.com', \Delight\Auth\Role::ADMIN); } catch (Delight\Auth\UnknownIdException $e) { die('User not found'); } // Remove roles $admin->removeRoleForUserById(42, \Delight\Auth\Role::MODERATOR); // Check user roles $hasRole = $admin->doesUserHaveRole(42, \Delight\Auth\Role::ADMIN); $allRoles = $admin->getRolesForUserById(42); // Impersonate user (log in as another user) try { $admin->logInAsUserById(42); echo 'Now logged in as user 42'; } catch (Delight\Auth\UnknownIdException $e) { die('User not found'); } // Change another user's password try { $admin->changePasswordForUserById(42, 'newPassword123'); } catch (Delight\Auth\InvalidPasswordException $e) { die('Invalid password'); } ?> ``` -------------------------------- ### Update MySQL Database Schema for php-auth v4.x.x to v5.x.x Source: https://github.com/delight-im/php-auth/blob/master/Migration.md This SQL statement updates the MySQL database schema when migrating from version 4.x.x to 5.x.x of the php-auth library. It adds a new 'status' column to the 'users' table, specified as a TINYINT with unsigned and not null constraints, with a default value of 0. ```sql ALTER TABLE `users` ADD COLUMN `status` TINYINT(2) UNSIGNED NOT NULL DEFAULT 0 AFTER `username`; ``` -------------------------------- ### Confirm Email and Sign In with PHP Source: https://github.com/delight-im/php-auth/blob/master/README.md This alternative method, `confirmEmailAndSignIn`, verifies the user's email and immediately signs them in. It also supports persistent logins via an optional third parameter. On success, it returns an array containing the new and potentially the old email address. ```php $auth->confirmEmailAndSignIn($_GET['selector'], $_GET['token']); ``` -------------------------------- ### Define Custom Role Names (PHP) Source: https://github.com/delight-im/php-auth/blob/master/README.md This code shows how to define custom role names by aliasing existing roles from the Delight Auth library. This allows for more domain-specific terminology in your application. Ensure you do not alias a single built-in role to multiple custom names. ```php namespace My\Namespace; final class MyRole { const CUSTOMER_SERVICE_AGENT = \Delight\Auth\Role::REVIEWER; const FINANCIAL_DIRECTOR = \Delight\Auth\Role::COORDINATOR; private function __construct() {} } // Usage: // \My\Namespace\MyRole::CUSTOMER_SERVICE_AGENT; // \My\Namespace\MyRole::FINANCIAL_DIRECTOR; ``` -------------------------------- ### PHP Utility Functions for Random Strings, UUIDs, IPs, and Cookies Source: https://context7.com/delight-im/php-auth/llms.txt Illustrates the use of utility functions provided by the PHP-Auth library. This includes generating random strings, creating UUID v4, retrieving the user's IP address, and generating custom or default remember cookie names. These functions are helpful for various application tasks. ```php getIpAddress(); echo "Your IP: $ip"; // Create custom cookie names $cookieName = \Delight\Auth\Auth::createCookieName('preferences'); echo $cookieName; // e.g., "preferences_a8B3cD4e" // Get remember cookie name $rememberCookieName = \Delight\Auth\Auth::createRememberCookieName(); ?> ``` -------------------------------- ### PHP Auth: Restore Old Session Cookie Domain Behavior Source: https://github.com/delight-im/php-auth/blob/master/Migration.md This snippet demonstrates how to restore the previous session cookie domain behavior in PHP Auth v7.x.x. It uses `ini_set` to dynamically set `session.cookie_domain` based on the HTTP host, which is necessary when `session.cookie_domain` is empty and the application is accessed via a domain name. ```php \ini_set('session.cookie_domain', \preg_replace('/^www\./', '', $_SERVER['HTTP_HOST'])); ```