### Install MkDocs and Plugins Source: https://github.com/codeigniter4/shield/blob/develop/admin/how_to_build_docs.md Installs MkDocs and essential plugins for documentation generation and management. ```console pip3 install mkdocs pip3 install mkdocs-material pip3 install mkdocs-git-revision-date-localized-plugin pip3 install mkdocs-redirects ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/codeigniter4/shield/blob/develop/admin/how_to_build_docs.md Starts a local development server to preview the documentation with live reloading. ```console mkdocs serve ``` -------------------------------- ### Run Shield Initial Setup Command Source: https://github.com/codeigniter4/shield/blob/develop/docs/getting_started/install.md Execute this command to perform the initial setup for CodeIgniter Shield, which includes several configuration steps. ```bash php spark shield:setup ``` -------------------------------- ### Install firebase/php-jwt Source: https://github.com/codeigniter4/shield/blob/develop/docs/addons/jwt.md Install the necessary JWT library using Composer. This is a prerequisite for using JWT authentication. ```bash composer require firebase/php-jwt:^6.4 ``` -------------------------------- ### Setup Default Auth Routes Source: https://github.com/codeigniter4/shield/blob/develop/docs/getting_started/install.md Include the default authentication routes in your app/Config/Routes.php file using the auth service. ```php service('auth')->routes($routes); ``` -------------------------------- ### Install CodeIgniter Shield Source: https://context7.com/codeigniter4/shield/llms.txt Install Shield via Composer and run the setup command to configure your CodeIgniter 4 application with authentication capabilities. ```bash composer require codeigniter4/shield php spark shield:setup php spark migrate --all ``` -------------------------------- ### Login Validation Rules Configuration Source: https://github.com/codeigniter4/shield/blob/develop/docs/customization/validation_rules.md Example of defining custom validation rules for the login form in `app/Config/Validation.php`. This example shows rules for email and password. ```php //-------------------------------------------------------------------- // Rules For Login //-------------------------------------------------------------------- public $login = [ // 'username' => [ // 'label' => 'Auth.username', // 'rules' => [ // 'required', // 'max_length[30]', // 'min_length[3]', // 'regex_match[/\A[a-zA-Z0-9.]+\Z/]', // ], // ], 'email' => [ 'label' => 'Auth.email', 'rules' => [ 'required', 'max_length[254]', 'valid_email' ], ], 'password' => [ 'label' => 'Auth.password', 'rules' => [ 'required', 'max_byte[72]', ], 'errors' => [ 'max_byte' => 'Auth.errorPasswordTooLongBytes', ] ], ]; ``` -------------------------------- ### Install CodeIgniter Shield Source: https://github.com/codeigniter4/shield/blob/develop/README.md Install Shield using Composer. Ensure you have CodeIgniter 4.3.5+ and PHP 8.1+. ```bash composer require codeigniter4/shield ``` -------------------------------- ### Configure Authenticators in Config\Auth Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authentication/authentication.md Defines the available authenticators and the default authenticator to be used. Ensure the class names are correct for your setup. ```php public array $authenticators = [ // alias => classname 'session' => Session::class, 'tokens' => AccessTokens::class, 'hmac' => HmacSha256::class, // 'jwt' => JWT::class, ]; ``` ```php public string $defaultAuthenticator = 'session'; ``` -------------------------------- ### Custom Registration Validation Rules Configuration Source: https://github.com/codeigniter4/shield/blob/develop/docs/customization/validation_rules.md Example of how to define custom registration validation rules in `app/Config/Validation.php`. Ensure table names match your database schema if customized. ```php //-------------------------------------------------------------------- // Rules For Registration //-------------------------------------------------------------------- public $registration = [ 'username' => [ 'label' => 'Auth.username', 'rules' => [ 'required', 'max_length[30]', 'min_length[3]', 'regex_match[/\A[a-zA-Z0-9.]+\Z/]', 'is_unique[users.username]', ], ], 'email' => [ 'label' => 'Auth.email', 'rules' => [ 'required', 'max_length[254]', 'valid_email', 'is_unique[auth_identities.secret]', ], ], 'password' => [ 'label' => 'Auth.password', 'rules' => 'required|max_byte[72]|strong_password[]', 'errors' => [ 'max_byte' => 'Auth.errorPasswordTooLongBytes' ] ], 'password_confirm' => [ 'label' => 'Auth.passwordConfirm', 'rules' => 'required|matches[password]', ], ]; ``` -------------------------------- ### Configure Route Filters for Token Protection Source: https://github.com/codeigniter4/shield/blob/develop/docs/guides/api_tokens.md Protect API routes by configuring the 'tokens' filter in app/Config/Filters.php. This example protects all routes under the '/api' group. ```php public $filters = [ 'tokens' => ['before' => ['api/*']], ]; ``` -------------------------------- ### Customize Login Redirect with Permissions Source: https://github.com/codeigniter4/shield/blob/develop/docs/customization/redirect_urls.md Implement custom login redirects based on user permissions using the `loginRedirect()` method. This example redirects users with 'admin.access' permission to '/admin', otherwise uses the configured login redirect. ```php public function loginRedirect(): string { if (auth()->user()->can('admin.access')) { return '/admin'; } $url = setting('Auth.redirects')['login']; return $this->getUrl($url); } ``` -------------------------------- ### Get Help for Shield CLI User Commands Source: https://github.com/codeigniter4/shield/blob/develop/docs/user_management/managing_users.md Display help information for the Shield user management CLI commands. This command provides details on how to use each specific user-related command. ```console php spark shield:user --help ``` -------------------------------- ### cURL Request for JWT Issuance Source: https://github.com/codeigniter4/shield/blob/develop/docs/addons/jwt.md Example cURL command to send user credentials for JWT authentication. Replace placeholder values with actual user email and password. ```curl curl --location 'http://localhost:8080/auth/jwt' \ --header 'Content-Type: application/json' \ --data-raw '{"email" : "admin@example.jp" , "password" : "passw0rd!"}' ``` -------------------------------- ### Manage Users with CodeIgniter Shield CLI Commands Source: https://context7.com/codeigniter4/shield/llms.txt This section lists various `spark` commands provided by CodeIgniter Shield for managing users, including creating, listing, activating, deactivating, changing details, deleting users, and managing groups. It also includes commands for HMAC key management and initial setup. ```bash # User management commands php spark shield:user create # Create a new user interactively php spark shield:user list # List all users php spark shield:user activate # Activate a user php spark shield:user deactivate # Deactivate a user php spark shield:user changename # Change username php spark shield:user changeemail # Change email php spark shield:user password # Change password php spark shield:user delete # Delete a user php spark shield:user addgroup # Add user to group php spark shield:user removegroup # Remove user from group # HMAC key management php spark shield:hmac invalidateAll # Invalidate all HMAC keys for all users php spark shield:hmac reencrypt # Re-encrypt all HMAC keys with new encryption key # Setup and help php spark shield:setup # Initial Shield setup php spark shield:user --help # Show help for user commands ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/codeigniter4/shield/blob/develop/admin/how_to_build_docs.md Generates the static documentation files for local viewing or deployment. ```console mkdocs build ``` -------------------------------- ### Run Database Migrations Source: https://github.com/codeigniter4/shield/blob/develop/docs/customization/adding_attributes_to_users.md Execute this command to apply pending database migrations. Verify the table structure using the `db:table` command. ```console php spark migrate ``` ```console php spark db:table users ``` -------------------------------- ### Get User's Group Memberships Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authorization.md Retrieve a list of all groups the user is currently a member of. ```php $user->getGroups(); ``` -------------------------------- ### Configure Autoload Helpers Source: https://github.com/codeigniter4/shield/blob/develop/docs/getting_started/install.md Add the 'auth' and 'setting' helpers to your app/Config/Autoload.php file to make them available globally. ```php public $helpers = ['auth', 'setting']; ``` -------------------------------- ### Find and List Users Source: https://context7.com/codeigniter4/shield/llms.txt Demonstrates finding users by ID or credentials. Preloads identity, group, and permission data for efficient listing of multiple users. ```php getProvider(); // Find by ID $user = $users->findById(123); // Find by credentials $user = $users->findByCredentials(['email' => 'john@example.com']); // List users with preloaded data (optimized for lists) $userList = $users ->withIdentities() // Preload email identities ->withGroups() // Preload groups ->withPermissions() // Preload permissions ->findAll(20); // Get 20 users // Now these don't trigger extra queries foreach ($userList as $u) { echo $u->email; // From preloaded identities $u->inGroup('admin'); // From preloaded groups $u->can('users.delete'); // From preloaded permissions } return view('users/list', ['users' => $userList]); } } ``` -------------------------------- ### Get Ban Reason Source: https://github.com/codeigniter4/shield/blob/develop/docs/user_management/banning_users.md Retrieve the reason for a user's ban using the `getBanMessage()` method on the User entity. ```php $user->getBanMessage(); ``` -------------------------------- ### Deploy Documentation Manually Source: https://github.com/codeigniter4/shield/blob/develop/admin/how_to_build_docs.md Deploys the built documentation to GitHub Pages. This is an alternative to the automated GitHub Actions deployment. ```console mkdocs gh-deploy ``` -------------------------------- ### Trigger and Listen to 'register' Event Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/events.md Use this to trigger the 'register' event when a new user registers, or to listen for it using a class and method. ```php Events::trigger('register', $user); ``` ```php Events::on('register', 'SomeLibrary::handleRegister'); ``` -------------------------------- ### Attempt Login with Credentials Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authentication/session.md Use this method to attempt a user login with their email and password. It returns a Result object indicating success or failure. ```php $credentials = [ 'email' => $this->request->getPost('email'), 'password' => $this->request->getPost('password') ]; $loginAttempt = auth()->attempt($credentials); if (! $loginAttempt->isOK()) { return redirect()->back()->with('error', $loginAttempt->reason()); } ``` -------------------------------- ### Get User Provider Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authentication/authentication.md Retrieves the user provider instance, which is typically the UserModel by default. This allows for direct interaction with user data management. ```php // get the User Provider (UserModel by default) $users = auth()->getProvider(); ``` -------------------------------- ### Create Migration to Add User Attributes Source: https://github.com/codeigniter4/shield/blob/develop/docs/customization/adding_attributes_to_users.md Use this command to generate a migration file for adding new columns to the users table. Implement the `up` method to add columns and the `down` method to remove them. ```console php spark make:migration AddMobileNumberToUsers ``` -------------------------------- ### Get User's Direct Permissions Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authorization.md Retrieve a list of all permissions assigned directly to the user. This method does not include permissions granted through group memberships. ```php $user->getPermissions(); ``` -------------------------------- ### Create a New User Source: https://github.com/codeigniter4/shield/blob/develop/docs/user_management/managing_users.md Instantiate a new User entity, set its properties including username, email, and password, save it to the database, and add it to the default group. Ensure the username is set even if null. ```php use CodeIgniter\Shield\Entities\User; // Get the User Provider (UserModel by default) $users = auth()->getProvider(); $user = new User([ 'username' => 'foo-bar', 'email' => 'foo.bar@example.com', 'password' => 'secret plain text password', ]); $users->save($user); // To get the complete user object with ID, we need to get from the database $user = $users->findById($users->getInsertID()); // Add to default group $users->addToDefaultGroup($user); ``` -------------------------------- ### Apply JWT Filter in Filters Config Source: https://github.com/codeigniter4/shield/blob/develop/docs/addons/jwt.md Configure the JWT filter in app/Config/Filters.php to protect specific routes or route groups. This example protects all routes under '/api'. ```php public $filters = [ 'jwt' => ['before' => ['api', 'api/*']], ]; ``` -------------------------------- ### Run All Database Migrations Source: https://github.com/codeigniter4/shield/blob/develop/docs/getting_started/install.md Execute this command to apply all pending database migrations, including those for CodeIgniter Shield. ```bash php spark migrate --all ``` -------------------------------- ### Configure HMAC Filter in Filters.php Source: https://github.com/codeigniter4/shield/blob/develop/docs/guides/api_hmac_keys.md Specify routes to be protected by the HMAC filter within the `$filters` array in app/Config/Filters.php. This example protects all routes under the '/api' group. ```php public $filters = [ 'hmac' => ['before' => ['api/*']], ]; ``` -------------------------------- ### Prepare Release Branch and Update Version Source: https://github.com/codeigniter4/shield/blob/develop/admin/RELEASE.md This command prepares the release by creating a new branch and updating the version number in the Auth.php file. The changes are committed and pushed to the origin. ```bash php admin/prepare-release.php 1.x.x ``` -------------------------------- ### Get Current User Entity Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authentication/authentication.md Retrieves the current user's entity object using the auth() helper function. This is useful for accessing user-specific data. ```php // get the current user $user = auth()->user(); ``` -------------------------------- ### Assign Wildcard Permissions to Groups Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authorization.md Utilize wildcards in the `$matrix` property to grant all permissions within a specific scope to a group. For example, 'users.*' grants all user-related actions. ```php public array $matrix = [ 'superadmin' => ['admin.*', 'users.*', 'beta.*'], ]; ``` -------------------------------- ### Configure Default Authentication Actions Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authentication/auth_actions.md Set the default authentication actions for registration and login in the Auth config file. Use null to disable an action. ```php public array $actions = [ 'register' => null, 'login' => null, ]; ``` -------------------------------- ### Shield User Management CLI Commands Source: https://github.com/codeigniter4/shield/blob/develop/docs/user_management/managing_users.md Overview of available commands for managing users via the command line interface. Use `php spark shield:user --help` for detailed usage instructions for each command. ```text create: Create a new user activate: Activate a user deactivate: Deactivate a user changename: Change user name changeemail: Change user email delete: Delete a user password: Change a user password list: List users addgroup: Add a user to a group removegroup: Remove a user from a group ``` -------------------------------- ### Trigger and Listen to 'login' Event Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/events.md Use this to trigger the 'login' event after a successful login, or to listen for it using a class and method. ```php Events::trigger('login', $user); ``` ```php Events::on('login', 'SomeLibrary::handleLogin'); ``` -------------------------------- ### List Users with Preloaded Data Source: https://github.com/codeigniter4/shield/blob/develop/docs/user_management/managing_users.md Fetch a list of users, optimizing performance by preloading associated identities, groups, and permissions using `withIdentities()`, `withGroups()`, and `withPermissions()`. This avoids N+1 query problems. ```php // Get the User Provider (UserModel by default) $users = auth()->getProvider(); $usersList = $users ->withIdentities() ->withGroups() ->withPermissions() ->findAll(10); // The below code would normally trigger an additional // DB queries, on every loop iteration, but now it won't foreach ($usersList as $u) { // Because identities are preloaded echo $u->email; // Because groups are preloaded $u->inGroup('admin'); // Because permissions are preloaded $u->hasPermission('users.delete'); // Because groups and permissions are preloaded $u->can('users.delete'); } ``` -------------------------------- ### Retrieve HMAC Keys Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authentication/hmac.md Methods for retrieving HMAC keys include `getHmacToken` by key, `getHmacTokenById` by database ID, and `hmacTokens` to get all tokens as an array of AccessToken instances. ```php // Retrieve a set of HMAC Token/Keys by key $token = $user->getHmacToken($key); ``` ```php // Retrieve an HMAC token/keys by its database ID $token = $user->getHmacTokenById($id); ``` ```php // Retrieve all HMAC tokens as an array of AccessToken instances. $tokens = $user->hmacTokens(); ``` -------------------------------- ### Retrieve Access Tokens Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authentication/tokens.md Provides methods to retrieve user access tokens by their raw token value, database ID, or to get all access tokens associated with the user. ```php // Retrieve a single token by plain text token $token = $user->getAccessToken($rawToken); ``` ```php // Retrieve a single token by it's database ID $token = $user->getAccessTokenById($id); ``` ```php // Retrieve all access tokens as an array of AccessToken instances. $tokens = $user->accessTokens(); ``` -------------------------------- ### Configure Password Validators Source: https://github.com/codeigniter4/shield/blob/develop/docs/getting_started/concepts.md Define which password validators are active by listing their class names in the `$passwordValidators` array within `Config\Auth`. This example shows the default validators, with `PwnedValidator` commented out. ```php public array $passwordValidators = [ CompositionValidator::class, NothingPersonalValidator::class, DictionaryValidator::class, // PwnedValidator::class, ]; ``` -------------------------------- ### Define Available Permissions Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authorization.md List all available permissions in the `AuthGroups.php` config file. Permissions are defined as strings combining a scope and an action (e.g., 'users.create'), with optional descriptions. ```php public array $permissions = [ 'admin.access' => 'Can access the sites admin area', 'admin.settings' => 'Can access the main site settings', 'users.manage-admins' => 'Can manage other admins', 'users.create' => 'Can create new non-admin users', 'users.edit' => 'Can edit existing non-admin users', 'users.delete' => 'Can delete existing non-admin users', 'beta.access' => 'Can access beta-level features' ]; ``` -------------------------------- ### Create a New User Source: https://context7.com/codeigniter4/shield/llms.txt Use the User Provider to create a new user, set their initial password, and add them to the default group. Retrieves the user ID after saving. ```php getProvider(); $user = new User([ 'username' => 'johndoe', 'email' => 'john@example.com', 'password' => 'secretPassword123' ]); $users->save($user); // Get the complete user with ID $user = $users->findById($users->getInsertID()); // Add to default group $users->addToDefaultGroup($user); return redirect()->to('/admin/users')->with('message', 'User created'); } } ``` -------------------------------- ### Customize Login Redirect URL Source: https://github.com/codeigniter4/shield/blob/develop/docs/customization/redirect_urls.md Override the default login redirect by implementing the `loginRedirect()` method in `app/Config/Auth.php`. This example redirects admins to '/admin' and others to a configured login redirect URL. ```php public function loginRedirect(): string { $url = auth()->user()->inGroup('admin') ? '/admin' : setting('Auth.redirects')['login']; return $this->getUrl($url); } ``` -------------------------------- ### Route Authorization with Filters Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authorization.md Demonstrates how to apply 'group' and 'permission' filters to routes and route groups to control access. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of new users within the system. It requires specific user details in the request body. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address for the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201) - **id** (integer) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. - **created_at** (string) - Timestamp of when the user was created. #### Response Example ```json { "id": 1, "username": "johndoe", "email": "john.doe@example.com", "created_at": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Customize Login Form Input Field Source: https://github.com/codeigniter4/shield/blob/develop/docs/customization/login_identifier.md Modify the HTML of your custom login view to use the new identifier field name. This example shows how to change the 'email' input to 'employee_id'. ```html
``` -------------------------------- ### Get Current User ID Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authentication/authentication.md Obtains the current user's ID using either the auth() helper or the dedicated user_id() function. This is a common requirement for tracking user actions. ```php // get the current user's id $user_id = auth()->id(); // or $user_id = user_id(); ``` -------------------------------- ### Configure HMAC Settings via Environment Variables Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authentication/hmac.md Set HMAC encryption keys and the current key using JSON strings in environment variables or the .env file. This allows for secure management of sensitive configuration. ```dotenv authtoken.hmacEncryptionKeys = '{"k1":{"key":"hex2bin:923dfab5ddca0c7784c2c388a848a704f5e048736c1a852c862959da62ade8c7"},"k2":{"key":"hex2bin:451df599363b19be1434605fff8556a0bbfc50bede1bb33793dcde4d97fce4b0"}}' authtoken.hmacEncryptionCurrentKey = k2 ``` -------------------------------- ### cURL Request with JWT Authorization Header Source: https://github.com/codeigniter4/shield/blob/develop/docs/addons/jwt.md Example cURL command to make a protected API request using the issued JWT in the Authorization header. Replace the placeholder JWT with a valid token. ```curl curl --location --request GET 'http://localhost:8080/api/users' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJTaGllbGQgVGVzdCBBcHAiLCJzdWIiOiIxIiwiaWF0IjoxNjgxODA1OTMwLCJleHAiOjE2ODE4MDk1MzB9.DGpOmRPOBe45whVtEOSt53qJTw_CpH0V8oMoI_gm2XI' ``` -------------------------------- ### Configure Auth Routes Source: https://context7.com/codeigniter4/shield/llms.txt Add Shield's authentication routes to your application by calling the routes helper in your Routes.php configuration file. You can include all default routes or exclude specific ones to customize them. ```php // app/Config/Routes.php routes($routes); // Or exclude specific routes you want to customize service('auth')->routes($routes, ['except' => ['login', 'register']]); // Then add your custom routes $routes->get('login', '\App\Controllers\Auth\LoginController::loginView'); $routes->post('login', '\App\Controllers\Auth\LoginController::loginAction'); ``` -------------------------------- ### Making an API Request with HMAC-SHA256 Authentication Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authentication/hmac.md This example uses the CodeIgniter CURLRequest class to make a POST request with the Authorization header set for HMAC-SHA256 authentication. Ensure the secret key is kept secure. ```php setHeader('Authorization', "HMAC-SHA256 {$key}:{$hashValue}") ->setBody($requestBody) ->request('POST', 'https://example.com/api'); ``` -------------------------------- ### Define Route for Mobile Login Source: https://github.com/codeigniter4/shield/blob/develop/docs/guides/mobile_apps.md Set up a POST route to handle login requests from mobile devices. ```php // Routes.php $routes->post('auth/token', '\App\Controllers\Auth\LoginController::mobileLogin'); ``` -------------------------------- ### User Activation Status Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authorization.md Explains how to check and manage the activation status of a user. ```APIDOC ## User Activation ### Description Manages the activation status of a user, which is relevant when using activation actions like `EmailActivation`. ### Checking Activation Status #### isActivated() Checks if the user has been activated. ```php if ($user->isActivated()) { // User is active } ``` #### isNotActivated() Checks if the user has not yet been activated. ```php if ($user->isNotActivated()) { // User is not active } ``` ### Activating a User #### activate() Manually activates the user. ```php $user->activate(); ``` ### Deactivating a User #### deactivate() Manually deactivates the user. ```php $user->deactivate(); ``` ``` -------------------------------- ### Get Current User Information Source: https://context7.com/codeigniter4/shield/llms.txt Use the auth helper to access the currently authenticated user's information from anywhere in your application. Check login status, retrieve the user entity, user ID, or specific properties like email and username. ```php loggedIn()) { return redirect()->to('/login'); } // Get current user entity $user = auth()->user(); // Get just the user ID $userId = auth()->id(); // Or use the helper function $userId = user_id(); // Access user properties $email = $user->email; $username = $user->username; // Get the User Provider (UserModel) $userProvider = auth()->getProvider(); return view('dashboard', [ 'user' => $user, 'userId' => $userId ]); } } ``` -------------------------------- ### Generate Access Token with Scopes Source: https://github.com/codeigniter4/shield/blob/develop/docs/guides/api_tokens.md Generate an access token for a user and assign specific permissions (scopes) to it. The raw token is returned. ```php return $user->generateAccessToken('token-name', ['users-read'])->raw_token; ``` -------------------------------- ### Implement Mobile Login Controller Source: https://github.com/codeigniter4/shield/blob/develop/docs/guides/mobile_apps.md Handles mobile app authentication, validates credentials, and generates an access token. Ensure the 'device_name' is provided in the request. ```php config('Auth')->emailValidationRules, 'password' => [ 'label' => 'Auth.password', 'rules' => 'required', ], 'device_name' => [ 'label' => 'Device Name', 'rules' => 'required|string', ], ]; if (! $this->validateData($this->request->getPost(), $rules, [], config('Auth')->DBGroup)) { return $this->response ->setJSON(['errors' => $this->validator->getErrors()]) ->setStatusCode(401); } // Get the credentials for login $credentials = $this->request->getPost(setting('Auth.validFields')); $credentials = array_filter($credentials); $credentials['password'] = $this->request->getPost('password'); // Attempt to login $result = auth()->attempt($credentials); if (! $result->isOK()) { return $this->response ->setJSON(['error' => $result->reason()]) ->setStatusCode(401); } // Generate token and return to client $token = auth()->user()->generateAccessToken(service('request')->getVar('device_name')); return $this->response ->setJSON(['token' => $token->raw_token]); } } ``` -------------------------------- ### Define Available User Groups Source: https://github.com/codeigniter4/shield/blob/develop/docs/quick_start_guide/using_authorization.md Configure the available user groups by adding entries to the `$groups` property in `app/Config/AuthGroups.php`. Each group can have a title and description. ```php public array $groups = [ 'superadmin' => [ 'title' => 'Super Admin', 'description' => 'Complete control of the site.', ], // ]; ``` -------------------------------- ### JWT Login Controller Source: https://github.com/codeigniter4/shield/blob/develop/docs/addons/jwt.md A sample controller that authenticates users with provided credentials and issues a JWT upon success. It handles validation, authentication checks, and JWT generation. ```php getValidationRules(); // Validate credentials if (! $this->validateData($this->request->getJSON(true), $rules, [], config('Auth')->DBGroup)) { return $this->fail( ['errors' => $this->validator->getErrors()], $this->codes['unauthorized'] ); } // Get the credentials for login $credentials = $this->request->getJsonVar(setting('Auth.validFields')); $credentials = array_filter($credentials); $credentials['password'] = $this->request->getJsonVar('password'); /** @var Session $authenticator */ $authenticator = auth('session')->getAuthenticator(); // Check the credentials $result = $authenticator->check($credentials); // Credentials mismatch. if (! $result->isOK()) { // @TODO Record a failed login attempt return $this->failUnauthorized($result->reason()); } // Credentials match. // @TODO Record a successful login attempt $user = $result->extraInfo(); /** @var JWTManager $manager */ $manager = service('jwtmanager'); // Generate JWT and return to client $jwt = $manager->generateToken($user); return $this->respond([ 'access_token' => $jwt, ]); } /** * Returns the rules that should be used for validation. * * @return array|string>> * @phpstan-return array>> */ protected function getValidationRules(): array { $rules = new ValidationRules(); return $rules->getLoginRules(); } } ``` -------------------------------- ### Listen to 'failedLogin' Event Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/events.md Listen for the 'failedLogin' event to handle failed login attempts. It provides an array of credentials, excluding the password. ```php // Original credentials array $credentials = ['email' => 'foo@example.com', 'password' => 'secret123']; Events::on('failedLogin', function($credentials) { dd($credentials); }); // Outputs: ['email' => 'foo@example.com']; ``` ```php ['magicLinkToken' => 'the token value used'] ``` -------------------------------- ### Configure Authentication View Paths Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authentication/auth_actions.md Define the view paths for various authentication action pages within the Auth config file's $views array. This allows customization of the user interface for actions like email 2FA and account activation. ```php public $views = [ 'action_email_2fa' => '\CodeIgniter\Shield\Views\email_2fa_show', 'action_email_2fa_verify' => '\CodeIgniter\Shield\Views\email_2fa_verify', 'action_email_2fa_email' => '\CodeIgniter\Shield\Views\Email\email_2fa_email', 'action_email_activate_show' => '\CodeIgniter\Shield\Views\email_activate_show', 'action_email_activate_email' => '\CodeIgniter\Shield\Views\Email\email_activate_email', ]; ``` -------------------------------- ### Generate and Return Access Token Source: https://github.com/codeigniter4/shield/blob/develop/docs/guides/api_tokens.md Generate an access token for a user and return its raw value. This is typically done within a route definition. ```php $routes->get('access/token', static function() { $token = auth()->user()->generateAccessToken(service('request')->getVar('token_name')); return json_encode(['token' => $token->raw_token]); }); ``` -------------------------------- ### Login Attempt Logging Configuration Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authentication/tokens.md Configure whether to log failed, all, or no login attempts. ```APIDOC ## Login Attempt Logging ### Description By default, only failed login attempts are recorded in the `auth_token_logins` table. This can be modified by changing the `$recordLoginAttempt` value. ### Configuration Options - `Auth::RECORD_LOGIN_ATTEMPT_FAILURE`: Logs only failed login attempts (default). - `Auth::RECORD_LOGIN_ATTEMPT_NONE`: Logs no login attempts. - `Auth::RECORD_LOGIN_ATTEMPT_ALL`: Logs all login attempts. ### Code Example ```php public int $recordLoginAttempt = Auth::RECORD_LOGIN_ATTEMPT_FAILURE; ``` ### Logged Data When a failed login attempt is logged, the raw token value sent is saved in the `identifier` column. When a successful login attempt is logged, the token name is saved in the `identifier` column. ``` -------------------------------- ### Define Available Permissions Source: https://github.com/codeigniter4/shield/blob/develop/docs/quick_start_guide/using_authorization.md Define the site's permissions in the `AuthGroups` config file under the `$permissions` property. Permissions are strings combining context and permission, separated by a decimal point. ```php public array $permissions = [ 'admin.access' => 'Can access the sites admin area', 'admin.settings' => 'Can access the main site settings', 'users.manage-admins' => 'Can manage other admins', 'users.create' => 'Can create new non-admin users', 'users.edit' => 'Can edit existing non-admin users', 'users.delete' => 'Can delete existing non-admin users', 'beta.access' => 'Can access beta-level features', ]; ``` -------------------------------- ### Set HMAC Encryption Keys and Defaults Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authentication/hmac.md Configure the HMAC encryption keys, current key, default driver, and default digest in app/Config/AuthToken.php. Ensure your encryption key is properly formatted. ```php public $hmacEncryptionKeys = [ 'k1' => [ 'key' => 'hex2bin:923dfab5ddca0c7784c2c388a848a704f5e048736c1a852c862959da62ade8c7', ], ]; public string $hmacEncryptionCurrentKey = 'k1'; public string $hmacEncryptionDefaultDriver = 'OpenSSL'; public string $hmacEncryptionDefaultDigest = 'SHA512'; ``` -------------------------------- ### Enable Account Activation via Email Source: https://github.com/codeigniter4/shield/blob/develop/docs/quick_start_guide/using_session_auth.md Set the 'register' action in the `Auth::$actions` array to `EmailActivator::class` to enable email-based account activation. Ensure email configuration in `app/Config/Email.php` is complete. ```php public array $actions = [ 'register' => \CodeIgniter\Shield\Authentication\Actions\EmailActivator::class, 'login' => null, ]; ``` -------------------------------- ### Listen to 'magicLogin' Event Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/events.md Listen for the 'magicLogin' event, which fires after a successful magic link login. The authenticated user can be accessed via the auth() helper. ```php Events::on('magicLogin', function() { $user = auth()->user(); // }) ``` -------------------------------- ### Generate Custom UserModel with CLI Source: https://github.com/codeigniter4/shield/blob/develop/docs/customization/user_provider.md Use the Shield CLI to quickly generate a custom UserModel class. The class name is optional; if omitted, 'UserModel' will be used. ```bash php spark shield:model UserModel ``` -------------------------------- ### Enable Magic Link Logins Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/magic_link_login.md Set this boolean to true in `app/Config/Auth.php` to enable the magic link login functionality. ```php public bool $allowMagicLinkLogins = true; ``` -------------------------------- ### User Authentication Methods Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authentication/session.md Provides methods for attempting login, checking credentials, verifying login status, and logging out users. ```APIDOC ## POST /api/login (Simulated) ### Description Attempts to log in a user with provided credentials. Supports a secure remember-me feature. ### Method POST ### Endpoint (Simulated - typically handled by framework routing) ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ### Request Example ```json { "email": "user@example.com", "password": "your_password" } ``` ### Response #### Success Response (200) - **user** (object) - The authenticated user object. - **message** (string) - Success message. #### Response Example ```json { "user": { "id": 1, "email": "user@example.com" }, "message": "Login successful." } ``` ## POST /api/check (Simulated) ### Description Checks if provided credentials are valid without logging the user in. ### Method POST ### Endpoint (Simulated - typically handled by framework routing) ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ### Request Example ```json { "email": "user@example.com", "password": "your_password" } ``` ### Response #### Success Response (200) - **isValid** (boolean) - True if credentials are valid, false otherwise. - **user** (object) - The user object if credentials are valid. #### Response Example ```json { "isValid": true, "user": { "id": 1, "email": "user@example.com" } } ``` ## GET /api/check-login-status (Simulated) ### Description Checks if a user is currently logged in. ### Method GET ### Endpoint (Simulated - typically handled by framework routing) ### Response #### Success Response (200) - **isLoggedIn** (boolean) - True if the user is logged in, false otherwise. #### Response Example ```json { "isLoggedIn": true } ``` ## POST /api/logout (Simulated) ### Description Logs the current user out of the session. ### Method POST ### Endpoint (Simulated - typically handled by framework routing) ### Response #### Success Response (200) - **message** (string) - Success message indicating logout. #### Response Example ```json { "message": "Logout successful." } ``` ## POST /api/remember-me (Simulated) ### Description Attempts to log in a user and sets a secure remember-me cookie. ### Method POST ### Endpoint (Simulated - typically handled by framework routing) ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ### Request Example ```json { "email": "user@example.com", "password": "your_password" } ``` ### Response #### Success Response (200) - **user** (object) - The authenticated user object. - **message** (string) - Success message. #### Response Example ```json { "user": { "id": 1, "email": "user@example.com" }, "message": "Login successful with remember-me." } ``` ## POST /api/forget-remember (Simulated) ### Description Purges all remember-me tokens for the current user. ### Method POST ### Endpoint (Simulated - typically handled by framework routing) ### Response #### Success Response (200) - **message** (string) - Success message indicating remember-me tokens were purged. #### Response Example ```json { "message": "Remember-me tokens purged." } ``` ``` -------------------------------- ### Subscribe to Magic Login Event Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/magic_link_login.md Listen for the 'magicLogin' event, which is fired after a successful magic link authentication. No data is passed to the event, but the current user can be accessed via helpers. ```php Events::on('magicLogin', static function () { // ... }); ``` -------------------------------- ### Generate Access Token with Scopes Source: https://github.com/codeigniter4/shield/blob/develop/docs/references/authentication/tokens.md Generates an access token with specific scopes, which act as permissions. A wildcard scope '*' grants access to all permissions. ```php $token = $user->generateAccessToken('Work Laptop', ['posts.manage', 'forums.manage']); ``` ```php $token = $user->generateAccessToken('Work Laptop', ['*']); ``` -------------------------------- ### Benchmark Password Hashing Cost Source: https://github.com/codeigniter4/shield/blob/develop/docs/guides/strengthen_password.md This code benchmarks your server to find an appropriate cost for PASSWORD_BCRYPT hashing, aiming for a stretching time of 50 milliseconds or less. It helps determine the highest cost that balances security with performance for interactive logins. ```php $cost]); $end = microtime(true); } while (($end - $start) < $timeTarget); echo "Appropriate Cost Found: " . $cost; ``` -------------------------------- ### Configure Email Settings Source: https://github.com/codeigniter4/shield/blob/develop/docs/getting_started/install.md Update your app/Config/Email.php configuration to allow Shield to send emails. Set the 'fromEmail' and 'fromName' properties. ```php request->getJSON(true); /** @var Session $authenticator */ $authenticator = auth('session')->getAuthenticator(); // Verify credentials $result = $authenticator->check([ 'email' => $credentials['email'], 'password' => $credentials['password'] ]); if (! $result->isOK()) { return $this->failUnauthorized($result->reason()); } $user = $result->extraInfo(); /** @var JWTManager $manager */ $manager = service('jwtmanager'); // Generate JWT with custom claims $jwt = $manager->generateToken($user, [ 'email' => $user->email, 'roles' => $user->getGroups() ]); return $this->respond([ 'access_token' => $jwt, 'token_type' => 'Bearer', 'expires_in' => config('AuthJWT')->timeToLive ]); } public function generateArbitraryToken() { /** @var JWTManager $manager */ $manager = service('jwtmanager'); // Generate JWT with custom payload (1 day TTL) $jwt = $manager->issue([ 'user_id' => '123', 'permissions' => ['read', 'write'] ], DAY); return $this->respond(['token' => $jwt]); } } // Example curl request: // curl -X POST http://localhost:8080/auth/jwt \ // -H "Content-Type: application/json" \ // -d '{"email":"user@example.com","password":"secret123"}' // Using the JWT: // curl -X GET http://localhost:8080/api/protected \ // -H "Authorization: Bearer eyJ0eXAiOiJKV1Qi..." ``` -------------------------------- ### Extend Auth Configuration Source: https://github.com/codeigniter4/shield/blob/develop/docs/getting_started/install.md Copy the default Auth.php configuration file and extend the CodeIgniter Shield Auth class. Ensure the namespace is set to 'Config'. ```php get('login', '\App\Controllers\Auth\LoginController::loginView'); $routes->get('register', '\App\Controllers\Auth\RegisterController::registerView'); ```