The ultimate PHP User Management: Authentication, Roles, Sessions, Users and More with TurboDepot's UsersManager class

In today's digital landscape, robust user management is crucial for any application. The TurboDepot's UsersManager class provides a powerful set of tools for handling user-related operations, from authentication to role-based access control. This tutorial will guide you through the key features and usage of the UsersManager class.

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setting Up
  4. User Management
  5. Authentication
  6. Role and Operation Management
  7. Email Management
  8. Advanced Features
  9. Best Practices and Security Considerations

Introduction

The UsersManager class is part of the TurboDepot library, designed to provide a comprehensive solution for user management in PHP applications. It offers features such as:

Prerequisites

Before we begin, make sure you have the following:

Download the latest TurboCommons and TurboDepot phar files and place them on your project as dependencies. Then you'll be able to directly use the UsersManager class:

require 'path/to/your/dependencies/folder/turbocommons-php-X.X.X.phar';
require 'path/to/your/dependencies/folder/turbodepot-php-X.X.X.phar';

Setting Up

To start using the UsersManager class, you'll need to have the TurboDepot library installed and a database set up. Here's how to initialize the class:

use org\turbodepot\src\main\php\managers\UsersManager;
use org\turbodepot\src\main\php\managers\DataBaseObjectsManager;

// Have a DataBaseObjectsManager instance ready
$dbObjectsManager = new DataBaseObjectsManager();
$dbObjectsManager->connectMariaDb('host', 'user', 'password', 'database');

// Create a UsersManager instance
$usersManager = new UsersManager($dbObjectsManager);

User Management

Creating a User

To create a new user, use the saveUser method:

use org\turbodepot\src\main\php\model\UserObject;

$user = new UserObject();
$user->userName = 'johndoe';

$userId = $usersManager->saveUser($user);

// Set the user's password
$usersManager->setUserPassword('johndoe', 'securepassword123');

Retrieving a User

You can retrieve a user object by username or token:

$user = $usersManager->findUserByUserName('johndoe');
// or
$user = $usersManager->findUserByToken($token);

Deleting a User

To delete a user:

$usersManager->deleteUser('johndoe');

Authentication

User Login

To authenticate a user and generate a token:

$loginResult = $usersManager->login('johndoe', 'securepassword123');
$token = $loginResult->token;
$user = $loginResult->user;
$operations = $loginResult->operations;

Validating a Token

To check if a token is valid:

$isValid = $usersManager->isTokenValid($token);

Logging Out

To invalidate a token (log out a user):

$usersManager->logout($token);

Role and Operation Management

Creating Roles

To create a new role:

$usersManager->saveRole('admin', 'Administrator role');
$user->roles = ['admin'];

Creating Operations

Operations represent actions that can be performed by users. You can use them later in your application to check if a user is allowed or not to certain functionalities:

$usersManager->saveOperation('edit_posts', 'The user can edit blog posts');

Assigning Operations to Roles

To specify which roles can perform an operation:

$usersManager->setOperationEnabledForRoles('edit_posts', ['admin', 'editor']);

Checking User Permissions

To check if a user is allowed to perform an operation:

$canEditPosts = $usersManager->isUserAllowedTo('johndoe', 'edit_posts');

Email Management

Adding an Email to a User

$usersManager->saveUserMail('johndoe', '[email protected]');

Verifying an Email

Email verification typically involves generating a verification hash, sending it to the user, and then verifying it:

$verificationHash = $usersManager->getUserMailVerificationHash('johndoe', '[email protected]');
// Send this hash to the user via email

// When the user clicks the verification link:
$isVerified = $usersManager->verifyUserMail('johndoe', '[email protected]', $verificationHash);

Advanced Features

Custom User Fields

You can add custom fields to users:

use org\turbodepot\src\main\php\model\DataBaseObject;

// NOTICE: You must create a custom user fields object that extends DataBaseObject with your custom properties
$customFields = new DataBaseObject(); 

$customFields->birthDate = '1990-01-01';
$customFields->favoriteColor = 'blue';

$usersManager->saveUserCustomFields('johndoe', $customFields);

Transaction Management

For operations that require multiple steps, you can use transactions:

try {
    $usersManager->transactionBegin();

    // Perform multiple operations
    $usersManager->saveUser($user);
    $usersManager->setUserPassword($user->userName, $password);
    $usersManager->saveUserMail($user->userName, $email);

    $usersManager->transactionCommit();
} catch (Exception $e) {
    $usersManager->transactionRollback();
    // Handle the error
}

Best Practices and Security Considerations

  1. Password Security: Always use setUserPassword() to set passwords, as it handles proper hashing.
  2. Token Management: Use tokens for authentication after initial login. Never send passwords over the network unnecessarily.
  3. Role-Based Access Control: Utilize roles and operations to create a fine-grained permission system.
  4. Email Verification: Implement email verification to ensure the validity of user email addresses.
  5. Error Handling: Wrap critical operations in try-catch blocks and use transactions where appropriate.

By leveraging the UsersManager class, you can implement a robust, secure, and feature-rich user management system in your PHP applications. Remember to always prioritize security and follow best practices when dealing with user data and authentication.