Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do I configure the impersonation rules in OctopyID/LaraPersonate


How do I configure the impersonation rules in OctopyID/LaraPersonate


To configure the impersonation rules in OctopyID/LaraPersonate, you need to add the following methods to your User model:

php
use Octopy\Impersonate\Concerns\HasImpersonation;
use Octopy\Impersonate\Authorization;

class User extends Authenticatable
{
    use HasImpersonation;

    /**
     * Define who can perform impersonation.
     *
     * @param Authorization $authorization
     * @return void
     */
    public function setImpersonateAuthorization(Authorization $authorization): void
    {
        $authorization->impersonator(function (User $user) {
            // Return true if the user can impersonate others
            return $user->hasRole('SUPER_ADMIN');
        });

        $authorization->impersonated(function (User $user) {
            // Return true if the user can be impersonated
            return $user->hasRole('CUSTOMER');
        });
    }

    /**
     * Define how to display the impersonated user.
     *
     * @return string
     */
    public function getImpersonateDisplayText(): string
    {
        return $this->name;
    }

    /**
     * Define the searchable fields for impersonation.
     *
     * @return array
     */
    public function getImpersonateSearchField(): array
    {
        return [
            'name',
            'posts.title',
        ];
    }
}

In the `setImpersonateAuthorization` method, you define the rules for who can impersonate others (`impersonator`) and who can be impersonated (`impersonated`). In this example, only users with the `SUPER_ADMIN` role can impersonate, and only users with the `CUSTOMER` role can be impersonated.

The `getImpersonateDisplayText` method defines how the impersonated user will be displayed in the interface, in this case, using the `name` attribute.

The `getImpersonateSearchField` method defines the fields that can be used to search for users to impersonate, in this case, the `name` field and the `title` field of the user's `posts` relationship.

By implementing these methods in your User model, you can customize the impersonation rules and behavior to fit your application's needs.

Citations:
[1] https://github.com/OctopyID/LaraPersonate
[2] https://github.com/topics/impersonate?l=php
[3] https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-configure-impersonation?redirectedfrom=MSDN
[4] https://packagist.org/packages/rhmdnj/laravel-impersonate
[5] https://docs.netapp.com/us-en/saasbackupO365/task_configuring_impersonation.html