californiamountainsnake/simple-laravel-auth-system

此包已被弃用且不再维护。未建议替代包。

Laravel的简单认证和授权实现

3.0.19 2020-04-20 13:43 UTC

README

Laravel的简单认证和授权实现

安装

使用Composer安装此包

通过Composer安装此包。编辑您的项目composer.json文件以要求californiamountainsnake/simple-laravel-auth-system

{
    "name": "yourproject/yourproject",
    "type": "project",
    "require": {
        "php": "^7.2",
        "californiamountainsnake/simple-laravel-auth-system": "*"
    }
}

并运行composer update

或者

在您的命令行中运行以下命令

composer require californiamountainsnake/simple-laravel-auth-system

使用方法

  1. 扩展枚举类:(AuthLangsEnumAuthUserAccountTypeEnumAuthUserRoleEnum)。
  2. 扩展AuthUserAvailableActions类。您可以在其中添加基于某些用户的任何检查,例如(new UserAvailableActions($user))->isSomeActionAvailableForThisUser()
  3. 扩展AuthUserEntity类。这是您的主要用户类。请参阅https://github.com/CaliforniaMountainSnake/php-database-entities
  4. 扩展AuthUserRepository类。这是包含所有用户数据库查询的仓库。请参阅https://github.com/CaliforniaMountainSnake/php-database-entities
  5. 扩展包含api_token请求参数的Laravel验证数组的AuthValidatorService类。
<?php
class MyValidatorService extends AuthValidatorService
{
    public function api_token(): array
        {
            return [
                AuthMiddleware::API_TOKEN_REQUEST_PARAM => [
                    'min:64',
                    'max:64',
                ]
            ];
        }
}
  1. 在Laravel AppServiceProvider中添加一些绑定
<?php
class AppServiceProvider extends ServiceProvider
{    
    public function boot (): void {
        $this->app->singleton(AuthRoleService::class, static function () {
            return new AuthRoleService(true);
        });
    }

    public function register(): void {
        // Binding Interfaces To Implementations.
        $this->app->singleton(AuthenticatorInterface::class, BasicHttpAuthenticator::class);
        $this->app->singleton(AuthValidatorServiceInterface::class, YourValidatorService::class);
        $this->app->singleton(AuthUserRepository::class, YourUserRepository::class);

        $this->app->singleton(AuthHashFunction::class, static function () {
            return new class implements AuthHashFunction
            {
                public function getHashFunction(): callable
                {
                    return static function ($_token) {
                        // You can use something like this:
                        // return sha1($_token);
                        return $_token;
                    };
                }
            };
        });
    }
}
  1. 扩展AuthApiUserController类并创建您自己的基础API控制器。实现抽象方法。此控制器(及其子类)的所有操作都将自动由认证系统处理。
<?php
class ApiUserController extends AuthApiUserController
{
    // Realise the abstract methods.
}
  1. 现在您可以将路由添加到www/routes/api.php文件中,如下所示
<?php
use CaliforniaMountainSnake\SimpleLaravelAuthSystem\AuthRoleService;

/** @var AuthRoleService $roleService */
$roleService = app()->make(AuthRoleService::class);

$roleService->setRote(
    Route::post('/users', 'User\UserController@createUser'),
    [
        UserRoleEnum::NOT_AUTH()
    ],
    [
        UserAccountTypeEnum::FREE(),
        UserAccountTypeEnum::PAID(),
    ]);

$roleService->setRote(
    Route::get('/users', 'User\UserController@getAllUsers'),
    [
        UserRoleEnum::TECHNICAL_ADMIN(),
        UserRoleEnum::ADMIN()
    ],
    [
        UserAccountTypeEnum::FREE(),
        UserAccountTypeEnum::PAID(),
    ]);
  1. App\Exceptions\Handler::render()中捕获MethodNotAllowedException
<?php
use CaliforniaMountainSnake\JsonResponse\JsonResponse;
use Exception;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use InvalidArgumentException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;

class Handler extends ExceptionHandler {
    /**
     * Render an exception into an HTTP response.
     *
     * @param Request   $request
     * @param Exception $exception
     *
     * @return Response
     * @throws BindingResolutionException
     * @throws InvalidArgumentException
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof MethodNotAllowedException || $exception instanceof MethodNotAllowedHttpException) {
            return JsonResponse::error([__('auth_middleware.method_not_allowed')],
                JsonResponse::HTTP_METHOD_NOT_ALLOWED)
                ->withCors()// Optional.
                ->make();
        }

        return parent::render($request, $exception);
    }
}
  1. 创建一个语言文件(/resources/lang/en/auth_middleware.php)以包含API错误消息
  • auth_middleware.method_not_allowed
  • auth_middleware.no_token_error
  • auth_middleware.bad_token_error
  • auth_middleware.wrong_role_error
  • auth_middleware.wrong_account_type_error
  1. 就这样)(