evil-corp/cakephp-awscognito

CakePHP 的 AwsCognito 插件

安装数: 4,748

依赖: 0

建议者: 0

安全: 0

类型:cakephp-plugin

v1.6.9 2019-01-17 20:12 UTC

This package is not auto-updated.

Last update: 2024-09-22 03:29:22 UTC


README

此插件允许通过应用程序面板管理 AWS Cognito 用户,确保它们与其本地副本同步。

此插件假设与 AWS Cognito 之间有一个单向通信渠道,其中同步字段的更改首先发生在应用程序中,然后由插件传播到 AWS Cognito。

变更日志

日期:2018-10-11

  • 重写了全部文档以反映最近的变化

文档

功能

实现

  • 用户注册。向用户发送邀请电子邮件,包含其临时密码
  • 用户注销,确保也从 Cognito 中移除
  • 通过“活动”复选框禁用/启用用户(阻止登录)
  • 密码重置
  • 更改电子邮件,可选是否发送验证码
  • 重新发送邀请电子邮件(创建账户)
  • 用户资料显示用户是否已正确与 Cognito 同步
  • 将用户头像上传到 AWS S3
  • JSON Web Token 认证器 (AwsCognitoJwtAuthenticate) 用于认证 Cognito 用户
  • 非管理员用户的 API 端点
  • 以 CSV 格式批量导入用户,预先进行验证

待办事项

  • 配置以使用电话、电子邮件或两者进行用户注册/访问(目前仅支持电子邮件)
  • 如果操作失败,用户导入不能撤销更改。请仅使用它来创建新用户以避免冲突。
  • 允许管理员更改用户头像

注释

  • 如果创建用户时用户被设置为“未激活”(active = 0),则插件将在创建后尝试在 Cognito 中禁用用户(因为不能在 Cognito 中创建未激活的用户)。如果失败,则插件将优先保证一致性,并将用户创建为“激活”状态。

安装

要使用 composer 获取插件,需要在 composer.json 中添加以下内容

  1. "require" 对象中添加插件:"evil-corp/cakephp-awscognito": "dev-master"
  2. "repositories" 数组中添加对象:`{"type": "vcs", "url": "git@bitbucket.org:evil-corp/cakephp-awscognito.git"}`
  3. 运行 composer update

注意:确保在存储库中具有正确的访问/部署权限。

在存储库中安装插件后

  1. config/bootstrap.php 中添加以下行以加载插件:Plugin::load('EvilCorp/AwsCognito', ['bootstrap' => true, 'routes' => true]);
  2. 确保存在 api_users 表。插件包含用于此的迁移,如果需要:运行 bin/cake migrations migrate -p EvilCorp/AwsCognito
  3. 在 Cognito 中创建一个用户池。请注意
    • 用户池应仅包含访问所需的数据。额外的字段应仅存在于本地表中。
    • 请确保Cognito创建用户所需的字段验证与本地表验证相同或更宽松,否则在创建用户时可能会发生错误,这些错误不会正确显示给用户。
    • 不允许用户通过Cognito更改其电子邮件或电话,这可能导致数据不同步。除密码更改外,所有用户更改都应通过插件提供的API进行。
  4. 在加载插件之前,将以下行添加到 config/bootstrap.php 中:Configure::write('AwsCognito.config', ['awscognito']);
  5. 将文件 vendor/evil-corp/cakephp-awscognito/config/awscognito.php 复制到 app/config/awscognito.php
  6. 修改文件以配置插件。(请参阅“配置变量”部分)
  7. 默认路由如下(要更改此设置,请参阅“扩展插件”部分。要禁用默认路由,请在 Plugin::load 中使用 'routes' => false
    • 插件的用户控制器应可通过 /aws-cognito/api-users 访问
    • API端点可通过 /aws-cognito/api/api-users/:action 访问

结构

EvilCorp\AwsCognito\Model\Entity\ApiUser

属性

  • aws_cognito_id (char 36) (隐藏,不可变)
  • aws_cognito_username (varchar 255) (隐藏,不可变)
  • email (varchar 255)
  • active (tinyint 1)
  • role (varchar 50)
  • first_name (varchar 50)
  • last_name (varchar 50)
  • created (datetime)
  • modified (datetime)

虚拟属性

  • full_name ("${first_name} ${last_name}")

EvilCorp\AwsCognito\Model\Table\ApiUsersTable

  • 受保护 $searchQueryFields
    • 用于表搜索配置的字段数组。
    • 抽象为受保护的属性,以便于扩展。
  • 公共 initialize()
    • 配置 CreatorsUsers 表的关联(created_by)以及 ModifiersUsers 表的关联(modified_by)。要更改使用的表,请扩展表,请参阅“扩展插件”部分。
    • 添加 Timestamp Behavior 以填充 created_atmodified_at 字段
    • 添加 Muffin/Footprint.Footprint Behavior 以填充 created_bymodified_by 字段
    • 添加 EvilCorp/AwsCognito.AwsCognito Behavior 以启用Cognito功能
    • 添加 EvilCorp/AwsCognito.ImportApiUsers Behavior 以添加批量导入功能
    • 添加 EvilCorp/AwsS3Upload.AwsS3Upload Behavior 以将用户头像上传到AWS S3
    • 添加 Search.Search Behavior 以启用搜索
  • 公共 validationDefault(Validator $validator)
    • 基本字段(id,first_name,last_name)的基本验证
    • 确保 role 字段存在并且属于配置的列表(要更改此设置,请扩展验证,请参阅“扩展插件”部分)。
  • 公共 getRoles()
    • 返回配置的角色的数组。
    • 如果配置不存在或无效,则抛出异常。

EvilCorp\AwsCognito\Model\Traits\AwsCognitoSaveTrait

此trait由ApiUsersTable使用。其功能是

  • 覆盖 saveMany 方法以捕获在尝试一次保存多个用户时发生的任何Cognito异常或保存错误。
  • 在这种情况下,负责回滚在Cognito中引起的变化,必要时删除新用户。
  • 未来还应该负责回滚编辑。

EvilCorp\AwsCognito\Model\Behavior\AwsCognitoBehavior

此Behavior负责启用所有与Cognito相关的功能。其方法如下

  • 公共 validationResendInvitationEmail(Validator $validator)
    • 包含用于重发邀请电子邮件操作的验证器
  • public validationChangeEmail(Validator $validator)
    • 用于邮箱更改操作的验证器
  • public buildValidator(Event $event, Validator $validator, $name)
    • 验证器的回调
    • 负责确保密码字段被要求并按相应方式验证
  • public buildRules(Event $event, RulesChecker $rules)
    • 添加应用规则
    • 确保Cognito用户名是唯一的
    • 确保邮箱是唯一的
    • 阻止编辑Cognito用户名
    • 阻止编辑Cognito ID
    • 阻止传统方式编辑邮箱(有选项允许changeEmail和resendInvitationEmail方法更改它)
  • public beforeSave(Event $event, EntityInterface $entity, ArrayObject $options)
    • 在保存用户之前,此回调执行以下操作
      • 如果用户是新的,则调用createCognitoUser
      • 如果用户正在编辑并且active字段已更改,则根据情况调用disableCognitoUserenableCognitoUser
  • public beforeDelete(Event $event, EntityInterface $entity, ArrayObject $options)
    • 在从数据库中删除用户之前,此回调调用deleteCognitoUser以在Cognito中删除它。
  • public changeEmail(EntityInterface $entity, $new_email, bool $require_verification = true)
    • 此方法封装了用户的邮箱更改,以便可以轻松地从Controller中调用。
    • 在Cognito中更改邮箱并在成功的情况下将更改保存到数据库。
    • 允许通过$require_verification参数选择邮箱是否需要验证。
    • 如果需要验证,Cognito将向用户发送验证码邮件。客户端的开发者可以使用此邮件来验证邮箱。
  • public resendInvitationEmail(EntityInterface $entity, $new_email)
    • 如果账户已过期(刷新账户),或者邮箱地址不正确(允许更改),则重新发送邀请邮件。
  • public getWithCognitoData($id, $options = [])
    • 在数据库中查找用户并添加Cognito信息
    • 调用Cognito以添加字段,因此性能不高。
    • 用于Controller中客户的详细页面。
    • 添加以下字段
      • bool aws_cognito_synced:指示用户的所有相关字段是否已正确与Cognito同步。通常永远不会是假的。
      • array aws_cognito_attributes:Cognito额外属性的列表
      • array aws_cognito_status:包含显示Cognito状态的字段,并已解析以便更易于阅读
        • aws_cognito_status['code']:状态代码
        • aws_cognito_status['title']:状态标题
        • aws_cognito_status['description']:状态描述
    • 如果未在Cognito中找到用户,不会抛出异常,而是字段为空,且aws_cognito_synced为假。
  • public resetCognitoPassword(EntityInterface $entity)
    • 清除密码。
    • 将在用户下次登录时启动密码更改过程。
    • 如果用户从未登录过,或者如果邮箱/电话未验证以发送验证消息,则无法清除密码。
  • public deleteCognitoUser(EntityInterface $entity)
    • 从Cognito中删除用户。
    • 在从本地表中删除用户时自动使用。
    • 此方法公开,因为它对批量处理和事务过程很有用。
  • protected createCognitoClient()
    • 用于初始化与Cognito连接的内部方法。
  • protected processCognitoUser(Result $cognito_user)
    • 处理由Cognito SDK返回的用户数据,并将其转换为更符合CakePHP的数据。
  • protected titleForUserStatus($status)
    • 返回用户Cognito状态的标题
  • 受保护 descriptionForUserStatus($status)
    • 返回用户Cognito状态的描述
  • 受保护 createCognitoUser(EntityInterface $entity, $message_action = null)
    • 用于在Cognito中创建新用户,或重新发送邀请邮件
  • 受保护 awsExceptionToEntityErrors(AwsException $exception, EntityInterface $entity)
    • 解析Cognito的一些异常并将它们转换为实体的验证错误
    • 涵盖诸如无效或重复的电子邮件和用户等情况
    • 由其他方法使用,以使过程更加CakePHP友好
  • 受保护 disableCognitoUser(EntityInterface $entity)
    • 在Cognito中禁用用户,阻止其登录
  • 受保护 enableCognitoUser(EntityInterface $entity)
    • 在Cognito中启用用户,恢复其登录

EvilCorp\AwsCognito\Model\Behavior\ImportApiUsersBehavior

此Behavior负责添加用户导入功能。目前,这包括批量导入CSV格式的用户的能力。其方法包括

  • 公共 validateMany(array $rows, $max_errors = false, array $options = []): array
    • $rows 是用户数组,可以包含CakePHP的实体或格式化为CakePHP的用户数据数组
    • 此方法将数组 $rows 中的所有用户转换为CakePHP的实体
    • 使用用户名搜索现有实体,并用传入的更改修补它们。其余的将被创建。
    • 使用实体验证和应用规则验证所有实体
    • 同时验证它们之间是否存在重复项
    • 返回包含所有验证的应用实体数组。可以通过调用 $entity->getErrors() 来查看错误
  • 公共 csvDataToAssociativeArray(string $csv_data, array $fields = []): array
    • 将输入的CSV格式的数据 ($csv_data) 转换为格式化为CakePHP的用户数组。
    • 期望字段按照特定顺序
    • 默认期望基本字段 (aws_cognito_username, email, first_name, last_name)
    • 要更改顺序或字段的数量,请使用参数 $fields。

EvilCorp\AwsCognito\Controller\ApiUsersController

使用以下Traits

  • BaseCrudTrait
  • ImportApiUsersTrait
  • AwsCognitoTrait

EvilCorp\AwsCognito\Controller\Traits\BaseCrudTrait

提供管理员用户的基本操作

  • /aws-cognito/api-users/index (GET)
    • 用户列表
  • /aws-cognito/api-users/view/:id (GET)
    • 用户详情
    • 包含Cognito的数据
  • /aws-cognito/api-users/add (GET, POST)
    • 添加用户
  • /aws-cognito/api-users/edit/:id (GET, POST)
    • 编辑用户的基本字段(first_name, last_name等)
  • /aws-cognito/api-users/change-email/:id (GET, POST)
    • 更改用户电子邮件
    • 允许决定电子邮件是否需要验证(在这种情况下,将发送验证邮件)
  • /aws-cognito/api-users/delete/:id (POST, DELETE)
    • 删除用户

EvilCorp\AwsCognito\Controller\Traits\ImportApiUsersTrait

提供用户导入操作

  • /aws-cognito/api-users/import (GET, POST)
    • 允许通过CSV格式的文本字段批量导入用户

EvilCorp\AwsCognito\Controller\Traits\AwsCognitoTrait

提供与Cognito功能相关的操作

  • /aws-cognito/api-users/activate/:id (POST)
    • 激活用户(允许登录)
  • /aws-cognito/api-users/deactivate/:id (POST)
    • 禁用用户(阻止登录)
  • /aws-cognito/api-users/reset-password/:id (POST)
    • 清除用户密码
    • 将在用户下次登录时启动密码更改过程。
    • 如果用户从未登录过,或者如果邮箱/电话未验证以发送验证消息,则无法清除密码。
  • /aws-cognito/api-users/resend-invitation-email/:id (GET, POST)
    • 重新发送邀请邮件
    • 刷新账户的过期时间
    • 允许更改电子邮件

EvilCorp\AwsCognito\Controller\Api\ApiUsersController

使用 BaseApiEndpointsTrait

EvilCorp\AwsCognito\Controller\Traits\BaseApiEndpointsTrait

提供以下端点供客户端开发者使用

  • /aws-cognito/api/api-users/profile (GET)
    • 用户配置文件详情
  • /aws-cognito/api/api-users/profile (POST)
    • 允许编辑用户资料(仅基本字段,如first_name和last_name)
  • /aws-cognito/api/api-users/change-email (POST)
    • 允许更改用户邮箱
    • 将发送包含验证码的邮件到新邮箱地址。开发者需要使用该验证码与cognito通信并验证邮箱。
  • /aws-cognito/api/api-users/upload-avatar (POST)
    • 允许更改用户头像
    • 期望在HTTP请求体中发送原始图像二进制文件
    • 将头像上传到S3

配置变量

配置变量存储在应用程序配置数组中,与其它配置一样(默认为config/app.php)。

可用的配置有

'AwsCognito' => [
    'AccessKeys' => [
        'id' => 'NSWPXE30F49XAOF',
        'secret' => 'QIQNxRO2425bb040e4adc8cc02fae05063c3c'
    ],
    'UserPool' => [
        'id' => 'us-east-2_rjaob1HaR',
    ],
    'IdentityProviderClient' => [
        'settings' => [], //https://docs.aws.amazon.com/sdkforruby/api/Aws/CognitoIdentityProvider/Client.html#initialize-instance_method
    ],
],
'ApiUsers' => [
    /* available user roles */
    'roles' => [
        'user' => __d('EvilCorp/AwsCognito', 'API User'),
    ],
    /* the max amount of errors alloweds before the validation process of the imported data is halted */
    'import_max_errors' => 10,

    /* the limit of accepted rows in the importing CSV data */
    'import_max_rows' => 500,
]

测试

目前该插件约90%的代码行覆盖率,70%的方法和函数覆盖率。

要运行测试,必须单独下载仓库(以便composer注册开发模式)。运行composer install来安装依赖,然后运行测试:vendor/bin/phpunit

扩展插件

更改路由

要更改插件的默认路由(/aws-cognito/api-users),可以在config/routes.php中添加以下内容,必须在bootstrap.php中加载插件时将'routes' => false设置为Plugin::load

然后,可以在config/routes.php中的基础作用域(/)内使用以下内容。

  • 将路由/aws-cognito/api-users替换为/api-users

      $routes->connect('/api-users/*', [
          'plugin' => 'EvilCorp/AwsCognito', 'controller' => 'ApiUsers'
      ]);
      $routes->connect('/api-users/:action', [
          'plugin' => 'EvilCorp/AwsCognito', 'controller' => 'ApiUsers', 'action' => ':action'
      ]);
      $routes->connect('/api-users/:action/:id', [
          'plugin' => 'EvilCorp/AwsCognito', 'controller' => 'ApiUsers', 'action' => ':action'
      ],  ['id' => '\d+', 'pass' => ['id']]);
    
    
  • 对于REST API,可以按照以下方式替换

      Router::prefix('api', function ($routes) {
          $routes->extensions(['json']);
    
           /* Api Users */
           $routes->connect('/me', [
              'plugin'     => 'EvilCorp/AwsCognito',
              'prefix'     => 'Api',
              'controller' => 'ApiUsers',
              'action'     => 'profile',
              '_method'    => 'GET'
          ]);
    
          $routes->connect('/me', [
              'plugin'     => 'EvilCorp/AwsCognito',
              'prefix'     => 'Api',
              'controller' => 'ApiUsers',
              'action'     => 'editProfile',
              '_method'    => 'PATCH'
          ]);
    
          $routes->connect('/me/avatar', [
              'plugin'     => 'EvilCorp/AwsCognito',
              'prefix'     => 'Api',
              'controller' => 'ApiUsers',
              'action'     => 'uploadAvatar',
              '_method'    => 'PUT'
          ]);
    
          $routes->connect('/me/email', [
              'plugin'     => 'EvilCorp/AwsCognito',
              'prefix'     => 'Api',
              'controller' => 'ApiUsers',
              'action'     => 'changeEmail',
              '_method'    => 'PUT'
          ]);
    
      });
    

覆盖视图

为了覆盖模板而不需要扩展控制器,应将新模板放置在以下位置

src/Template/Plugin/EvilCorp/AwsCognito/ApiUsers/*

例如,要替换index模板

src/Template/Plugin/EvilCorp/AwsCognito/ApiUsers/index.ctp

扩展控制器/模型

如果需要扩展控制器和模型(例如,向ApiUsers模型添加新关联),最佳做法如下

首先,扩展ApiUsersTable

//archivo: src/Model/Table/ApiUsersTable.php
namespace App\Model\Table;

use EvilCorp\AwsCognito\Model\Entity\ApiUser;
use EvilCorp\AwsCognito\Model\Table\ApiUsersTable as AwsApiUsersTable;

class ApiUsersTable extends AwsApiUsersTable
{
    //esto solo es necesario si no se va a extender la Entidad
    protected $_entityClass = 'EvilCorp\AwsCognito\Model\Entity\ApiUser';

    public function initialize(array $config)
    {
        parent::initialize($config);

        //cambiando la tabla de usuarioa administradores
        $this->association('Creators')->className('AppUsers');
        $this->association('Modifiers')->className('AppUsers');

        //agregar nuevas asociaciones aca
         $this->belongsToMany('FunctionalUnits', [
            'through' => 'ApiUsersFunctionalUnits',
            'saveStrategy' =>'append',
        ]);

        //y podemos facilmente reconfigurar el search cambiando estos valores
        $this->searchQueryFields = [
            'ApiUsers.aws_cognito_username',
            'ApiUsers.email',
            'ApiUsers.phone',
            'ApiUsers.first_name',
            'ApiUsers.last_name',
        ];
    }

    //extendiendo la validación por defecto
    public function validationDefault(Validator $validator)
    {
        $validator = parent::validationDefault($validator);

        //se puede remover la validacion de un campo si no se usa
        $validator->remove('role');

        //y agregar campos nuevos
        $validator
            ->scalar('phone')
            ->allowEmpty('phone');

        return $validator;
    }


}

然后扩展ApiUsersController

//archivo: src/Controller/ApiUsersController.php
namespace App\Controller;

use EvilCorp\AwsCognito\Controller\ApiUsersController as AwsApiUsersController;
use App\Model\Table\ApiUsersTable;

class ApiUsersController extends AwsApiUsersController
{
    //aca se pueden agregar nuevas acciones o reemplazar las existentes

    //por ejemplo el index:
    public function index()
    {
        $this->paginate['contain'] = ['PointsOfSale'];

        $this->set('api_users', $this->paginate('ApiUsers'));
        $this->set('_serialize', ['api_users']);
    }
}

可选地,可以扩展实体ApiUser

//archivo: src/Model/Entity/ApiUser.php
namespace App\Model\Entity;

use EvilCorp\AwsCognito\Model\Entity\ApiUser as AwsApiUser;

class ApiUser extends AwsApiUser
{
    protected $_accessible = [
        '*' => true,
        'id' => false,
        'role' => false,

        //cognito fields:
        'aws_cognito_username' => false,
        'aws_cognito_id' => false,
        'email' => false,

        //dejando lo demás como viene, podemos agregar nuevos campos
        'phone' => false
    ];

    //podemos agregar nuevas virtual properties aca
}

现在,为了保留插件的模板并只需添加新模板(或要替换的模板),可以修改路由,使新操作使用此控制器,而其他操作则导向插件内的控制器

//el index lleva al nuevo controller
$routes->connect('/api-users', ['controller' => 'ApiUsers', 'action' => 'index']);
$routes->connect('/api-users/index', ['controller' => 'ApiUsers', 'action' => 'index']);

//las demas rutas llevan al controller del plugin
$routes->connect('/api-users/*', [
    'plugin' => 'EvilCorp/AwsCognito', 'controller' => 'ApiUsers'
]);
$routes->connect('/api-users/:action', [
    'plugin' => 'EvilCorp/AwsCognito', 'controller' => 'ApiUsers', 'action' => ':action'
]);
$routes->connect('/api-users/:action/:id', [
    'plugin' => 'EvilCorp/AwsCognito', 'controller' => 'ApiUsers', 'action' => ':action'
],  ['id' => '\d+', 'pass' => ['id']]);