rickycezar/laravel-jwt-impersonate 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

rickycezar/laravel-jwt-impersonate

Composer 安装命令:

composer require rickycezar/laravel-jwt-impersonate

包简介

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

README 文档

README

DISCLAIMER: This is a fork of lab404/laravel-impersonate patched to work with JWTAuth in a REST API application. I'll Always recommend you to use the original component.

Laravel JWT Impersonate makes it easy to authenticate as your users. Add a simple trait to your user model and impersonate as one of your users in one click.

Requirements

  • Laravel >= 5.8
  • PHP >= 7.1
  • JWT-Auth >= dev-develop

Installation

  • Require it with Composer:
composer require rickycezar/laravel-jwt-impersonate
  • Add the service provider at the end of your config/app.php:
'providers' => [
    // ...
    Rickycezar\Impersonate\ImpersonateServiceProvider::class,
],
  • Add the trait Rickycezar\Impersonate\Models\Impersonate to your User model.

Simple usage

Impersonate a user:

$token = Auth::user()->impersonate($other_user);
// You're now logged as the $other_user and the authentication token is stored in $token.

Leave impersonation:

$token = Auth::user()->leaveImpersonation();
// You're now logged as your original user and the authentication token is stored in $token.

Using the built-in controller

In your routes file you can call the impersonate route macro if you want to use the built-in controller.

Route::impersonate();

Alternatively, you can execute this macro with your 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) //the url path is "impersonate/take/{id}".
// Generate an URL to leave current impersonation
route('impersonate.leave') //the url path is "impersonate/leave".
// Check the current user impersonation status
route('impersonate.info') //the url path is "impersonate/info".

Advanced Usage

Defining impersonation authorization

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

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

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

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

Using your own strategy

It is possible to implement your own controller to deal with impersonation:

use Rickycezar\Impersonate\Services\ImpersonateManager;

class ImpersonateController extends Controller
{
    protected $manager;
    
    // Dependency Injection
    public function __construct(ImpersonateManager $manager)
    {
        $this->manager = $manager;
    }

    public function impersonate(){ /*....*/ }
    public function leave(){ /*....*/ }
}
class ImpersonateController extends Controller
{
    protected $manager;
        
    //Direct app call
    public function __construct()
    {
        $this->manager = app('impersonate');
    }

    public function impersonate(){ /*....*/ }
    public function leave(){ /*....*/ }
}
  • Working with the manager:
$manager = app('impersonate');

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

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

// Impersonate a user. Pass the original user and the user you want to impersonate. Returns authentication token
$token = $manager->take($from, $to);

// Leave current impersonation. Returns authentication token
$token = $manager->leave();

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

Middleware

Protect From Impersonation

You can use the middleware impersonate.protect to protect your routes against user impersonation.
This middleware can be useful when you want to protect specific pages like users subscriptions, users credit cards, ...

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

Exceptions

There are six possible exceptions thrown by the service:

  • AlreadyImpersonatingException is thrown when an impersonator tries to take another persona without leaving the first one.
  • CantBeImpersonatedException is thrown when the method canBeImpersonated() fails.
  • CantImpersonateException is thrown when the method canImpersonate() fails.
  • CantImpersonateSelfException is thrown when an user tries to impersonate self.
  • NotImpersonatingException is thrown when an user tries to leave an impersonation without being impersonating.
  • ProtectedFromImpersonationException is thrown when an impersonator tries to get access to a route protected by the middleware.

Each exception have a message and a status code available through the respective methods getErrorMessage() and getErrorCode().

Events

There are two events available that can be used to improve your workflow:

  • TakeImpersonation is fired when an impersonation is taken.
  • LeaveImpersonation is fired when an impersonation is left.

Each events returns two properties $event->impersonator and $event->impersonated containing a User model isntance.

Configuration

The package comes with a configuration file.

Publish it with the following command:

php artisan vendor:publish --tag=impersonate

Available options:

    // The custom claim key used to store the original user id in the JWT token.
    'session_key' => 'impersonated_by',
    // The alias for the authentication middleware to be used in the routes.
    'auth_alias' => 'auth',

Licence

MIT

rickycezar/laravel-jwt-impersonate 适用场景与选型建议

rickycezar/laravel-jwt-impersonate 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 124.2k 次下载、GitHub Stars 达 24, 最近一次更新时间为 2017 年 06 月 08 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「package」 「plugin」 「user」 「auth」 「laravel」 「impersonation」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 rickycezar/laravel-jwt-impersonate 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 rickycezar/laravel-jwt-impersonate 我们能提供哪些服务?
定制开发 / 二次开发

基于 rickycezar/laravel-jwt-impersonate 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 124.2k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 25
  • 点击次数: 34
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 24
  • Watchers: 2
  • Forks: 235
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2017-06-08