PHP code example of azaharizaman / nexus-identity

1. Go to this page and download the library: Download azaharizaman/nexus-identity library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

azaharizaman / nexus-identity example snippets


// For read-only operations
public function __construct(
    private readonly UserQueryInterface $userQuery
) {}

// For write operations
public function __construct(
    private readonly UserPersistInterface $userPersist
) {}

use Nexus\Identity\Services\UserManager;
use Nexus\Identity\ValueObjects\Credentials;

// Create a new user
$user = $userManager->createUser([
    'email' => '[email protected]',
    'password' => 'SecureP@ssw0rd!',
    'name' => 'John Doe',
    'tenant_id' => 'tenant_ulid',
]);

// Change password
$userManager->changePassword($user->getId(), 'NewSecureP@ssw0rd!');

// Activate user
$userManager->activateUser($user->getId());

// Lock user
$userManager->lockUser($user->getId(), 'Suspicious activity detected');

use Nexus\Identity\Services\AuthenticationService;
use Nexus\Identity\ValueObjects\Credentials;

$credentials = new Credentials('[email protected]', 'SecureP@ssw0rd!');

// Login
$result = $authService->login($credentials, [
    'ip' => '192.168.1.1',
    'user_agent' => 'Mozilla/5.0...',
]);

$user = $result['user'];
$session = $result['session'];

// Validate session
$authenticatedUser = $authService->validateSession($session->token);

// Logout
$authService->logout($session->token);

use Nexus\Identity\Services\PermissionChecker;

// Check permission
if ($permissionChecker->hasPermission($user, 'users.create')) {
    // User can create users
}

// Check multiple permissions
if ($permissionChecker->hasAllPermissions($user, ['users.create', 'users.update'])) {
    // User has all permissions
}

// Check role
if ($permissionChecker->hasRole($user, 'admin')) {
    // User is an admin
}

// Wildcard permission matching
// If user has "users.*", they have "users.create", "users.update", etc.

use Nexus\Identity\Contracts\PolicyEvaluatorInterface;
use Nexus\Identity\ValueObjects\Policy;

// Register a custom policy
$leavePolicy = Policy::define('hrm.leave.apply_on_behalf')
    ->description('User can apply leave on behalf of employees in same department or as their manager')
    ->check(function(UserInterface $user, string $action, mixed $resource, array $context) use ($employeeQuery) {
        // Extract target employee from context
        $targetEmployeeId = $context['target_employee_id'] ?? null;
        if (!$targetEmployeeId) {
            return false;
        }

        $userEmployee = $employeeQuery->findByUserId($user->getId());
        $targetEmployee = $employeeQuery->findById($targetEmployeeId);

        // Check if same department OR user is manager
        return $userEmployee?->getDepartmentId() === $targetEmployee?->getDepartmentId()
            || $userEmployee?->getId() === $targetEmployee?->getManagerId();
    });

$policyEvaluator->registerPolicy(
    $leavePolicy->getName(),
    $leavePolicy->getEvaluator()
);

// Evaluate policy with context
$canApply = $policyEvaluator->evaluate(
    user: $user,
    action: 'hrm.leave.apply_on_behalf',
    resource: null,
    context: ['target_employee_id' => $employeeId]
);

if ($canApply) {
    // User can apply leave on behalf of this employee
}

use Nexus\Identity\Services\RoleManager;

// Create a role
$role = $roleManager->createRole([
    'name' => 'manager',
    'description' => 'Department Manager',
    'tenant_id' => 'tenant_ulid',
]);

// Assign permission to role
$roleManager->assignPermission($role->getId(), $permission->getId());

// Assign role to user
$userManager->assignRole($user->getId(), $role->getId());

use Nexus\Identity\Services\PermissionManager;

// Create a permission
$permission = $permissionManager->createPermission([
    'name' => 'users.create',
    'resource' => 'users',
    'action' => 'create',
    'description' => 'Create new users',
]);

// Create wildcard permission
$wildcardPermission = $permissionManager->createPermission([
    'name' => 'users.*',
    'resource' => 'users',
    'action' => '*',
    'description' => 'All user operations',
]);

use Nexus\Identity\Contracts\TokenManagerInterface;

// Generate API token
$token = $tokenManager->generateToken(
    userId: $user->getId(),
    name: 'Production API',
    scopes: ['users.read', 'invoices.read'],
    expiresAt: new \DateTimeImmutable('+1 year')
);

// Validate token
$tokenUser = $tokenManager->validateToken($token->token);

// Revoke token
$tokenManager->revokeToken($token->id);

use Nexus\Identity\ValueObjects\UserStatus;

$status = UserStatus::ACTIVE;
$status->canAuthenticate(); // true

$locked = UserStatus::LOCKED;
$locked->

use Nexus\Identity\ValueObjects\Credentials;

$credentials = new Credentials('[email protected]', 'password');
// Validates email format on construction

use Nexus\Identity\ValueObjects\Permission;

$permission = Permission::fromName('users.create');
$permission->resource; // 'users'
$permission->action; // 'create'
$permission->isWildcard(); // false

$wildcard = Permission::fromName('users.*');
$wildcard->matches('users.create'); // true
$wildcard->matches('users.update'); // true
$wildcard->matches('roles.create'); // false

use Nexus\Identity\Exceptions\UserNotFoundException;
use Nexus\Identity\Exceptions\InvalidCredentialsException;
use Nexus\Identity\Exceptions\InsufficientPermissionsException;

try {
    $user = $userManager->findUser($userId);
} catch (UserNotFoundException $e) {
    // Handle user not found
}

try {
    $authService->login($credentials);
} catch (InvalidCredentialsException $e) {
    // Handle invalid credentials
} catch (AccountLockedException $e) {
    // Handle locked account
}

// Repository bindings
$this->app->singleton(UserRepositoryInterface::class, DbUserRepository::class);
$this->app->singleton(RoleRepositoryInterface::class, DbRoleRepository::class);
$this->app->singleton(PermissionRepositoryInterface::class, DbPermissionRepository::class);

// Service implementations
$this->app->singleton(PasswordHasherInterface::class, LaravelPasswordHasher::class);
$this->app->singleton(PasswordValidatorInterface::class, LaravelPasswordValidator::class);
$this->app->singleton(UserAuthenticatorInterface::class, LaravelUserAuthenticator::class);
$this->app->singleton(SessionManagerInterface::class, LaravelSessionManager::class);
$this->app->singleton(TokenManagerInterface::class, LaravelTokenManager::class);

// Permission checker (uses base implementation)
$this->app->singleton(PermissionCheckerInterface::class, PermissionChecker::class);

use Nexus\Identity\Services\UserManager;
use Nexus\Identity\Contracts\UserRepositoryInterface;
use PHPUnit\Framework\TestCase;

class UserManagerTest extends TestCase
{
    public function test_create_user()
    {
        $mockRepo = $this->createMock(UserRepositoryInterface::class);
        $mockRepo->expects($this->once())
            ->method('emailExists')
            ->willReturn(false);
        
        $userManager = new UserManager($mockRepo, $hasher, $validator);
        // ... test logic
    }
}