onix-systems-php/hyperf-impersonate

Hyperf Impersonate is a plugin that allows to you to authenticate as your users

v1.0.0 2024-02-16 09:47 UTC

This package is auto-updated.

Last update: 2024-04-16 10:14:38 UTC


README

Includes the following classes:

  • Contract:
    • Impersonatable;
  • Controller:
    • ImpersonateController;
  • DTO:
    • ImpersonateInfoDTO;
    • ImpersonateLeaveDTO;
    • ImpersonateTakeDTO;
  • Event:
    • LeaveImpersonation
    • TakeImpersonation
  • Exception:
    • AlreadyImpersonatingException;
    • CantBeImpersonatedException;
    • CantImpersonateException;
    • CantImpersonateSelfException;
    • NotImpersonatingException;
    • ProtectedAgainstImpersonationException;
  • Middleware:
    • ProtectFromImpersonation;
  • Resource:
    • ResourceInfoImpersonate;
    • ResourceLeaveImpersonate;
    • ResourceTakeImpersonate;
  • Service:
    • ImpersonateService;
  • Trait
    • Impersonatable

Install:

composer require onix-systems-php/hyperf-impersonate

Publish config:

php bin/hyperf.php vendor:publish onix-systems-php/hyperf-impersonate -i config

Publish translations:

php bin/hyperf.php vendor:publish onix-systems-php/hyperf-impersonate -i en_us_translation
php bin/hyperf.php vendor:publish onix-systems-php/hyperf-impersonate -i ua_uk_translation

Import impersonate routes:

require_once './vendor/onix-systems-php/hyperf-auth/publish/routes.php';

Add line to config/autoload/swagger.php for swagger:

'vendor/onix-systems-php/hyperf-impersonate/src/',

Basic Usage

use OnixSystemsPHP\HyperfImpersonate\Contract\Impersonatable as ImpersonatableInterface;
use OnixSystemsPHP\HyperfImpersonate\Trait\Impersonatable;

class User extends ... implements ImpersonatableInterface
{
    use Impersonatable;
}

Advanced Usage

Defining impersonation authorization

By default all users can impersonate an user. You need to add the method canImpersonate() to your user model:

public function canImpersonate(): bool
{
    return in_array($this->getRole(), UserRoles::GROUP_ADMINS);
}

By default all users can be impersonated. You need to add the method canBeImpersonated() to your user model to extend this behavior:

public function canBeImpersonated(): bool
{
    return in_array($this->getRole(), UserRoles::GROUP_USERS);
}