### 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 '