lab404/laravel-impersonate

Laravel Impersonate是一个插件,允许您以用户身份进行认证。

1.7.5 2024-03-11 14:26 UTC

README

Build Status Scrutinizer Code Quality

Laravel Impersonate允许您轻松地以用户身份进行认证。将一个简单的trait添加到您的user model中,然后一键模拟您的用户。

要求

  • Laravel 6.x到11.x
  • PHP >= 7.2 或 >= 8.0

Laravel支持

安装

  • 使用Composer安装
composer require lab404/laravel-impersonate
  • 在您的config/app.php文件末尾添加服务提供者
'providers' => [
    // ...
    Lab404\Impersonate\ImpersonateServiceProvider::class,
],
  • Lab404\Impersonate\Models\Impersonate trait添加到您的User模型中。

简单用法

模拟用户

Auth::user()->impersonate($other_user);
// You're now logged as the $other_user

退出模拟

Auth::user()->leaveImpersonation();
// You're now logged as your original user.

使用内置控制器

在您的路由文件中,在web中间件下,您必须调用impersonate路由宏。

Route::impersonate();

或者,您可以使用您的RouteServiceProvider来执行此宏。

namespace App\Providers;

class RouteServiceProvider extends ServiceProvider
{
    public function map() {
        Route::middleware('web')->group(function (Router $router) {
            $router->impersonate();
        });
    }
}
// Where $id is the ID of the user you want impersonate
route('impersonate', $id)

// Or in case of multi guards, you should also add `guardName` (defaults to `web`)
route('impersonate', ['id' => $id, 'guardName' => 'admin'])

// Generate an URL to leave current impersonation
route('impersonate.leave')

高级用法

定义模拟授权

默认情况下,所有用户都可以模拟任何用户。
您需要将canImpersonate()方法添加到您的用户模型中

    /**
     * @return bool
     */
    public function canImpersonate()
    {
        // For example
        return $this->is_admin == 1;
    }

默认情况下,所有用户都可以被模拟。
您需要将canBeImpersonated()方法添加到您的用户模型中,以扩展此行为

    /**
     * @return bool
     */
    public function canBeImpersonated()
    {
        // For example
        return $this->can_be_impersonated == 1;
    }

使用自己的策略

  • 获取管理器
// With the app helper
app('impersonate')
// Dependency Injection
public function impersonate(ImpersonateManager $manager, $user_id) { /* ... */ }
  • 与管理者协同工作
$manager = app('impersonate');

// Find an user by its ID
$manager->findUserById($id);

// TRUE if your are impersonating an user.
$manager->isImpersonating();

// Impersonate an user. Pass the original user and the user you want to impersonate
$manager->take($from, $to);

// Leave current impersonation
$manager->leave();

// Get the impersonator ID
$manager->getImpersonatorId();

中间件

防止模拟

您可以使用中间件impersonate.protect来保护您的路由免受用户模拟。
当您想要保护特定页面,如用户订阅、用户信用卡等时,此中间件非常有用。

Router::get('/my-credit-card', function() {
    echo "Can't be accessed by an impersonator";
})->middleware('impersonate.protect');

事件

有两个事件可用于改进您的流程

  • TakeImpersonation在模拟开始时触发。
  • LeaveImpersonation在模拟结束时触发。

每个事件返回两个属性$event->impersonator$event->impersonated,它们包含User模型实例。

配置

该软件包附带一个配置文件。

使用以下命令发布它

php artisan vendor:publish --tag=impersonate

可用选项

    // The session key used to store the original user id.
    'session_key' => 'impersonated_by',
    // Where to redirect after taking an impersonation.
    // Only used in the built-in controller.
    // You can use: an URI, the keyword back (to redirect back) or a route name
    'take_redirect_to' => '/',
    // Where to redirect after leaving an impersonation.
    // Only used in the built-in controller.
    // You can use: an URI, the keyword back (to redirect back) or a route name
    'leave_redirect_to' => '/'

Blade模板

有三种Blade指令可用。

当用户可以模拟时

@canImpersonate($guard = null)
    <a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>
@endCanImpersonate

当用户可以被模拟时

当您有一个用户列表并且想要在所有用户旁边显示一个“模拟”按钮时,这很有用。但是您不希望在当前认证用户或根据您的canBeImpersonated()实现无法模拟的用户旁边显示此按钮。

@canBeImpersonated($user, $guard = null)
    <a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>
@endCanBeImpersonated

当用户正在被模拟时

@impersonating($guard = null)
    <a href="{{ route('impersonate.leave') }}">Leave impersonation</a>
@endImpersonating

测试

vendor/bin/phpunit

贡献者

理由

为什么不用loginAsId()

此包增加了更广泛的功能,包括Blade指令,允许您在模拟时覆盖分析和其他跟踪事件,根据模拟状态触发事件,等等。有关简短讨论,请参阅 issues/5

许可证

MIT