bishwopl/zf3-circlical-user 问题修复 & 功能扩展

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

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

bishwopl/zf3-circlical-user

Composer 安装命令:

composer require bishwopl/zf3-circlical-user

包简介

Complete user entity, rights, and access module for Laminas

README 文档

README

Codacy Badge Codacy Badge Latest Stable Version Total Downloads Quality Gate Status Gitter

Plug and play authentication, roles, resource, and action control for Laminas.

Quickly Installs:

  • cookie based authentication (using halite and its authenticated encryption)
  • role-based access control (RBAC) with guards at the controller and action level
  • user-based access control to complement RBAC
  • resource-based permissions, giving you 'resource' and 'verb' control at the role and user level, e.g. (all administrators can 'add' a server, only Pete can 'delete')

You can see it in action, in this ready-to-use skeleton.

Missive

Sure - there are other Authentication, ACL, and User modules out there. This one comes with out-of-the-box support for Doctrine - just plug in your user entity and go.

Authentication is persisted using cookies, meaning no session usage at all. This was done because I develop for circumstances where this is preferable, removing any need for complex or error-prone solutions for session management on an EC2 auto-scale group for example.

Lastly, authenticated encryption is handled using the well-trusted Halite, and password hashing is properly done with PHP's new password functions. Feedback always solicited on r/php.. If you are a paranoid fellow like me, this library should serve well!

This library works on a deny-first basis. Everything defined by its parts below, are 'allow' grants.

User Authentication

The module provides full identity/auth management, starting at the user-level. A design goal was to connect this to registration or login processes with little more than one-liners.

Login

Validate your submitted Login form, and then execute this to get your user through the door:

$user = $this->auth()->authenticate( $emailOrUsername, $password );

Successful authentication, will drop cookies that satisfy subsequent identity retrieval.

Logout

Trash cookies and regenerate the session key for that user, using this command:

 $this->auth()->clearIdentity();

Pluggable Deny Strategy

Someone trying to do something they shouldn't? It's easy to control what happens with a pluggable DenyStrategy. Create a class that implements DenyStrategyInterface and plug it into your config. This module comes with a default RedirectStrategy that will send users to a login page, if the problem was that there was no auth, and it wasn't an XHTTP request. Easy to use, you'd configure it like so:

'deny_strategy' => [

    'class' => \CirclicalUser\Strategy\RedirectStrategy::class,

    'options' => [
        'controller' => \Application\Controller\LoginController::class,
        'action' => 'index',
    ],
],

Writing your own should be very simple, see provided tests.

Pluggable Password Strength Checker

You can use the built-in support for paragonie/passwdqc by uncommenting the password_strength_checker config key. You can also roll your own if you have more complex needs; uncomment the key and specify your own implementation of PasswordCheckerInterface. This will cause the password input routines to throw WeakPasswordExceptions when weak input is received.

Configuration of the password checker can be done two ways:

Class without options

'password_strength_checker' => \CirclicalUser\Service\PasswordChecker\Passwdqc::class,

Class with options

'password_strength_checker' => [
    'implementation' => \CirclicalUser\Service\PasswordChecker\Zxcvbn::class,
    'config' => [
        'required_strength' => 3,
    ],
],

Creating Access For Your Users

Your app needs to be modified to create a distinct auth record for each user. It's very simple.

create & authenticate

During user registration routines, you probably want to create the records and also log them in. To accomplish this, you can use the helper or the 'create' method on AccessService.

From a Controller, you can use the auth plugin:

 $this->auth()->create(User $user, string $usernameOrEmail, string $password); // controller helper

or, the AuthenticationService:

$container->get(AuthenticationService::class)->create($user, $usernameOrEmail, $password);

create only

Otherwise, if you simply want to create a user auth record but not log them in, use:

$container->get(AuthenticationService::class)->registerAuthenticationRecord(User $user, string $username, string $password)

Roles

Your users belong to hierarchical roles that are configured in the database. The default guest user, is group-less.
Roles are used to restrict access to controllers, actions, or resources.

Guards

Guards are conditions on controllers & actions -- or middleware -- that examine group or user privileges to permit/decline attempted access. It works very similarly to BjyAuthorize (a great module I used for years).

Configuring guards is very simple. Your module's config would look like so:

 return [
    'circlical' => [
        'user' => [
            'guards' => [
                'ModuleName' => [
                    "controllers" => [
                        \Application\Controller\IndexController::class => [
                            'default' => [], // anyone can access
                        ],
                        \Application\Controller\MemberController::class => [
                            'default' => ['user'], // specific role access
                        ],
                        \Application\Controller\AdminController::class => [
                            'default' => ['admin'],
                            'actions' => [  // action-level guards
                                'list' => [ 'user' ], // role 'user' can access 'listAction' on AdminController
                            ],
                        ],
                    ],
                ],
            ],
        ],
    ],
 ];   

If you are defining access for middleware route definitions, then you don't need to configure the 'actions' section above. Further, the Module is then ignored, so you can place your middleware handler's class in any module; example:

 return [
    'circlical' => [
        'user' => [
            'guards' => [
                'Middleware' => [
                    "controllers" => [
                        \Application\Middleware\MiddlewareHandler::class => [
                            'default' => [], // anyone can access
                        ],
                    ],
                ],
            ],
        ],
    ],
 ];  

Resources & Permissions

Resources can be:

Both these usages are valid from a controller:

$this->auth()->isAllowed('door','open');

or if an object:

// server implements ResourceInterface
$server = $serverMapper->get(142);
$this->auth()->isAllowed($server,'shutdown');

The AccessService is also similarly usable. See AccessService tests for more usage examples.

Granting a role a permission is done through the AccessService

User Permissions

You can also give individual users, access to specific actions on resources as well. This library provides Doctrine entities and a mapper to make this happen -- but you could wire your own UserPermissionProviderInterface very easily. In short, this lets the AccessService use the authenticated user to determine whether or not the logged-in individual can perform an action that supersedes what his role permissions otherwise grant. User Permissions are meant to be more permissive, not restrictive.

User API Tokens

This module also provides a utility with which to generate UserApiToken objects. See tests for usage.

Adding the mapping for this entity to your User entity is very trivial

/**
 * @ORM\OneToMany(targetEntity="CirclicalUser\Entity\UserApiToken", mappedBy="user");
 */
private $api_tokens;

Pulling a token to perform your own logic with it, is done with UserApiTokenMapper, e.g.

$token = $this->userApiTokenMapper->get('d0cad39b-f269-405e-b3f9-d45b349c0587');

When it is used/consumed, you can tag it:

$token->tagUse();

Scope (as defined by your application) is defined with bit flags

$token->addScope(FooApi::SCOPE_QUERY);

Cookie Security

You can configure whether or not your cookies should have the secure flag set to 'true' by adjusting the auth/secure_cookies configuration value. This value accepts a boolean or closure if you need to run a discovery method on your server, perhaps, for example, to check if the current request is coming through SSL.

Installation

Composer Tune-Ups

This package's dependency chain depends on doctrine/doctrine-module, which in turn depends on laminas/laminas-cache.

Laminas cache is wired in a strange way, and might attempt to install a ton of problematic adapters (depending on your PHP version). It is recommended that you use composer's replace to keep that mess out of your application, like so:

  "replace": {    
    "laminas/laminas-cache-storage-adapter-apc": "*",
    "laminas/laminas-cache-storage-adapter-apcu": "*",
    "laminas/laminas-cache-storage-adapter-blackhole": "*",
    "laminas/laminas-cache-storage-adapter-dba": "*",
    "laminas/laminas-cache-storage-adapter-ext-mongodb": "*",
    "laminas/laminas-cache-storage-adapter-filesystem": "*",
    "laminas/laminas-cache-storage-adapter-memcache": "*",
    "laminas/laminas-cache-storage-adapter-memcached": "*",
    "laminas/laminas-cache-storage-adapter-mongodb": "*",
    "laminas/laminas-cache-storage-adapter-redis": "*",
    "laminas/laminas-cache-storage-adapter-session": "*",
    "laminas/laminas-cache-storage-adapter-wincache": "*",
    "laminas/laminas-cache-storage-adapter-xcache": "*",
    "laminas/laminas-cache-storage-adapter-zend-server": "*",
  },

What's more, since you are using this library, you probably aren't using laminas/laminas-authentication, which is also installed by doctrine-module. You can go ahead and throw this line into your replace block as well:

"laminas/laminas-authentication": "*",

bishwopl/zf3-circlical-user 适用场景与选型建议

bishwopl/zf3-circlical-user 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 37 次下载、GitHub Stars 达 0, 最近一次更新时间为 2020 年 10 月 14 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 bishwopl/zf3-circlical-user 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 37
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 4
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 15
  • 开发语言: PHP

其他信息

  • 授权协议: MPL-2.0
  • 更新时间: 2020-10-14