### Start Barcode Buddy Websocket Server Source: https://github.com/forceu/barcodebuddy/wiki/2.0-Installation Execute this command in your installation folder to start the websocket server. This enables the Screen module and automatic refreshes on changes. ```bash php wsserver.php ``` -------------------------------- ### Example: Show Inventory for Product via URL Source: https://github.com/forceu/barcodebuddy/wiki/3.0-Usage This example demonstrates how to display the current stock for a specific product ('Pizza' with barcode '123456') in the 'inventory' mode. ```bash https://your.webhost.com/barcodebuddy/index.php?showui&add=123456&mode=inventory ``` -------------------------------- ### Install PHP-HTTP via Composer Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/http/README.md Install the library using Composer, the recommended method. Ensure you include the Composer autoloader in your project. ```bash $ composer require delight-im/http ``` ```php require __DIR__.'/vendor/autoload.php'; ``` -------------------------------- ### Install PHP-Base64 via Composer Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/base64/README.md Install the library using Composer. Ensure you have PHP 5.3.0 or higher. ```bash $ composer require delight-im/base64 ``` -------------------------------- ### Enable and Start Barcode Buddy Services Source: https://github.com/forceu/barcodebuddy/blob/master/example/README.md Copy the systemd service scripts to /etc/systemd/system, adjust paths, reload the daemon, and then enable and start the grabInput and websocket services. ```bash systemctl daemon-reload systemctl enable --now bbuddy-grabInput.service systemctl enable --now bbuddy-websocket.service ``` -------------------------------- ### Install PHP-DB via Composer Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/db/README.md Use Composer to add the delight-im/db library to your project dependencies. ```bash composer require delight-im/db ``` -------------------------------- ### Install PHP-Cookie via Composer Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/cookie/README.md Include the delight-im/cookie library in your project using Composer. ```bash $ composer require delight-im/cookie ``` -------------------------------- ### Throttle Resource with IP Address Tracking Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Example of how to include an IP address in the resource description for more granular throttling. ```php [ 'my-resource-name', $_SERVER['REMOTE_ADDR'] ] ``` -------------------------------- ### Set Web Server Folder Permissions (Linux) Source: https://github.com/forceu/barcodebuddy/wiki/2.0-Installation Ensure the web server has the necessary permissions to create the database file. Replace '/path/to/the/barcodebuddy/folder' with your actual installation path. ```bash sudo chown www-data:www-data -R /path/to/the/barcodebuddy/folder ``` -------------------------------- ### Start Session with Custom SameSite Restriction Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/cookie/README.md Start or resume a session with a specified SameSite cookie restriction. Supports 'Lax', 'Strict', or 'None' (for Chrome 80+). ```php // start session and have session cookie with 'lax' same-site restriction \Delight\Cookie\Session::start(); // or \Delight\Cookie\Session::start('Lax'); // start session and have session cookie with 'strict' same-site restriction \Delight\Cookie\Session::start('Strict'); // start session and have session cookie without any same-site restriction \Delight\Cookie\Session::start(null); // or \Delight\Cookie\Session::start('None'); // Chrome 80+ ``` -------------------------------- ### Listing Available Roles Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Provides examples of accessing predefined role constants within the ` Delight Auth Role` class. These constants represent standard roles available in the system. ```php \Delight\Auth\Role::ADMIN; \Delight\Auth\Role::AUTHOR; \Delight\Auth\Role::COLLABORATOR; \Delight\Auth\Role::CONSULTANT; \Delight\Auth\Role::CONSUMER; \Delight\Auth\Role::CONTRIBUTOR; \Delight\Auth\Role::COORDINATOR; \Delight\Auth\Role::CREATOR; \Delight\Auth\Role::DEVELOPER; \Delight\Auth\Role::DIRECTOR; \Delight\Auth\Role::EDITOR; \Delight\Auth\Role::EMPLOYEE; \Delight\Auth\Role::MAINTAINER; \Delight\Auth\Role::MANAGER; \Delight\Auth\Role::MODERATOR; \Delight\Auth\Role::PUBLISHER; \Delight\Auth\Role::REVIEWER; \Delight\Auth\Role::SUBSCRIBER; \Delight\Auth\Role::SUPER_ADMIN; \Delight\Auth\Role::SUPER_EDITOR; \Delight\Auth\Role::SUPER_MODERATOR; \Delight\Auth\Role::TRANSLATOR; ``` -------------------------------- ### Install Delight Auth via Composer Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Include the library in your PHP project using Composer. This command adds the delight-im/auth package to your project's dependencies. ```bash composer require delight-im/auth ``` -------------------------------- ### Run grabInput.sh Script Source: https://github.com/forceu/barcodebuddy/blob/master/example/README.md This bash script is recommended for most scanners and is used for the docker image. Ensure the SCRIPT_LOCATION variable points to your Barcode Buddy installation. ```bash bash grabInput.sh /dev/input/eventX ``` -------------------------------- ### Start Websocket Server in Background (Linux) Source: https://github.com/forceu/barcodebuddy/wiki/2.0-Installation Run the websocket server in the background using nohup and the ampersand. This command is an alternative to using the 'screen' application for background processes. ```bash nohup php wsserver.php & ``` -------------------------------- ### Get Database Server and Client Information Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/db/README.md Retrieve the database driver name, server information (like uptime, threads, questions), server version, and client version. ```php $db->getDriverName(); // e.g. 'MySQL' $db->getServerInfo(); // e.g. 'Uptime: 82196 Threads: 1 Questions: 2840 Slow queries: 0 Opens: 23 Flush tables: 1 Open tables: 33 Queries per second avg: 0.736' $db->getServerVersion(); // e.g. '5.5.5-10.1.13-MariaDB' $db->getClientVersion(); // e.g. 'mysqlnd 5.0.1-dev' ``` -------------------------------- ### Getting All Roles for a User by ID Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Retrieves a list of all roles assigned to a user identified by their unique ID. ```php $auth->admin()->getRolesForUserById($userId); ``` -------------------------------- ### Retrieving All User Roles Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Shows how to get a list of all roles assigned to the current user using the `getRoles` method. This is useful for displaying user privileges or performing complex role-based logic. ```php $auth->getRoles(); ``` -------------------------------- ### Initiate Password Reset Request Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Starts the password reset process by sending an email with a selector and token to the user. Handles exceptions for invalid emails, unverified emails, disabled resets, or too many requests. ```PHP try { $auth->forgotPassword($_POST['email'], function ($selector, $token) { // send `$selector` and `$token` to the user (e.g. via email) }); // request has been generated } catch (Delight\Auth\InvalidEmailException $e) { // invalid email address } catch (Delight\Auth\EmailNotVerifiedException $e) { // email not verified } catch (Delight\Auth\ResetDisabledException $e) { // password reset is disabled } catch (Delight\Auth\TooManyRequestsException $e) { // too many requests } ``` -------------------------------- ### Add Barcode via URL Source: https://github.com/forceu/barcodebuddy/wiki/3.0-Usage Add a single barcode by making a GET request to the Barcode Buddy index.php script. This method is useful for integrations where direct script execution is not possible. ```bash https://your.webhost.com/barcodebuddy/index.php?add=123456789 ``` -------------------------------- ### Connect to Database using PdoDataSource Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/db/README.md Establish a database connection by configuring a PdoDataSource object and then creating a PdoDatabase instance from it. Connections are lazy. ```php $dataSource = new Delight\Db\PdoDataSource('mysql'); // see "Available drivers for database systems" below $dataSource->setHostname('localhost'); $dataSource->setPort(3306); $dataSource->setDatabaseName('my-database'); $dataSource->setCharset('utf8mb4'); $dataSource->setUsername('my-username'); $dataSource->setPassword('my-password'); $db = Delight\Db\PdoDatabase::fromDataSource($dataSource); ``` -------------------------------- ### Get Current Session ID Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/cookie/README.md Retrieve the current internal session ID. ```php \Delight\Cookie\Session::id(); ``` -------------------------------- ### Get User IP Address Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Retrieves the IP address from which the current user logged in. ```php $ip = $auth->getIpAddress(); ``` -------------------------------- ### Retrieving the Remember Me Cookie Name Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Gets the name of the optional cookie used for persistent logins. ```php \Delight\Auth\Auth::createRememberCookieName(); ``` -------------------------------- ### Update Docker Image and Run New Instance Source: https://github.com/forceu/barcodebuddy/wiki/2.1-Installation:-Updating-Barcode-Buddy Update the Docker image and restart the Barcode Buddy container. Ensure to mount the configuration volume. ```bash docker pull f0rc3/barcodebuddy-docker:latest ``` ```bash docker run -d -v bbconfig:/config -p 80:80 -p 443:443 f0rc3/barcodebuddy-docker:latest ``` -------------------------------- ### Retrieving the Session Cookie Name Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Gets the name of the mandatory session cookie used by the library. ```php \session_name(); ``` -------------------------------- ### User Registration with Email Verification Callback Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Register a new user with email, password, and an optional username. A callback function is provided to handle sending the verification selector and token to the user. ```php try { $userId = $auth->register($_POST['email'], $_POST['password'], $_POST['username'], function ($selector, $token) { // send `$selector` and `$token` to the user (e.g. via email) }); // we have signed up a new user with the ID `$userId` } catch ( Delight\Auth\InvalidEmailException $e) { // invalid email address } catch ( Delight\Auth\InvalidPasswordException $e) { // invalid password } catch ( Delight\Auth\UserAlreadyExistsException $e) { // user already exists } catch ( Delight\Auth\TooManyRequestsException $e) { // too many requests } ``` -------------------------------- ### Get User Email Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Retrieves the email address of the currently logged-in user. Returns `null` if no user is signed in. ```php $email = $auth->getEmail(); ``` -------------------------------- ### Auth Constructor Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Initializes the Auth class with a database connection and optional parameters for IP address, table prefix, throttling, session resync interval, and schema. ```APIDOC ## Auth Constructor ### Description Initializes the Auth class with a database connection. ### Parameters - **$db** (PDO|PdoDsn) - Required - A PDO connection object or a PdoDsn instance. - **$ipAddress** (string) - Optional - The user's real IP address if behind a proxy. Defaults to ` $_SERVER['REMOTE_ADDR']`. - **$dbTablePrefix** (string) - Optional - A prefix for database tables. Defaults to an empty string. - **$throttling** (bool|false) - Optional - Disables request limiting if set to `false`. Enabled by default. - **$sessionResyncInterval** (int) - Optional - Custom interval in seconds for session resynchronization. Defaults to five minutes. - **$dbSchema** (string) - Optional - A qualifier for database tables (e.g., schema name). Defaults to null. ``` -------------------------------- ### Create User Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Creates a new user account with the provided email, password, and an optional username. ```APIDOC ## Create User ### Description Creates a new user account with the provided email, password, and an optional username. ### Method ```php $auth->admin()->createUser(string $email, string $password, ?string $username = null): int ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php try { $userId = $auth->admin()->createUser($_POST['email'], $_POST['password'], $_POST['username']); // we have signed up a new user with the ID `$userId` } catch ( \Delight\Auth\InvalidEmailException $e) { // invalid email address } catch ( \Delight\Auth\InvalidPasswordException $e) { // invalid password } catch ( \Delight\Auth\UserAlreadyExistsException $e) { // user already exists } ``` ### Response #### Success Response (200) - **int** - The ID of the newly created user. #### Response Example ```php 12345 ``` ### Error Handling - **InvalidEmailException**: Thrown if the provided email address is invalid. - **InvalidPasswordException**: Thrown if the provided password is invalid. - **UserAlreadyExistsException**: Thrown if a user with the provided email already exists. ``` -------------------------------- ### Select Single Column Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/db/README.md Retrieve all values from a specific column across multiple rows. Useful for getting lists of data. ```php $column = $db->selectColumn( 'SELECT author FROM books ORDER BY copies DESC LIMIT ?, ?', [ 0, 3 ] ); ``` -------------------------------- ### Create New User Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Creates a new user account with the provided email, password, and an optional username. Catches exceptions for invalid input or existing users. ```php try { $userId = $auth->admin()->createUser($_POST['email'], $_POST['password'], $_POST['username']); // we have signed up a new user with the ID `$userId` } catch ( \Delight\Auth\InvalidEmailException $e) { // invalid email address } catch ( \Delight\Auth\InvalidPasswordException $e) { // invalid password } catch ( \Delight\Auth\UserAlreadyExistsException $e) { // user already exists } ``` -------------------------------- ### Read a Cookie Value Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/cookie/README.md Retrieve the value of a cookie using the static get method. An optional default value can be provided. ```php \Delight\Cookie\Cookie::get('first_visit'); // or \Delight\Cookie\Cookie::get('first_visit', \time()); ``` -------------------------------- ### Retrieve a Response Header Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/http/README.md Get the value of a specific response header. An optional value prefix can be provided to filter results. ```php \Delight\Http\ResponseHeader::get('Content-type') ``` ```php \Delight\Http\ResponseHeader::get('Content-type', 'text/') ``` -------------------------------- ### Register User Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Registers a new user with email, password, and an optional username. Includes a callback for sending verification details. ```APIDOC ## Register User ### Description Registers a new user with email, password, and an optional username. A callback function is provided for sending verification details. ### Method `Auth::register(string $email, string $password, string $username = null, callable $verify = null)` ### Parameters - **$email** (string) - Required - The user's email address. - **$password** (string) - Required - The user's password. - **$username** (string|null) - Optional - The user's username. Can be `null` if not managing usernames. - **$verify** (callable) - Optional - A closure to send verification details (selector and token) to the user. ### Exceptions - ` Delight\Auth\InvalidEmailException` - If the email address is invalid. - ` Delight\Auth\InvalidPasswordException` - If the password is invalid. - ` Delight\Auth\UserAlreadyExistsException` - If a user with the provided email already exists. - ` Delight\Auth\TooManyRequestsException` - If too many requests have been made. ### Example ```php try { $userId = $auth->register($_POST['email'], $_POST['password'], $_POST['username'], function ($selector, $token) { // send `$selector` and `$token` to the user (e.g. via email) $url = 'https://www.example.com/verify_email?selector=' . urlencode($selector) . '&token=' . urlencode($token); // ... send email ... }); // User registered successfully with ID: $userId } catch ( Delight\Auth\InvalidEmailException $e) { // Handle invalid email } catch ( Delight\Auth\InvalidPasswordException $e) { // Handle invalid password } catch ( Delight\Auth\UserAlreadyExistsException $e) { // Handle user already exists } catch ( Delight\Auth\TooManyRequestsException $e) { // Handle too many requests } ``` ``` -------------------------------- ### Creating a New Auth Instance with PDO Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Instantiate the Auth class using an existing PDO connection. Ensure the database user has necessary privileges. Optional parameters include IP address, table prefix, throttling, session resync interval, and schema. ```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'); // or $db = new Delight\Auth\PdoDsn('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password'); // or $db = new Delight\Auth\PdoDsn('pgsql:dbname=my-database;host=localhost;port=5432', 'my-username', 'my-password'); // or $db = new Delight\Auth\PdoDsn('sqlite:../Databases/my-database.sqlite'); $auth = new Delight\Auth\Auth($db); ``` -------------------------------- ### Retrieve Profiler Measurements Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/db/README.md Get all recorded query measurements from the profiler. The measurements can be sorted, typically to list the longest-running queries first. ```php $db->getProfiler()->getMeasurements(); ``` ```php $db->getProfiler()->sort(); ``` -------------------------------- ### Retrieve and Remove a Response Header Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/http/README.md Get the value of a response header and remove it from the collection simultaneously. An optional value prefix can be provided. ```php \Delight\Http\ResponseHeader::take('Set-Cookie') ``` ```php \Delight\Http\ResponseHeader::take('Set-Cookie', 'mysession=') ``` -------------------------------- ### Create and Configure Cookie using Builder Pattern Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/cookie/README.md Instantiate the Cookie class to build a cookie by setting individual properties with reasonable defaults. ```php $cookie = new \Delight\Cookie\Cookie('SID'); $cookie->setValue('31d4d96e407aad42'); $cookie->setMaxAge(60 * 60 * 24); // $cookie->setExpiryTime(time() + 60 * 60 * 24); $cookie->setPath('/~rasmus/'); $cookie->setDomain('example.com'); $cookie->setHttpOnly(true); $cookie->setSecureOnly(true); $cookie->setSameSiteRestriction('Strict'); // echo $cookie; $cookie->save(); ``` -------------------------------- ### Get Username Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Retrieves the username of the currently logged-in user. Usernames are optional and only available if provided during registration. Returns `null` if no user is signed in. ```php $email = $auth->getUsername(); ``` -------------------------------- ### Enable Performance Profiling Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/db/README.md Enable performance profiling to monitor query execution times during development. Use a SimpleProfiler instance. ```php $db->setProfiler(new Delight\Db\SimpleProfiler()); ``` -------------------------------- ### Chain Cookie Configuration and Save Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/cookie/README.md Configure cookie properties and save the cookie using method chaining for a more concise syntax. ```php (new \Delight\Cookie\Cookie('SID'))->setValue('31d4d96e407aad42')->setMaxAge(60 * 60 * 24)->setSameSiteRestriction('None')->save(); ``` -------------------------------- ### Session Management Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/cookie/README.md Manages PHP sessions with improved cookie handling, including starting sessions with specific SameSite restrictions and regenerating session IDs. ```APIDOC ## ` Delight\Cookie\Session::start(string $sameSite = null) ` ### Description Starts or resumes a session with improved cookie handling. Allows specifying the SameSite attribute for the session cookie. ### Method `start` ### Parameters #### Path Parameters - **sameSite** (string|null) - Optional - The SameSite attribute for the session cookie ('Strict', 'Lax', 'None'). If null, it defaults to PHP's session settings. ``` ```APIDOC ## ` Delight\Cookie\Session::regenerate(bool $deleteOldSession = false) ` ### Description Regenerates the current session ID, providing protection against session fixation attacks with improved cookie handling. ### Method `regenerate` ### Parameters #### Path Parameters - **deleteOldSession** (bool) - Optional - If true, the old session ID will be deleted. Defaults to false. ``` ```APIDOC ## ` Delight\Cookie\Session::id() ` ### Description Retrieves the current internal session ID. ### Method `id` ``` -------------------------------- ### Get User ID Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Retrieves the unique identifier for the currently logged-in user. Returns `null` if no user is signed in. An alias `$auth->id()` is available. ```php $id = $auth->getUserId(); ``` -------------------------------- ### Login with Email Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Handles user login using email and password. Catches specific exceptions for invalid credentials, unverified emails, or too many requests. ```PHP try { $auth->login($_POST['email'], $_POST['password']); // user is logged in } catch (\Delight\Auth\InvalidEmailException $e) { // wrong email address } catch (Delight\Auth\InvalidPasswordException $e) { // wrong password } catch (Delight\Auth\EmailNotVerifiedException $e) { // email not verified } catch (Delight\Auth\TooManyRequestsException $e) { // too many requests } ``` -------------------------------- ### Get Last Inserted ID Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/db/README.md Retrieve the ID of the last inserted row. An optional sequence name can be provided for databases that require it (e.g., PostgreSQL). ```php $newId = $db->getLastInsertId(); ``` ```php $newId = $db->getLastInsertId('my-sequence-name'); ``` -------------------------------- ### Retrieving Role Maps, Names, and Values Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Demonstrates methods to retrieve role information in different formats: a map, an array of names, or an array of values. Useful for introspection or dynamic role management. ```php \Delight\Auth\Role::getMap(); // or \Delight\Auth\Role::getNames(); // or \Delight\Auth\Role::getValues(); ``` -------------------------------- ### Connect to Database using DSN Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/db/README.md Create a database connection directly from a Data Source Name (DSN) string, username, and password. This is efficient if you do not need a separate PDO instance. Connections are lazy. ```php $db = Delight\Db\PdoDatabase::fromDsn( new Delight\Db\PdoDsn( 'mysql:dbname=my-database;host=localhost', 'my-username', 'my-password' ) ); ``` -------------------------------- ### Login (sign in) Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Authenticates a user using their email and password. Handles various exceptions like invalid credentials, unverified emails, and excessive requests. ```APIDOC ## Login (sign in) ### Description Authenticates a user using their email and password. Handles various exceptions like invalid credentials, unverified emails, and excessive requests. ### Method POST ### Endpoint `/auth/login` ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. - **rememberDuration** (int|null) - Optional - Duration in seconds for a persistent login (e.g., `60 * 60 * 24 * 365.25` for one year). Defaults to `null` for session-only login. ### Response #### Success Response (200) Indicates successful login. #### Error Responses - **InvalidEmailException**: Wrong email address. - **InvalidPasswordException**: Wrong password. - **EmailNotVerifiedException**: Email not verified. - **TooManyRequestsException**: Too many requests. ``` -------------------------------- ### Implementing Centralized Permissions Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Illustrates a pattern for managing permissions by abstracting role checks into dedicated functions. This approach centralizes access control logic, making it easier to manage and audit. ```php function canEditArticle(\Delight\Auth\Auth $auth) { return $auth->hasAnyRole( \Delight\Auth\Role::MODERATOR, \Delight\Auth\Role::SUPER_MODERATOR, \Delight\Auth\Role::ADMIN, \Delight\Auth\Role::SUPER_ADMIN ); } // ... if (canEditArticle($auth)) { // the user can edit articles here } // ... if (canEditArticle($auth)) { // ... and here } // ... if (canEditArticle($auth)) { // ... and here } ``` -------------------------------- ### Add Barcode and Show UI via URL Source: https://github.com/forceu/barcodebuddy/wiki/3.0-Usage This URL combines adding a barcode with displaying the Barcode Buddy user interface. Useful for interactive barcode entry and immediate feedback. ```bash https://your.webhost.com/barcodebuddy/index.php?showui&add=123456789 ``` -------------------------------- ### Available Database Drivers Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/db/README.md Constants for specifying database drivers when using PdoDataSource. ```php Delight\Db\PdoDataSource::DRIVER_NAME_MYSQL; Delight\Db\PdoDataSource::DRIVER_NAME_POSTGRESQL; Delight\Db\PdoDataSource::DRIVER_NAME_SQLITE; ``` -------------------------------- ### Register Connection Established Listener Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/db/README.md Add a listener that will be executed when a database connection is successfully established. The listener receives the PdoDatabase instance as an argument. ```php $db->addOnConnectListener(function ( Delight\\Db\\[PdoDatabase](https://github.com/delight-im/PHP-PDO-Database/blob/master/src/PdoDatabase.php) $db) { // do something }); ``` -------------------------------- ### Transactions Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/db/README.md Provides methods to manage database transactions. You can start a transaction with `beginTransaction`, commit changes with `commit`, or roll back changes with `rollBack`. The `isTransactionActive` method checks if a transaction is currently active. ```APIDOC ## TRANSACTIONS ### Description Manages database transactions. ### Methods * `beginTransaction()`: Starts a new database transaction. * `commit()`: Commits the current transaction. * `rollBack()`: Rolls back the current transaction. * `isTransactionActive()`: Returns `true` if a transaction is active, `false` otherwise. ``` -------------------------------- ### Login with Username Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Authenticates a user using their username and password. Similar to email login but with username-specific exceptions. ```APIDOC ## Login with Username ### Description Authenticates a user using their username and password. Similar to email login but with username-specific exceptions. ### Method POST ### Endpoint `/auth/loginWithUsername` ### Parameters #### Request Body - **username** (string) - Required - The user's username. - **password** (string) - Required - The user's password. - **rememberDuration** (int|null) - Optional - Duration in seconds for a persistent login. Defaults to `null`. ### Response #### Success Response (200) Indicates successful login. #### Error Responses - **UnknownUsernameException**: The username does not exist. - **AmbiguousUsernameException**: The username is not unique. - **InvalidPasswordException**: Wrong password. - **EmailNotVerifiedException**: Email not verified. - **TooManyRequestsException**: Too many requests. ``` -------------------------------- ### Defining Custom Role Aliases Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Shows how to create custom role names by aliasing existing ` Delight Auth Role` constants within your own namespace. This allows for more domain-specific role terminology. ```php namespace My\Namespace; final class MyRole { const CUSTOMER_SERVICE_AGENT = \Delight\Auth\Role::REVIEWER; const FINANCIAL_DIRECTOR = \Delight\Auth\Role::COORDINATOR; private function __construct() {} } // Usage: // \My\Namespace\MyRole::CUSTOMER_SERVICE_AGENT; // \My\Namespace\MyRole::FINANCIAL_DIRECTOR; ``` -------------------------------- ### Connect using Existing PDO Instance Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/db/README.md Reuse an existing PDO instance to create a PdoDatabase object, avoiding a new connection. Optionally preserve the original PDO instance's state. ```php // $pdo = new PDO('mysql:dbname=my-database;host=localhost;charset=utf8mb4', 'my-username', 'my-password'); $db = Delight\Db\PdoDatabase::fromPdo($pdo); ``` ```php $db = Delight\Db\PdoDatabase::fromPdo($pdo, true); ``` -------------------------------- ### Verify Password Reset Attempt with Exceptions Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Verifies a password reset attempt using a selector and token, throwing specific exceptions for different error conditions. Use this when detailed error handling is required. ```php try { $auth->canResetPasswordOrThrow($_GET['selector'], $_GET['token']); // put the selector into a `hidden` field (or keep it in the URL) // put the token into a `hidden` field (or keep it in the URL) // ask the user for their new password } catch (\ Delight\\Auth\\InvalidSelectorTokenPairException $e) { // invalid token } catch (\ Delight\\Auth\\TokenExpiredException $e) { // token expired } catch (\ Delight\\Auth\\ResetDisabledException $e) { // password reset is disabled } catch (\ Delight\\Auth\\TooManyRequestsException $e) { // too many requests } ``` -------------------------------- ### Listeners Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/db/README.md Allows registering listeners for specific database events, such as connection establishment. The `addOnConnectListener` method registers a callback function to be executed when a connection is successfully established. ```APIDOC ## LISTENERS ### Description Registers callbacks for database events. ### Method `addOnConnectListener(callable $listener)`: Adds a listener that will be called when a database connection is established. ``` -------------------------------- ### Server and Client Information Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/db/README.md Provides methods to retrieve information about the database server and the PHP database client. Methods include `getDriverName`, `getServerInfo`, `getServerVersion`, and `getClientVersion`. ```APIDOC ## SERVER AND CLIENT INFORMATION ### Description Retrieves information about the database server and client. ### Methods * `getDriverName()`: Returns the name of the database driver (e.g., 'MySQL'). * `getServerInfo()`: Returns general information about the database server. * `getServerVersion()`: Returns the version of the database server. * `getClientVersion()`: Returns the version of the database client used by PHP. ``` -------------------------------- ### Checking User Roles Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Demonstrates how to check if a user has specific roles using `hasRole`, `hasAnyRole`, and `hasAllRoles` methods. Useful for enforcing access control based on user privileges. ```php if ($auth->hasRole(\Delight\Auth\Role::SUPER_MODERATOR)) { // the user is a super moderator } // or if ($auth->hasAnyRole(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER)) { // the user is either a developer, or a manager, or both } // or if ($auth->hasAllRoles(\Delight\Auth\Role::DEVELOPER, \Delight\Auth\Role::MANAGER)) { // the user is both a developer and a manager } ``` -------------------------------- ### Logging in as a User by Email Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Impersonates a user by their email address, logging them into the current session. Catches exceptions for invalid emails or unverified email addresses. ```php try { $auth->admin()->logInAsUserByEmail($_POST['email']); } catch ( Delight\Auth InvalidEmailException $e) { // unknown email address } catch ( Delight\Auth EmailNotVerifiedException $e) { // email address not verified } ``` -------------------------------- ### Implement Custom Password Requirements Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md This snippet demonstrates how to wrap custom password validation logic around the library's registration call. It 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); } ``` -------------------------------- ### Include Composer Autoloader Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/cookie/README.md Include the Composer autoloader file to enable class autoloading. ```php require __DIR__ . '/vendor/autoload.php'; ``` -------------------------------- ### Logging in as a User by Username Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Impersonates a user by their username, logging them into the current session. Catches exceptions for unknown/ambiguous usernames or unverified email addresses. ```php try { $auth->admin()->logInAsUserByUsername($_POST['username']); } catch ( Delight\Auth UnknownUsernameException $e) { // unknown username } catch ( Delight\Auth AmbiguousUsernameException $e) { // ambiguous username } catch ( Delight\Auth EmailNotVerifiedException $e) { // email address not verified } ``` -------------------------------- ### Logout Methods Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Provides methods to log out the current user, either from the current session, all sessions, or all sessions except the current one. It also includes a method to destroy the entire session. ```APIDOC ## Logout Methods ### Description Provides methods to log out the current user, either from the current session, all sessions, or all sessions except the current one. It also includes a method to destroy the entire session. ### Methods - `logOut()`: Logs the user out of the current session. - `logOutEverywhereElse()`: Logs the user out of all sessions except the current one. - `logOutEverywhere()`: Logs the user out of all sessions. - `destroySession()`: Destroys the entire session data. ### Usage Examples ```php // Log out of the current session $auth->logOut(); // Log out of all sessions except the current one try { $auth->logOutEverywhereElse(); } catch (\Delight\Auth\NotLoggedInException $e) { // not logged in } // Log out of all sessions try { $auth->logOutEverywhere(); } catch (\Delight\Auth\NotLoggedInException $e) { // not logged in } // Destroy the entire session $auth->destroySession(); ``` ### Notes Global logouts take effect immediately in the local session. In other sessions, changes may take up to five minutes to take effect. This behavior can be adjusted by changing the `$sessionResyncInterval` argument in the `Auth` constructor. ``` -------------------------------- ### Linux Script for Automatic Barcode Scanning Source: https://github.com/forceu/barcodebuddy/wiki/3.0-Usage A Python script designed to run on Linux as root, capturing input from USB keyboard barcode scanners and sending it to Barcode Buddy. Ensure the path within the script is correctly configured. ```python # Example python script for Linux # Make sure to modify the path first and then run it as root. # Example: # sudo python3 your_script_name.py ``` -------------------------------- ### Verify Password Reset Attempt without Exceptions Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Checks if a password reset attempt is valid using a selector and token without throwing exceptions. Use this for a simpler validity check. ```php if ($auth->canResetPassword($_GET['selector'], $_GET['token'])) { // put the selector into a `hidden` field (or keep it in the URL) // put the token into a `hidden` field (or keep it in the URL) // ask the user for their new password } ``` -------------------------------- ### Set Cookie using Static Method Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/cookie/README.md Use the static setcookie method, similar to PHP's built-in function but with added features like SameSite attribute support. ```php \Delight\Cookie\Cookie::setcookie('SID', '31d4d96e407aad42'); // or \Delight\Cookie\Cookie::setcookie('SID', '31d4d96e407aad42', time() + 3600, '/~rasmus/', 'example.com', true, true, 'Lax'); ``` -------------------------------- ### Throttle Resource or Feature Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Limits the number of requests to a specific resource or feature. Throws an exception if the limit is exceeded. ```php try { // throttle the specified resource or feature to *3* requests per *60* seconds $auth->throttle([ 'my-resource-name' ], 3, 60); // do something with the resource or feature } catch ( \Delight\Auth\TooManyRequestsException $e) { // operation cancelled exit; } ``` -------------------------------- ### Logging in as a User by ID Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Impersonates a user by their ID, logging them into the current session. Catches exceptions for unknown IDs, unverified emails. ```php try { $auth->admin()->logInAsUserById($_POST['id']); } catch ( Delight\Auth UnknownIdException $e) { // unknown ID } catch ( Delight\Auth EmailNotVerifiedException $e) { // email address not verified } ``` -------------------------------- ### Barcode Buddy API Specification Source: https://github.com/forceu/barcodebuddy/blob/master/api/doc.html The Barcode Buddy API is documented using OpenAPI. The specification can be found at the provided URL. ```APIDOC ## Barcode Buddy API ### Description This API allows interaction with the Barcode Buddy system for barcode-related operations. ### Specification URL `../openapi.json` ### Note UI elements related to server information and schemes are hidden for a cleaner view. ``` -------------------------------- ### Add Barcode via PHP Script Source: https://github.com/forceu/barcodebuddy/wiki/3.0-Usage Use this method to add a single barcode by calling the Barcode Buddy index.php script with the barcode as a parameter. ```bash php index.php yourBarcode ``` -------------------------------- ### Accessing User Information Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Methods for checking login status, retrieving user ID, email, display name, status, and IP address. ```APIDOC ## Accessing User Information ### Description Methods for checking login status, retrieving user ID, email, display name, status, and IP address. ### Methods - `isLoggedIn()`: Checks if the user is currently signed in. Alias: `check()`. - `getUserId()`: Retrieves the ID of the currently signed-in user. Returns `null` if not logged in. Alias: `id()`. - `getEmail()`: Retrieves the email address of the currently signed-in user. Returns `null` if not logged in. - `getUsername()`: Retrieves the display name (username) of the currently signed-in user. Returns `null` if not logged in or if username was not provided during registration. - `isNormal()`: Checks if the user is in the default state. - `isArchived()`: Checks if the user has been archived. - `isBanned()`: Checks if the user has been banned. - `isLocked()`: Checks if the user has been locked. - `isPendingReview()`: Checks if the user is pending review. - `isSuspended()`: Checks if the user has been suspended. - `isRemembered()`: Checks if the user was logged in through a long-lived cookie (not manually signed in). Returns `null` if not logged in. - `getIpAddress()`: Retrieves the IP address of the currently signed-in user. ### Usage Examples ```php // Check login state if ($auth->isLoggedIn()) { // user is signed in } // Get user ID $id = $auth->getUserId(); // Get email address $email = $auth->getEmail(); // Get username $username = $auth->getUsername(); // Check user status if ($auth->isBanned()) { // user has been banned } // Check if user was remembered if ($auth->isRemembered()) { // user logged in through cookie } // Get IP address $ip = $auth->getIpAddress(); ``` ### Additional User Information This library does not bundle additional columns for user information. To use custom user information: 1. Add custom database tables (e.g., `profiles`). 2. After calling the `register` method, fill your custom database tables with user data. 3. To load and access custom data, you can use a session variable: ```php function getUserInfo(\\Delight\\Auth\\Auth $auth) { if (!$auth->isLoggedIn()) { return null; } if (!isset($_SESSION['_internal_user_info'])) { // TODO: load your custom user information and assign it to the session variable below // $_SESSION['_internal_user_info'] = ... } return $_SESSION['_internal_user_info']; } ``` ``` -------------------------------- ### Constructing Email Verification URL Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Build a URL for email verification by encoding the selector and token. This URL would typically be sent to the user via email. ```php $url = 'https://www.example.com/verify_email?selector=' . urlencode($selector) . '&token=' . urlencode($token); ``` -------------------------------- ### Add a Response Header Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/http/README.md Add a response header, preserving other headers that share the same name. ```php \Delight\Http\ResponseHeader::add('X-Frame-Options', 'SAMEORIGIN') ``` -------------------------------- ### \Delight\Base64\Base64::encodeUrlSafeWithoutPadding Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/base64/README.md Encodes data using URL-safe Base64 without padding. ```APIDOC ## \Delight\Base64\Base64::encodeUrlSafeWithoutPadding ### Description Encodes the provided string data into a URL-safe Base64 format, without padding characters ('='). ### Method Signature `public static function encodeUrlSafeWithoutPadding(string $data): string` ### Parameters - **$data** (string) - Required - The string data to be encoded. ### Returns (string) - The URL-safe Base64 encoded string without padding. ### Example ```php \Delight\Base64\Base64::encodeUrlSafeWithoutPadding('πάντα χωρεῖ καὶ οὐδὲν μένει …'); // string(78) "z4DOrM69z4TOsSDPh8-Jz4HOteG_liDOus6x4b22IM6_4b2QzrThvbLOvSDOvM6tzr3Otc65IOKApg" ``` ``` -------------------------------- ### Confirm Email and Sign In Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Confirms a user's email address and automatically signs them in. Optionally supports persistent logins. ```APIDOC ## Confirm Email and Sign In ### Description Confirms a user's email address and automatically signs them in. Optionally supports persistent logins. ### Method GET ### Endpoint `/auth/confirmEmailAndSignIn` ### Parameters #### Query Parameters - **selector** (string) - Required - The selector part of the verification token. - **token** (string) - Required - The token part of the verification token. - **rememberDuration** (int|null) - Optional - Duration in seconds for a persistent login. Defaults to `null`. ### Response #### Success Response (200) Indicates successful email confirmation and sign-in. #### Error Responses - **InvalidSelectorTokenPairException**: The provided selector and token pair is invalid. - **TokenExpiredException**: The verification token has expired. - **UserAlreadyExistsException**: The email address is already associated with an existing user. - **TooManyRequestsException**: Too many requests. ``` -------------------------------- ### Create a random string Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Generate a random string of a specified length using the Auth::createRandomString method. ```php $length = 24; $randomStr = \Delight\Auth\Auth::createRandomString($length); ``` -------------------------------- ### Performance Profiling Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/db/README.md Enables performance profiling to monitor query execution times during development. You can set a profiler using `setProfiler`, and then retrieve analyzed queries using `getProfiler()->getMeasurements()`. The measurements can be sorted by duration using `getProfiler()->sort()`. ```APIDOC ## PERFORMANCE PROFILING ### Description Monitors and analyzes query performance. ### Methods * `setProfiler(ProfilerInterface $profiler)`: Sets a profiler instance to monitor queries. * `getProfiler()`: Returns the current profiler instance. ### Profiler Methods * `getMeasurements()`: Retrieves all recorded query measurements as an array. * `sort()`: Sorts the measurements, typically by duration. ``` -------------------------------- ### Create User with Unique Username Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Creates a new user account, enforcing that the provided username must be unique. ```APIDOC ## Create User with Unique Username ### Description Creates a new user account, enforcing that the provided username must be unique. ### Method ```php $auth->admin()->createUserWithUniqueUsername(string $email, string $password, string $username): int ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php try { $userId = $auth->admin()->createUserWithUniqueUsername($_POST['email'], $_POST['password'], $_POST['username']); // we have signed up a new user with the ID `$userId` } catch ( \Delight\Auth\InvalidEmailException $e) { // invalid email address } catch ( \Delight\Auth\InvalidPasswordException $e) { // invalid password } catch ( \Delight\Auth\DuplicateUsernameException $e) { // username already exists } ``` ### Response #### Success Response (200) - **int** - The ID of the newly created user. #### Response Example ```php 12345 ``` ### Error Handling - **InvalidEmailException**: Thrown if the provided email address is invalid. - **InvalidPasswordException**: Thrown if the provided password is invalid. - **DuplicateUsernameException**: Thrown if the provided username is not unique. ``` -------------------------------- ### Construct Password Reset URL Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/auth/README.md Builds a URL for password reset using the provided selector and token, intended to be sent to the user. ```PHP $url = 'https://www.example.com/reset_password?selector=' . \urlencode($selector) . '&token=' . \urlencode($token); ``` -------------------------------- ### \Delight\Base64\Base64::encodeUrlSafe Source: https://github.com/forceu/barcodebuddy/blob/master/incl/authentication/composer/vendor/delight-im/base64/README.md Encodes data using URL-safe Base64. ```APIDOC ## \Delight\Base64\Base64::encodeUrlSafe ### Description Encodes the provided string data into a URL-safe Base64 format, replacing '+' with '-' and '/' with '_'. ### Method Signature `public static function encodeUrlSafe(string $data): string` ### Parameters - **$data** (string) - Required - The string data to be encoded. ### Returns (string) - The URL-safe Base64 encoded string. ### Example ```php \Delight\Base64\Base64::encodeUrlSafe('πάντα χωρεῖ καὶ οὐδὲν μένει …'); // string(80) "z4DOrM69z4TOsSDPh8-Jz4HOteG_liDOus6x4b22IM6_4b2QzrThvbLOvSDOvM6tzr3Otc65IOKApg~~" ``` ```