### Install RainLab User Plugin Source: https://github.com/rainlab/user-plugin/blob/master/README.md Installs the RainLab User plugin using the October CMS artisan command. ```bash php artisan plugin:install RainLab.User ``` -------------------------------- ### Install User Plugin v1.7 for October CMS v1.0-v2.3 Source: https://github.com/rainlab/user-plugin/blob/master/README.md Installs version 1.7 of the User plugin for even older versions of October CMS (v1.0 to v2.3) using Composer. ```bash composer require rainlab/user-plugin "^1.7" ``` -------------------------------- ### Install User Plugin v2.1 for October CMS v3.0-v3.5 Source: https://github.com/rainlab/user-plugin/blob/master/README.md Installs version 2.1 of the User plugin for older versions of October CMS (v3.0 to v3.5) using Composer. ```bash composer require rainlab/user-plugin "^2.1" ``` -------------------------------- ### Registration Component Setup (PHP) Source: https://context7.com/rainlab/user-plugin/llms.txt This PHP snippet is a basic configuration for the Registration component, typically added to a registration page. It enables the user registration functionality. ```php // Add to your registration page [registration] ``` -------------------------------- ### Two-Factor Authentication API Source: https://github.com/rainlab/user-plugin/blob/master/docs/component-account.md Manages the setup, confirmation, and management of two-factor authentication for the user account. ```APIDOC ## POST /account/enableTwoFactor ### Description Initiates the process of enabling two-factor authentication for the user account. ### Method POST ### Endpoint /account/enableTwoFactor ### Response #### Success Response (200) Returns information or prompts for confirmation to enable two-factor authentication. #### Response Example ```json { "message": "Two-factor authentication setup initiated. Please check your authenticator app." } ``` ``` ```APIDOC ## POST /account/confirmTwoFactor ### Description Confirms the enablement of two-factor authentication by providing a valid code from the user's authenticator app. ### Method POST ### Endpoint /account/confirmTwoFactor ### Parameters #### Request Body - **code** (string) - Required - The code generated by the two-factor authenticator app. ### Response #### Success Response (200) Indicates successful confirmation and enablement of two-factor authentication. #### Response Example ```json { "message": "Two-factor authentication enabled successfully." } ``` ``` ```APIDOC ## POST /account/showTwoFactorRecoveryCodes ### Description Retrieves and displays the recovery codes for two-factor authentication. These codes can be used if the user loses access to their authenticator app. ### Method POST ### Endpoint /account/showTwoFactorRecoveryCodes ### Response #### Success Response (200) Returns an array of two-factor recovery codes. #### Response Example ```json { "recovery_codes": [ "12345678", "87654321" ] } ``` ``` ```APIDOC ## POST /account/regenerateTwoFactorRecoveryCodes ### Description Deletes the current two-factor recovery codes and generates a new set. This is useful if recovery codes are compromised or lost. ### Method POST ### Endpoint /account/regenerateTwoFactorRecoveryCodes ### Response #### Success Response (200) Returns the newly generated two-factor recovery codes. #### Response Example ```json { "message": "Recovery codes have been regenerated.", "recovery_codes": [ "abcdefgh", "hgfedcba" ] } ``` ``` ```APIDOC ## POST /account/disableTwoFactor ### Description Disables two-factor authentication for the user account. This action may require re-authentication or a confirmation step. ### Method POST ### Endpoint /account/disableTwoFactor ### Response #### Success Response (200) Confirms that two-factor authentication has been disabled. #### Response Example ```json { "message": "Two-factor authentication has been disabled." } ``` ``` -------------------------------- ### User API Page Example (Twig) Source: https://github.com/rainlab/user-plugin/blob/master/docs/auth-bearer-tokens.md A CMS page example demonstrating how to handle API requests for user actions like signin, registration, logout, and token refresh. It utilizes AJAX handlers and the session component for managing tokens. ```twig title = "User API Page" url = "/api/user/:action" [resetPassword] [account] [session] checkToken = 1 == {% if this.param.action == 'signin' %} {% do response( ajaxHandler('onLogin').withVars({ token: session.token() }) ) %} {% endif %} {% if this.param.action == 'register' %} {% do response(ajaxHandler('onRegister')) %} {% endif %} {% if this.param.action == 'logout' %} {% do response(ajaxHandler('onLogout')) %} {% endif %} {% if this.param.action == 'refresh' %} {% do response({ data: { token: session.token() }}) %} {% endif %} ``` -------------------------------- ### Artisan Commands for User Plugin Upgrade Source: https://github.com/rainlab/user-plugin/blob/master/UPGRADE.md These commands are used to manage the RainLab.User plugin installation and database migration during the upgrade process. Ensure you are running October CMS v3.6 or greater. ```bash php artisan plugin:install rainlab.user php artisan user:migratev1 ``` -------------------------------- ### User API Page Endpoints Source: https://github.com/rainlab/user-plugin/blob/master/docs/auth-bearer-tokens.md This example demonstrates how to build API endpoints using CMS pages to handle user authentication actions like sign-in, registration, logout, and token refresh. ```APIDOC ## User API Page Endpoints This CMS page serves as an API endpoint for user authentication actions. ### URL `/api/user/:action` ### Actions - **signin**: Handles user login. Returns the session token. - **register**: Handles user registration. - **logout**: Handles user logout. - **refresh**: Refreshes the session token. ### Example Implementation ```twig title = "User API Page" url = "/api/user/:action" [resetPassword] [account] [session] checkToken = 1 == {% if this.param.action == 'signin' %} {% do response( ajaxHandler('onLogin').withVars({ token: session.token() }) ) %} {% endif %} {% if this.param.action == 'register' %} {% do response(ajaxHandler('onRegister')) %} {% endif %} {% if this.param.action == 'logout' %} {% do response(ajaxHandler('onLogout')) %} {% endif %} {% if this.param.action == 'refresh' %} {% do response({ data: { token: session.token() }}) %} {% endif %} ``` ``` -------------------------------- ### Email Verification API Source: https://github.com/rainlab/user-plugin/blob/master/docs/auth-bearer-tokens.md This example shows how to implement email verification as an API, supporting 'request' and 'confirm' actions. ```APIDOC ## Email Verification API This CMS page functions as an API for email verification. ### URL `/api/user/verify/:action?request` ### Actions - **request** (default): Requests an email verification. The verification URL in the email can be overridden using `setUrlForEmailVerification()`. The `redirect=0` parameter disables standard redirects. - **confirm**: Confirms the email verification using a one-time bearer token. ### Example Implementation ```twig title = "User Email Verification API" url = "/api/user/verify/:action?request" [account] [session] checkToken = 1 == {% if not session.user %} {% do response({ error: 'Access Denied' }, 403) %} {% endif %} {% if this.param.action == 'request' %} {% do session.user.setUrlForEmailVerification( this|page({ action: 'confirm' }) ~ '?redirect=0' ) %} {% do response(ajaxHandler('onVerifyEmail')) %} {% endif %} {% if this.param.action == 'confirm' %} {% if session.user.hasVerifiedEmail %} {% do response({ success: "Thank you for verifying your email." }, 201) %} {% else %} {% do response({ error: "The provided email verification code was invalid." }, 400) %} {% endif %} {% endif %} ``` ``` -------------------------------- ### Customizing User Authentication with Legacy System (PHP) Source: https://github.com/rainlab/user-plugin/blob/master/docs/events.md This example shows how to hook into the 'rainlab.user.beforeAuthenticate' event to integrate with a legacy authentication system, such as WordPress. It checks credentials against an old hashing method and updates the password to the new October system's format if successful. It receives the authentication component and credentials as arguments. ```php Event::listen('rainlab.user.beforeAuthenticate', function($component, $credentials) { $email = $credentials['email'] ?? null; $password = $credentials['password'] ?? null; // Check that the user exists with the provided email $user = Auth::getProvider()->retrieveByCredentials(['email' => $email]); if (!$user) { return; } // The user is logging in with their old WordPress account // for the first time. Rehash their password using the new // October system. if (WordPressLogin::check($user->password, $password)) { $user->password = $user->password_confirmation = $password; $user->forceSave(); } }); ``` -------------------------------- ### Creating and Managing Users with User Model Source: https://context7.com/rainlab/user-plugin/llms.txt Provides instructions and code examples for creating new users, updating their profiles, accessing user attributes, banning/unbanning users, managing email verification, tracking user activity (online status, last seen), setting/getting user preferences, and handling avatar uploads and thumbnail generation. Uses the RainLab User model and related components. ```php use RainLab\User\Models\User; use RainLab\User\Models\UserGroup; use Validator; // Create new user $user = User::create([ 'first_name' => 'John', 'last_name' => 'Doe', 'email' => 'john@example.com', 'username' => 'johndoe', 'password' => 'SecurePass123!', 'password_confirmation' => 'SecurePass123!' ]); // Update user profile $user->fill([ 'first_name' => 'Jane', 'phone' => '+1234567890', 'company' => 'Acme Inc' ]); $user->save(); // User attributes echo $user->full_name; // "Jane Doe" echo $user->login; // Returns email or username based on settings echo $user->avatar_url; // URL to avatar image // Ban/Unban user $user->ban('Violated terms of service'); if ($user->is_banned) { echo "Banned on: " . $user->banned_at; echo "Reason: " . $user->banned_reason; } $user->unban(); // Email verification if (!$user->hasVerifiedEmail()) { $user->sendEmailVerificationNotification(); } $user->markEmailAsVerified(); // Activity tracking $user->touchLastSeen(); if ($user->isOnline()) { echo "User is currently online"; } echo "Last seen: " . $user->last_seen; // Preferences $user->setPreference('theme', 'dark'); $theme = $user->getPreference('theme', 'light'); // Avatar management $user->avatar = Input::file('avatar'); $user->save(); $thumbUrl = $user->getAvatarThumb(100); // 100x100 thumb ``` -------------------------------- ### Two-Factor Authentication (2FA) API with RainLab User Plugin (PHP) Source: https://context7.com/rainlab/user-plugin/llms.txt This code illustrates how to implement and manage two-factor authentication using the `TwoFactorManager` in the RainLab User Plugin. It covers enabling 2FA by generating secret keys, creating QR code URLs for authenticator apps, generating QR code SVGs, verifying 2FA codes, confirming 2FA setup, generating recovery codes, checking if 2FA is enabled, verifying recovery codes, regenerating recovery codes, and disabling 2FA. It depends on `TwoFactorManager`, `User` model, `Auth` facade, `BaconQrCode` library, and `Str` helper. ```php use RainLabUserClasses\TwoFactorManager; use RainLabUserModelsUser; use BaconQrCode\Renderer\ImageRenderer; use BaconQrCode\Renderer\Image\SvgImageBackEnd; use BaconQrCode\Renderer\RendererStyle\RendererStyle; use BaconQrCode\Writer; $twoFactor = TwoFactorManager::instance(); $user = Auth::user(); // Enable two-factor authentication $secret = $twoFactor->generateSecretKey(); $user->two_factor_secret = $secret; $user->save(); // Generate QR code URL for authenticator app $qrCodeUrl = $twoFactor->qrCodeUrl( 'My Application', $user->email, $secret ); // Generate QR code SVG $renderer = new ImageRenderer( new RendererStyle(200), new SvgImageBackEnd() ); $writer = new Writer($renderer); $qrCodeSvg = $writer->writeString($qrCodeUrl); // Verify 2FA code $userCode = '123456'; // From authenticator app if ($twoFactor->verify($user->two_factor_secret, $userCode)) { // Confirm 2FA setup $user->two_factor_confirmed_at = now(); // Generate recovery codes $recoveryCodes = collect(range(1, 8))->map(function () { return Str::random(10) . '-' . Str::random(10); })->toArray(); $user->two_factor_recovery_codes = encrypt(json_encode($recoveryCodes)); $user->save(); return $recoveryCodes; // Show to user once } else { throw new ValidationException(['code' => 'Invalid authentication code']); } // Check if user has 2FA enabled if ($user->hasTwoFactorEnabled()) { echo "Two-factor authentication is active"; } // Verify recovery code $recoveryCode = 'abc123-def456'; if ($user->replaceRecoveryCode($recoveryCode)) { // Recovery code was valid and has been replaced Auth::login($user); } else { throw new ValidationException(['recovery_code' => 'Invalid recovery code']); } // Regenerate recovery codes $newRecoveryCodes = $user->recoverTwoFactorRecoveryCodes(); // Disable 2FA $user->two_factor_secret = null; $user->two_factor_recovery_codes = null; $user->two_factor_confirmed_at = null; $user->save(); ``` -------------------------------- ### User Authentication Events with RainLab User Plugin (PHP) Source: https://context7.com/rainlab/user-plugin/llms.txt This section details how to hook into various user authentication events provided by the RainLab User Plugin using the `Event` facade. It shows examples for listening to events before authentication, after successful authentication, on user logout, before user registration, and after user registration. These event listeners allow for custom logic such as custom authentication checks, logging user activity, modifying registration data, or sending welcome emails. It utilizes `Event`, `User` model, `Auth`, `Log`, `Request`, and `Mail`. ```php use Event; use RainLabUserModelsUser; // Before authentication Event::listen('rainlab.user.beforeAuthenticate', function ($component, $credentials) { // Custom authentication logic // Return User object to bypass default authentication // Return false to deny authentication // Return null to continue with default authentication if ($credentials['login'] === 'admin@example.com') { return User::findByEmail($credentials['login']); } }); // After successful authentication Event::listen('rainlab.user.authenticate', function ($component) { $user = Auth::user(); Log::info("User {$user->email} logged in from " . Request::ip()); }); // On logout Event::listen('rainlab.user.logout', function ($component, $user) { Log::info("User {$user->email} logged out"); // Custom cleanup logic }); // Before registration Event::listen('rainlab.user.beforeRegister', function ($component, &$input) { // Modify registration data $input['referral_code'] = session('referral'); // Or create user manually return User::create($input); }); // After registration Event::listen('rainlab.user.register', function ($component, $user) { // Send welcome email, assign default roles, etc. Mail::send('welcome', ['user' => $user], function ($message) use ($user) { $message->to($user->email); }); }); ``` -------------------------------- ### User Impersonation with Auth Facade Source: https://context7.com/rainlab/user-plugin/llms.txt Details the user impersonation feature, allowing administrators to temporarily act as other users. Includes starting impersonation, checking if impersonation is active, retrieving the original administrator and the impersonated user, stopping impersonation, and notes on permission requirements and limitations. Requires the Auth facade and RainLab User models. ```php use Auth; use RainLab\User\Models\User; // Start impersonating a user (requires backend authentication) $targetUser = User::find(5); Auth::impersonate($targetUser); // Check if currently impersonating if (Auth::isImpersonator()) { $realAdmin = Auth::getImpersonator(); $impersonatedUser = Auth::user(); echo "Admin {$realAdmin->email} is viewing as {$impersonatedUser->email}"; } // Get the real authenticated user (admin) $realUser = Auth::getRealUser(); // Stop impersonation Auth::stopImpersonate(); // The impersonate method respects permissions: // - User must have 'rainlab.users.impersonate_user' permission // - Cannot impersonate self // - Session is preserved when stopping impersonation ``` -------------------------------- ### Update User Profile using AJAX Source: https://github.com/rainlab/user-plugin/blob/master/docs/component-account.md An example of an HTML form that utilizes the 'onUpdateProfile' AJAX handler provided by the Account component. It allows users to update their first and last names and includes basic form handling attributes for AJAX requests and loading indicators. ```html
``` -------------------------------- ### Email Verification API Example (Twig) Source: https://github.com/rainlab/user-plugin/blob/master/docs/auth-bearer-tokens.md Implements an API endpoint for email verification, supporting 'request' and 'confirm' actions. It allows overriding the verification URL and uses a one-time bearer token for authentication during the confirmation process. ```twig title = "User Email Verification API" url = "/api/user/verify/:action?request" [account] [session] checkToken = 1 == {% if not session.user %} {% do response({ error: 'Access Denied' }, 403) %} {% endif %} {% if this.param.action == 'request' %} {% do session.user.setUrlForEmailVerification( this|page({ action: 'confirm' }) ~ '?redirect=0' ) %} {% do response(ajaxHandler('onVerifyEmail')) %} {% endif %} {% if this.param.action == 'confirm' %} {% if session.user.hasVerifiedEmail %} {% do response({ success: "Thank you for verifying your email." }, 201) %} {% else %} {% do response({ error: "The provided email verification code was invalid." }, 400) %} {% endif %} {% endif %} ``` -------------------------------- ### Get Signed-in User Model Source: https://github.com/rainlab/user-plugin/blob/master/docs/auth-manager.md Retrieves the currently signed-in user's model instance using the Auth facade's 'user' method. ```php // Returns the signed in user $user = Auth::user(); ``` -------------------------------- ### Account Component - User Profile and Security Management (PHP, Twig) Source: https://context7.com/rainlab/user-plugin/llms.txt The Account component enables authenticated users to manage their profile information, including name, email, and avatar. It also handles the setup and management of two-factor authentication, account deletion, and email verification workflows. ```php // Add to your account page [account] isDefault = 1 ``` ```twig {# Update user profile #}
{# Avatar upload #} {% if account.user.avatar %} Remove avatar {% endif %}
{# Two-Factor Authentication Management #} {% if account.twoFactorEnabled %}

Two-factor authentication is enabled

{% if showRecoveryCodes %} {% endif %} {% else %} {% if showConfirmation %}

Scan this QR code with your authenticator app:

{% endif %} {% endif %} {# Delete User Account #}
{# Email Verification #} {% if account.user and not account.user.hasVerifiedEmail %}
Please verify your email address.
{% endif %} ``` -------------------------------- ### Register User Form with Username Field (Twig) Source: https://github.com/rainlab/user-plugin/blob/master/docs/component-registration.md Example of an HTML form using Twig for user registration. It includes fields for full name, email, username, and password. The form is configured to submit registration data via AJAX to the 'onRegister' handler. Additional fields like phone or company can be added. ```twig
``` -------------------------------- ### Custom AJAX Error Handling (JavaScript) Source: https://github.com/rainlab/user-plugin/blob/master/docs/component-registration.md Provides a JavaScript example to customize the default alert box behavior for AJAX errors in October CMS. By listening to the `ajaxErrorMessage` event, developers can implement their own logic, such as logging errors or displaying user-friendly messages, and prevent the default alert. ```javascript ``` -------------------------------- ### Basic Authentication Operations with Auth Facade Source: https://context7.com/rainlab/user-plugin/llms.txt Demonstrates how to perform basic authentication tasks such as attempting login with credentials, direct login, logout, checking authentication status, logging out a specific device, and checking for 'remember me' sessions. Requires the Auth facade and RainLab User models. ```php use Auth; use RainLab\User\Models\User; // Authenticate user by credentials $credentials = [ 'login' => 'user@example.com', 'password' => 'secret123' ]; if (Auth::attempt($credentials, $remember = true)) { $user = Auth::user(); echo "Welcome, " . $user->full_name; } else { throw new ValidationException(['login' => 'Invalid credentials']); } // Login user directly $user = User::find(1); Auth::login($user, $remember = false); // Logout current user Auth::logout(); Request::session()->invalidate(); Request::session()->regenerateToken(); // Check authentication status if (Auth::check()) { $user = Auth::user(); echo "User ID: " . $user->id; } // Logout specific device Auth::logoutCurrentDevice(); // Check if logged in via "remember me" cookie if (Auth::viaRemember()) { echo "User was automatically logged in"; } ``` -------------------------------- ### Create New User Account Source: https://github.com/rainlab/user-plugin/blob/master/docs/auth-manager.md Registers a new user account using the 'create' method on the User model. Requires first name, last name, email, password, and password confirmation. ```php $user = \RainLab\User\Models\User::create([ 'first_name' => 'Some', 'last_name' => 'User', 'email' => 'some@website.tld', 'password' => 'ChangeMe888', 'password_confirmation' => 'ChangeMe888', ]); ``` -------------------------------- ### PHP: Get Real User (Underlying User) via Auth Facade Source: https://github.com/rainlab/user-plugin/blob/master/docs/auth-impersonation.md Retrieves the underlying user when impersonation is active, or the currently logged-in user if no impersonation is in effect. This method is useful for accessing the true user context. ```php $user = Auth::getRealUser(); ``` -------------------------------- ### User Account Creation Email Template Source: https://github.com/rainlab/user-plugin/blob/master/views/mail/invite_email.htm This is a template for an email sent to a new user upon account creation. It includes a personalized greeting, an explanation for the email, a confirmation button with an embedded URL, and information about link expiration. It also provides a raw URL for manual pasting and a partial for styling. ```twig subject = "An Account Has Been Created For You" description = "Invite a new user to the website" == Hello {{ first_name }} You are receiving this email because we received a request to create a new user account for you. If you did not perform this request, you can safely ignore this email. {% partial 'button' url=url body %} Confirm Account {% endpartial %} This confirmation link will expire in {{ count }} minutes. You may attempt this again using our password recovery service. {% partial 'subcopy' body %} If you're having trouble clicking the button, copy the URL below into your browser. {{ url|raw }} {% endpartial %} ``` -------------------------------- ### Basic Authentication Operations Source: https://context7.com/rainlab/user-plugin/llms.txt Handles user authentication using email/password, direct login, logout, and checking authentication status. ```APIDOC ## Basic Authentication Operations ### Description Provides methods for authenticating users via credentials, direct login, logging out, and checking the current authentication state. ### Methods **Authenticate User:** ```php use Auth; use RainLab\User\Models\User; $credentials = [ 'login' => 'user@example.com', 'password' => 'secret123' ]; if (Auth::attempt($credentials, $remember = true)) { $user = Auth::user(); echo "Welcome, " . $user->full_name; } else { throw new ValidationException(['login' => 'Invalid credentials']); } ``` **Login User Directly:** ```php use Auth; use RainLab\User\Models\User; $user = User::find(1); Auth::login($user, $remember = false); ``` **Logout User:** ```php use Auth; use Request; Auth::logout(); Request::session()->invalidate(); Request::session()->regenerateToken(); ``` **Check Authentication Status:** ```php use Auth; if (Auth::check()) { $user = Auth::user(); echo "User ID: " . $user->id; } ``` **Logout Current Device:** ```php use Auth; Auth::logoutCurrentDevice(); ``` **Check "Remember Me" Cookie:** ```php use Auth; if (Auth::viaRemember()) { echo "User was automatically logged in"; } ``` ``` -------------------------------- ### Account Component Configuration Source: https://github.com/rainlab/user-plugin/blob/master/docs/component-account.md This INI configuration block defines the 'Account' component, including its display title and the URL pattern it responds to. The 'isDefault' flag indicates if this component is set as the default for the account page. ```ini title = "Account" url = "/account/:code?" [account] isDefault = 1 ``` -------------------------------- ### User Model - User Management API Source: https://context7.com/rainlab/user-plugin/llms.txt Covers the creation, updating, and management of user profiles, including banning, email verification, and activity tracking. ```APIDOC ## User Model - User Management API ### Description Provides comprehensive functionalities for managing user accounts, including creation, profile updates, status management (ban/unban), email verification, activity tracking, and preference settings. ### Methods **Create New User:** ```php use RainLab\User\Models\User; $user = User::create([ 'first_name' => 'John', 'last_name' => 'Doe', 'email' => 'john@example.com', 'username' => 'johndoe', 'password' => 'SecurePass123!', 'password_confirmation' => 'SecurePass123!' ]); ``` **Update User Profile:** ```php $user->fill([ 'first_name' => 'Jane', 'phone' => '+1234567890', 'company' => 'Acme Inc' ]); $user->save(); ``` **User Attributes:** ```php echo $user->full_name; // "Jane Doe" echo $user->login; // Returns email or username based on settings echo $user->avatar_url; // URL to avatar image ``` **Ban/Unban User:** ```php $user->ban('Violated terms of service'); if ($user->is_banned) { echo "Banned on: " . $user->banned_at; echo "Reason: " . $user->banned_reason; } $user->unban(); ``` **Email Verification:** ```php if (!$user->hasVerifiedEmail()) { $user->sendEmailVerificationNotification(); } $user->markEmailAsVerified(); ``` **Activity Tracking:** ```php $user->touchLastSeen(); if ($user->isOnline()) { echo "User is currently online"; } echo "Last seen: " . $user->last_seen; ``` **Preferences:** ```php $user->setPreference('theme', 'dark'); $theme = $user->getPreference('theme', 'light'); ``` **Avatar Management:** ```php use Input; $user->avatar = Input::file('avatar'); $user->save(); $thumbUrl = $user->getAvatarThumb(100); // 100x100 thumb ``` ``` -------------------------------- ### Authentication Component: Login, 2FA, Password Recovery (PHP) Source: https://context7.com/rainlab/user-plugin/llms.txt This PHP configuration snippet is used to set up the Authentication component. It controls options like asking for 'remember me', enabling two-factor authentication, and enabling password recovery on the login page. ```php // Add to your login page [authentication] rememberMe = "ask" twoFactorAuth = 1 recoverPassword = 1 ``` -------------------------------- ### Create Guest User Source: https://github.com/rainlab/user-plugin/blob/master/docs/auth-manager.md Creates a guest user account using the 'create' method on the User model with the 'is_guest' attribute set to true. Requires at least an email address. ```php $user = \RainLab\User\Models\User::create([ 'first_name' => 'Some', 'last_name' => 'User', 'email' => 'person@acme.tld', 'is_guest' => true ]); ``` -------------------------------- ### Password Management with RainLab User Plugin (PHP) Source: https://context7.com/rainlab/user-plugin/llms.txt This snippet demonstrates various password management functionalities provided by the RainLab User Plugin. It covers password validation against defined rules, changing a user's password securely after verifying the old one, sending password reset links, resetting passwords using a token, and generating random passwords for guest users. It relies on the `User` model, `UserHelper`, `Password` facade, and `Hash` facade. ```php use RainLabUserModelsUser; use RainLabUserHelpersUser as UserHelper; use Password; use Hash; // Validate password against rules $validator = Validator::make( ['password' => 'NewPass123!'], ['password' => UserHelper::passwordRules()] ); // Change password $user = User::find(1); if (Hash::check($oldPassword, $user->password)) { $user->password = $newPassword; $user->password_confirmation = $newPassword; $user->save(); } // Send password reset email $response = Password::sendResetLink(['email' => 'user@example.com']); if ($response === Password::RESET_LINK_SENT) { echo "Password reset email sent"; } // Reset password with token $credentials = [ 'email' => 'user@example.com', 'password' => 'NewPassword123!', 'password_confirmation' => 'NewPassword123!', 'token' => $resetToken ]; $response = Password::reset($credentials, function ($user, $password) { $user->password = $password; $user->save(); }); // Generate random password for guest users $user->generatePassword(); ``` -------------------------------- ### Configure Session Driver for Account Component Source: https://github.com/rainlab/user-plugin/blob/master/docs/component-account.md This configuration snippet shows how to set the session driver to 'database' which is required for the 'onDeleteOtherSessions' functionality. It can be set in the config/session.php file or via the .env file using the SESSION_DRIVER variable. ```php 'driver' => env('SESSION_DRIVER', 'database'), ``` -------------------------------- ### Bearer Token (JWT) Authentication with Auth Facade Source: https://context7.com/rainlab/user-plugin/llms.txt Explains how to generate and use JWT bearer tokens for API authentication. Covers generating tokens for the current or a specific user, authenticating using a token, verifying token validity without authentication, and notes on API endpoint configuration with the session component. Depends on the Auth facade and Request. ```php use Auth; use Request; // Generate JWT token for current user $token = Auth::getBearerToken(); // Generate token for specific user $user = User::findByEmail('user@example.com'); $token = Auth::getBearerToken($user); // Authenticate with bearer token $jwtToken = Request::bearerToken(); if ($user = Auth::loginUsingBearerToken($jwtToken)) { echo "Authenticated as: " . $user->email; } // Verify token without authentication if ($user = Auth::checkBearerToken($token)) { echo "Token valid for: " . $user->email; } else { echo "Invalid or expired token"; } // API endpoint example with session component // In your page template with [session] component: // [session] // checkToken = 1 // This automatically authenticates requests with bearer tokens ``` -------------------------------- ### Manage User Permissions and Impersonation in PHP Source: https://context7.com/rainlab/user-plugin/llms.txt Access backend user information, check permissions for managing users or impersonating them, and perform impersonation using PHP. This is useful for administrative tasks and support scenarios. ```php // Check permissions $backendUser = BackendAuth::user(); if ($backendUser->hasPermission('rainlab.users.access_users')) { // Can manage users } if ($backendUser->hasPermission('rainlab.users.impersonate_user')) { // Can impersonate users $frontendUser = User::find(1); Auth::impersonate($frontendUser); } ``` -------------------------------- ### Authenticate User by Credentials Source: https://github.com/rainlab/user-plugin/blob/master/docs/auth-manager.md Authenticates a user by providing their email and password using the Auth facade's 'attempt' method. Accepts an optional second argument to store a non-expiring cookie. ```php // Authenticate user by credentials $user = Auth::attempt([ 'email' => post('email'), 'password' => post('password') ]); ``` ```php $user = Auth::attempt([...], true); ``` -------------------------------- ### Auth Bearer Tokens API Source: https://github.com/rainlab/user-plugin/blob/master/docs/auth-bearer-tokens.md This section details how to generate and verify bearer tokens (JWT) for user authentication using the Auth component. ```APIDOC ## Auth Bearer Tokens API This API provides functionality for generating and verifying bearer tokens (JWT) for user authentication. ### Generating a Token The `Auth::getBearerToken()` method generates a JWT for the current user, valid for 1 hour by default. A specific user can also be passed to generate a token for them. ```php // Get token for the current user $token = Auth::getBearerToken(); // Get token for a specific user $token = Auth::getBearerToken($user); ``` ### Verifying a Token The `Auth::checkBearerToken($token)` method verifies a given token and returns the associated user if valid, or `false` otherwise. `Auth::loginUsingBearerToken($jwtToken)` verifies and logs in the user if the token is valid. ```php // Verify token and get user $user = Auth::checkBearerToken($token); // Verify token and log in user if ($jwtToken = Request::bearerToken()) { Auth::loginUsingBearerToken($jwtToken); } ``` **Configuration**: Further configuration can be found in `rainlab.user::config.bearer_token`. ``` -------------------------------- ### PHP: Impersonate User with Auth Facade Source: https://github.com/rainlab/user-plugin/blob/master/docs/auth-impersonation.md Impersonates a specified user using the Auth facade. This method requires a user object as input. It is the primary method for initiating user impersonation. ```php Auth::impersonate($user); ``` -------------------------------- ### Convert Guest to Registered User Source: https://github.com/rainlab/user-plugin/blob/master/docs/auth-manager.md Converts an existing guest user to a registered user by calling the 'convertToRegistered' method. This sends an invitation email. The process can be disabled by passing 'false' as an argument. ```php User::where('email', 'person@acme.tld')->first(); $user->convertToRegistered(); ``` ```php $user->convertToRegistered(false); ``` -------------------------------- ### User Groups and Permissions Management Source: https://context7.com/rainlab/user-plugin/llms.txt Details how to manage user group memberships and check permissions. Covers retrieving a user's groups, adding/removing users from specific groups (by model or code string), checking group membership, accessing system-defined groups (guest, registered), and converting guest users to registered users. Uses RainLab User and UserGroup models. ```php use RainLab\User\Models\User; use RainLab\User\Models\UserGroup; // Get user groups $user = User::find(1); $groups = $user->groups; // All groups user belongs to $primaryGroup = $user->primary_group; // Primary group // Add user to group $group = UserGroup::findByCode('premium'); $user->addGroup($group); $user->addGroup('vip'); // Can use code string // Remove from group $user->removeGroup($group); // Check group membership if ($user->inGroup('premium')) { echo "User is premium member"; } // Check primary group only if ($user->inGroup('registered', false)) { echo "Registered user"; } // Get system groups $guestGroup = UserGroup::getGuestGroup(); $registeredGroup = UserGroup::getRegisteredGroup(); // Convert guest to registered if ($user->is_guest) { $user->convertToRegistered($sendNotification = true); } ``` -------------------------------- ### Configure RainLab User Plugin Settings in PHP Source: https://context7.com/rainlab/user-plugin/llms.txt Define and programmatically set plugin configuration options in PHP. This includes settings like login attribute, registration allowance, email activation requirements, and two-factor authentication. ```php // config/rainlab.user::config.php return [ // Login attribute: email or username 'login_attribute' => 'email', // Allow user registration 'allow_registration' => true, // Require email verification 'require_activation' => true, // Notify administrators of new registrations 'notify_admins' => true, 'notify_admin_group' => 'admins', // Force two-factor authentication 'force_two_factor_auth' => false, // Prevent concurrent sessions 'prevent_concurrent_sessions' => false, // Password reset token expiry (minutes) 'password_reset_expiry' => 60, // Bearer token configuration 'bearer_token' => [ 'ttl' => 60, // Token expiry in minutes 'secret' => env('JWT_SECRET'), // JWT signing key ] ]; // Set login attribute programmatically use RainLab\User\Models\Setting; Setting::set('login_attribute', Setting::LOGIN_USERNAME); Setting::set('allow_registration', false); Setting::set('require_activation', true); // Check settings if (Setting::get('allow_registration')) { echo "Registration is open"; } ``` -------------------------------- ### Activate Existing User Source: https://github.com/rainlab/user-plugin/blob/master/docs/auth-manager.md Marks an existing user's email as verified, effectively activating their account. This method is called on the user model instance. ```php // Auto activate this user $user->markEmailAsVerified(); ``` -------------------------------- ### Configure Users Field with Controller Display Mode (YAML) Source: https://github.com/rainlab/user-plugin/blob/master/docs/tailor.md This YAML configuration sets the 'users' content field to use the 'controller' display mode for a more advanced user management interface. It supports associating with an unlimited number of users (`maxItems: 0`). This leverages the `RainLab\User\ContentFields\UsersField` class. ```yaml users: label: Users type: users maxItems: 0 displayMode: controller ``` -------------------------------- ### Restrict Page Access with Session Component Configuration Source: https://github.com/rainlab/user-plugin/blob/master/docs/component-session.md Configures page access restrictions using INI format. The 'security' property can be set to 'user', 'guest', or 'all' to control who can access the page. The 'redirect' property specifies a page to redirect to if access is denied. ```ini title = "Restricted page" url = "/users-only" [session] security = "user" redirect = "home" ``` -------------------------------- ### Configure Users Field with Taglist Display Mode (YAML) Source: https://github.com/rainlab/user-plugin/blob/master/docs/tailor.md This configuration enables the 'taglist' display mode for the 'users' content field, allowing users to be selected by their email address. It supports unlimited user associations (`maxItems: 0`) and uses the `RainLab\User\ContentFields\UsersField` class. ```yaml users: label: Users type: users maxItems: 0 displayMode: taglist ``` -------------------------------- ### Enable Token Verification with Session Component Configuration Source: https://github.com/rainlab/user-plugin/blob/master/docs/component-session.md Enables the verification of supplied bearer tokens in request headers. When 'checkToken' is set to '1', the component will validate tokens provided in the 'Authorization: Bearer TOKEN' header. ```ini [session] checkToken = 1 ``` -------------------------------- ### User Groups and Permissions Source: https://context7.com/rainlab/user-plugin/llms.txt Manages user group memberships, including adding, removing, checking group status, and accessing system-defined groups. ```APIDOC ## User Groups and Permissions ### Description Provides functionalities for managing user group memberships, allowing users to be added to or removed from groups, checking their group affiliations, and accessing predefined system groups like guest and registered. ### Methods **Get User Groups:** ```php use RainLab\User\Models\User; $user = User::find(1); $groups = $user->groups; // All groups user belongs to $primaryGroup = $user->primary_group; // Primary group ``` **Add User to Group:** ```php use RainLab\User\Models\UserGroup; // By object $group = UserGroup::findByCode('premium'); $user->addGroup($group); // By code string $user->addGroup('vip'); ``` **Remove User from Group:** ```php $user->removeGroup($group); ``` **Check Group Membership:** ```php // Check any group membership if ($user->inGroup('premium')) { echo "User is premium member"; } // Check primary group only if ($user->inGroup('registered', false)) { echo "Registered user"; } ``` **Get System Groups:** ```php use RainLab\User\Models\UserGroup; $guestGroup = UserGroup::getGuestGroup(); $registeredGroup = UserGroup::getRegisteredGroup(); ``` **Convert Guest to Registered User:** ```php if ($user->is_guest) { $user->convertToRegistered($sendNotification = true); } ``` ``` -------------------------------- ### Configure Users Field for Single User Association (YAML) Source: https://github.com/rainlab/user-plugin/blob/master/docs/tailor.md This configuration sets up a 'users' content field in Tailor to associate with a single user, effectively creating a 'belongs to' relationship. It utilizes the `RainLab\User\ContentFields\UsersField` class and requires no external dependencies beyond Tailor and the User plugin. ```yaml users: label: Users type: users maxItems: 1 ``` -------------------------------- ### Registration Component Form (Twig) Source: https://context7.com/rainlab/user-plugin/llms.txt This Twig template defines the user registration form. It includes fields for name, email, and password, with password confirmation. The form submits data via AJAX to the onRegister backend handler and redirects upon success. ```twig
{% if helper.showUsername %} {% endif %}
{# Check if registration is allowed #} {% if not registration.canRegister %}

Registration is currently closed.

{% endif %} ``` -------------------------------- ### Import and Export Users using PHP Source: https://context7.com/rainlab/user-plugin/llms.txt Utilize PHP classes to export user data to CSV files and import user data from CSV files. This functionality is essential for bulk user management operations. ```php use RainLab\User\Models\User\UserExport; use RainLab\User\Models\User\UserImport; // Export users to CSV $export = new UserExport(); $export->export('users.csv'); // Import users from CSV $import = new UserImport(); $import->import('users.csv'); ``` -------------------------------- ### ResetPassword Component Configuration (PHP) Source: https://context7.com/rainlab/user-plugin/llms.txt This PHP configuration sets the ResetPassword component as the default for the password reset page. It's essential for initiating the password reset flow. ```php // Add to your password reset page [resetPassword] isDefault = 1 ``` -------------------------------- ### Configure Users Field for Unlimited Users (YAML) Source: https://github.com/rainlab/user-plugin/blob/master/docs/tailor.md This configuration allows associating an unlimited number of users with a Tailor content field, implementing a 'belongs to many' relationship. The `maxItems: 0` setting enables this functionality. It relies on the `RainLab\User\ContentFields\UsersField` class. ```yaml users: label: Users type: users maxItems: 0 ```