关于Luthier CI SimpleAuth

SimpleAuth

内容 Contents

  1. 介绍 Introduction
  2. 安装 Installation
    1. 第1步:复制所需的文件 Step 1: Copy the required files
    2. 第2步:安装数据库 Step 2: Install the database
    3. 第3步:定义路线 Step 3: Define the routes
  3. SimpleAuth控制器 SimpleAuth Controller
    1. 自定义用户注册表单 Customize the user registration form
  4. SimpleAuth中间件 SimpleAuth Middleware
  5. SimpleAuth库 SimpleAuth Library
    1. 基本功能 Basic functions
      1. 获取当前用户 Obtaining the current user
      2. 验证用户是不是来宾(匿名) Verify if a user is a guest (anonymous)
      3. 验证用户的角色 Verify the role of a user
      4. 验证用户的权限 Verify the user's permissions
    2. 访问控制列表(ACL)功能 Access Control List (ACL) functions
    3. 其余功能 Other functions
  6. 意见和翻译 Views and translations
    1. 设置SimpleAuth外观 Setting the SimpleAuth skin
    2. 设置SimpleAuth语言 Setting the SimpleAuth language
    3. 使用您本身的观点 Using your own views
  7. SimpleAuth配置 SimpleAuth configuration
    1. 通常配置 General configuration
    2. 启用/禁用功能 Enabling/Disabling features
    3. 视图配置 Views configuration
    4. 访问控制列表(ACL)的配置 Configuration of Access Control Lists (ACL)
    5. 电子邮件配置 Email onfiguration
    6. 配置“提醒我”功能 Configuration of the "Remind me" functionality
    7. 数据库配置 Database configuration

介绍 Introduction

使用SimpleAuth,您能够在不到5分钟的时间内为您的应用程序添加登陆和用户注册!SimpleAuth包含一个controller(SimpleAuthController),一个中间件(SimpleAuthMiddleware),一个库(Simple_auth)以及从Luthier CI Authentication Framework构建的其余元素。php

安装 Installation

因为安装是经过 Built-in CLI Tools of Luthier CI, 内置CLI工具的命令完成的,所以请务必在路由文件中定义如下命令 cli .php:css

<?php
# application/routes/cli.php

Luthier\Cli::maker();      // 'luthier make' command
Luthier\Cli::migrations(); // 'luthier migrate' command
复制代码

此外,还必须在启动以前正确配置与数据库(in application/config/database.php)和迁移(in application/config/migration.php)的链接。web

第1步:复制所需的文件

在应用程序的根文件夹中运行:数据库

php index.php luthier make auth
复制代码

若是一切顺利,您应该拥有如下新文件:数组

application
    |- config
    |   |- auth.php
    |
    |- controllers
    |   |- SimpleAuthController.php
    |
    |- libraries
    |   |- Simple_Auth.php
    |
    |- middleware
    |   |- SimpleAuthMiddleware.php
    |
    |- migrations
    |   |- 20180516000000_create_users_table.php
    |   |- 20180516000001_create_password_resets_table.php
    |   |- 20180516000002_create_email_verifications_table.php
    |   |- 20180516000003_create_login_attempts_table.php
    |   |- 20180516000004_create_user_permissions_categories_table.php
    |   |- 20180516000005_create_user_permissions_table.php
    |
    |- security
    |   |- providers
    |       |- User.php
    |       |- UserProvider.php
复制代码

第2步:安装数据库

在应用程序的根文件夹中运行:安全

php index.php luthier migrate
复制代码

您应该可以看到如下输出:bash

MIGRATED: 20180516000000_create_users_table.php
MIGRATED: 20180516000001_create_password_resets_table.php
MIGRATED: 20180516000002_create_email_verifications_table.php
MIGRATED: 20180516000003_create_login_attempts_table.php
MIGRATED: 20180516000004_create_user_permissions_categories_table.php
MIGRATED: 20180516000005_create_user_permissions_table.php
复制代码

第3步:定义路由

在您的web.php文件中,添加如下行:cookie

Route::auth();
复制代码

这是定义全部这些路线的快捷方式:session

Route::match(['get', 'post'], 'login', 'SimpleAuthController@login')->name('login');
Route::post('logout', 'SimpleAuthController@logout')->name('logout');
Route::get('email_verification/{token}', 'SimpleAuthController@emailVerification')->name('email_verification');
Route::match(['get', 'post'], 'signup', 'SimpleAuthController@signup')->name('signup');
Route::match(['get', 'post'], 'confirm_password', 'SimpleAuthController@confirmPassword')->name('confirm_password');
Route::group('password-reset', function(){
    Route::match(['get','post'], '/', 'SimpleAuthController@passwordReset')->name('password_reset');
    Route::match(['get','post'], '{token}', 'SimpleAuthController@passwordResetForm')->name('password_reset_form');
});
复制代码

若是您已正确执行全部步骤,则在访问该URL时,/login您应该会看到新的登陆屏幕:app

SimpleAuth login screen
有关会话注销路径的信息
默认状况下,路由logout仅接受POST请求,所以/logout除非使用指向该路由的HTML表单,不然指向该URL的连接将没法关闭会话。要容许GET请求,请使用Route::auth(FALSE)

SimpleAuth控制器

SimpleAuth控制器(SimpleAuthController)包含身份验证操做,如登陆,用户注册,密码重置等。它看起来相似于:

<?php
# application/controllers/SimpleAuthController.php

defined('BASEPATH') OR exit('No direct script access allowed');

/* (...) */

class SimpleAuthController extends Luthier\Auth\SimpleAuth\Controller {

    /** * Sign up form fields * * (...) */
    public function getSignupFields() {
        return [ /* (...) */ ];
    }

    /** * Fillable database user fields * * (...) * @access public */
    public function getUserFields() {
        return [ /* (...) */ ];
    }
}
复制代码

除非您想要自定义SimpleAuth,不然您不须要向此驱动程序添加任何其余内容,由于您扩展的类(Luthier\Auth\SimpleAuth\Controller)已经定义了身份验证逻辑,而且在路由文件中Route::auth()已经定义了应该指向此处的全部路由。

覆盖方法消除了任何基本功能
它看起来很明显,可是若是你覆盖SimpleAuth驱动程序的任何方法,你将丢失皮肤(主题),翻译视图,用户注册表单构造函数和其余预先配置的有用函数的系统。 , 以下面所描述的

自定义用户注册表单

( Customize the user registration form ) 您能够根据本身的喜爱更改注册表单的字段。为此,getSignupFields()SimpleAuth驱动程序的方法必须返回一个定义其结构的数组,语法以下:

public function getSignupFields() {
    return [
        'Field name 1' => [
            'Field type',
            'Field label',
            [ /* HTML5 attributes array */ ],
            [ /* CI Validation rules array */] ,
            [ /* CI Validation error essages array (Optional)*/]
        ],
        'Field name 2' => [
            'Field type',
            'Field label',
            [ /* ... */ ],
            [ /* ... */ ] ,
        ],

        // ( ... )

        'Field name N' => [
            'Field type',
            'Field label',
            [ /* ... */ ],
            [ /* ... */ ] ,
        ]
    ];
}
复制代码

另外一方面,getUserFields()SimpleAuth驱动程序的方法必须返回一个数组,该数组包含将存储在新用户中的该表单的字段,其中数组的每一个元素都匹配该注册表单的字段和名称数据库中users表的列:

public function getUserFields() {
    return [
        'first_name',
        'last_name',
        'username',
        'gender',
        'email',
        'password',
        'role',
    ];
}
复制代码

Laravel用户会注意到这$fillable与EloquentORM模型的属性彻底相同,但应用于SimpleAuth用户注册表单。

SimpleAuth中间件

SimpleAuth中间件 (SimpleAuthMiddleware) 是须要用户预身份验证的路由的第一道防线。此中间件自动负责验证用户的当前状态:

  • 若是用户已经过身份验证,则请求仍然正常
  • 若是用户未通过身份验证,则会尝试使用“记住我”功能(若是已激活)恢复会话
  • 若是没法恢复任何先前的会话,则用户将被重定向到登陆屏幕

您能够根据须要在尽量多的路由和路由组中使用SimpleAuth中间件,甚至能够将其与您本身的中间件结合使用,以添加额外的安全层。

例:

<?php
# application/routes/web.php

// SimpleAuth default routes:

Route::auth();

// Public routes:

Route::get('/', 'FrontendController@homepage')->name('homepage');
Route::get('/about', 'FrontendController@about')->name('about');
Route::match(['get','post'], '/contact', 'FrontendController@contact')->name('contact');

// Protected routes: access here without being authenticated will direct to the
// login screen

Route::group('dashboard', ['middleware' => ['SimpleAuthMiddleware']], function(){
    Route::get('/', 'UserArea@dashboard');
});
复制代码

SimpleAuth库

SimpleAuth库是Luthier CI身份验证框架类的包装器,Auth采用本机CodeIgniter库的格式,所以您可使用您应该已知的语法来使用它的全部方法。

要开始使用SimpleAuth库,您必须将其加载到框架中:

$this->load->library('Simple_auth');
复制代码

基本功能 ( Basic functions )

注意: Luthier\Auth 当您使用SimpleAuth时,并不是全部类的方法都相关,所以咱们仅列出可能有用的方法

获取当前用户 ( Obtaining the current user )

要获取在应用程序中进行身份验证的用户,请使用user()返回用户对象的方法,或者NULL若是不存在通过身份验证的用户:

// The current user object:
$userObject = $this->simple_auth->user();

// With the user object you have access to:
// ...the user entity of the database:
$user = $userObject->getEntity();

// ...their roles:
$roles = $userObject->getRoles();

// ...and its permissions:
$permissions = $userObject->getPermissions();
复制代码

若是您使用默认的SimpleAuth用户提供程序,则能够直接访问当前用户的数据,而无需使用该getEntity()方法。如下表达式是等效的:

$this->simple_auth->user()->getEntity()->first_name;

$this->simple_auth->user()->first_name;
复制代码
验证用户是不是来宾(匿名) Verify if a user is a guest (anonymous)

要快速验证用户是否被邀请,请使用该isGuest()方法,TRUE若是用户还没有登陆,则返回该方法,FALSE不然:

$this->simple_auth->isGuest();
复制代码
验证用户的角色 Verify the role of a user

要验证用户是否具备特定角色,请使用该方法isRole(role),TRUE若是用户具备该角色role,或者FALSE若是他不拥有该角色,或者没有通过身份验证的用户,则使用该方法:

$this->simple_auth->isRole('ADMIN');
复制代码
验证用户的权限 Verify the user's permissions

要验证用户是否具备特定权限,请使用该方法isGranted($permission),该方法TRUE在用户具备权限时返回permission,或者FALSE若是用户没有该权限,或者没有通过身份验证的用户

例:

$this->simple_auth->isGranted('general.read');
复制代码

可使用替代语法来验证用户是否属于以特定短语/类别开头的角色:

// The following will give TRUE for permits that begin with 'general.'
$this->simple_auth->isGranted('general.*');
复制代码

访问控制列表(ACL)功能 Access Control List (ACL) functions

访问控制列表(ACL)是一种可选的身份验证功能,用于为每一个通过身份验证的用户设置特定权限。所以,用户能够具备角色和若干分配的权限,以保证(或拒绝)访问应用程序的某些资源。

在SimpleAuth中没有用户组或相似的东西,用户权限存储在变量深度权限树中(子权限限制取决于您)。

请考虑如下权限:

ID      NAME        PARENT_ID
-----------------------------
1       general     [null]
2       read        1
3       write       1
4       delete      1
5       local       4
6       global      4
复制代码

这个权限分配:

ID      USERNAME    PERMISSION_ID
---------------------------------
1       anderson    2
2       anderson    5
3       julio       3
4       julio       6
复制代码

例如,当用户anderson登陆时,您将拥有如下权限:

general.read
general.delete.local
复制代码

当用户julio登陆时,他将拥有如下权限:

general.write
general.delete.global
复制代码

权限树存储在user_permissions_categories表中,而权限分配存储在user_permissions表中,二者都由SimpleAuth中包含的迁移建立。没有自动建立或删除权限的方法,所以您必须手动执行此操做。


这些是SimpleAuth库中可用的ACL函数:

permissionsExists(string $permission) : [bool]

验证$permission访问控制列表(ACL)表中是否存在权限。

例:

$this->simple_auth->permissionExists('general.read');
复制代码
grantPermission(string permission**, *string* **username = NULL) : [bool]

将权限分配permission给用户username,TRUE若是操做成功FALSE则返回。

// Assigning the 'general.read' permission to the current user
$this->simple_auth->grantPermission('general.read');
复制代码
revokePermission(string permission**, *string* **username = NULL) : [bool]

撤消对permission用户的权限username,TRUE若是操做成功或FALSE以其余方式返回。

// Revoking the 'general.read' permission to the current user
$this->simple_auth->revokePermission('general.read');
复制代码

其余功能 Other functions

如下功能对于与用户身份验证相关的特殊任务很是有用:

isFullyAutenticated() : [bool]

TRUE若是用户彻底经过身份验证,FALSE则返回。彻底经过身份验证的用户是直接登陆而不是经过“记住我”功能登陆的用户。

promptPassword(string $route = 'confirm_password') : [bool]

$route若是用户未彻底经过身份验证,则会自动重定向到路径。此功能对于经过“记住我”功能再次请求通过身份验证的用户确认密码很是有用。

searchUser(mixed $search) : [object|null]

返回在标准下找到的用户的对象search,或者NULL若是找不到任何对象。根据变量的类型search,此方法执行三种类型的搜索:

  • int: 它将使用匹配的主键(配置simpleauth_id_col)搜索并返回用户
  • string: 它将在登陆期间搜索并返回与用户名列集值匹配的第一个用户(配置simpleauth_username_col)
  • array: 它等同于where($search)CodeIgniter QueryBuilder 的方法。

例:

// It will search the user with ID 1
$this->simple_auth->searchUser(1);

// It will search the user with the username/email column equal to 'admin@admin.com'
$this->simple_auth->searchUser('admin@admin.com');

// It will search for the user whose column value 'gender' is 'm' and 'active' is equal to 1
$this->simple_auth->searchUser(['gender' => 'm', 'active' => 1]);
复制代码
updateUser(int|string $search) : [void]

更新在search标准下找到的用户。根据变量的类型search,此方法执行两种不一样类型的更新:

  • int: 将使用匹配的主键值(配置simpleauth_id_col)搜索和更新第一个用户
  • string: 将匹配登陆期间为用户名设置的列值搜索并更新第一个用户(配置simpleauth_username_col)

例:

// It will replace the user's data with ID 1
$this->simple_auth->updateUser(1, ['first_name' => 'John']);

// It will replace the user's data with the user name / email column equal to 'admin@admin.com'
$this->simple_auth->searchUser('admin@admin.com', ['gender' => 'f']);
复制代码
createUser(array $data) : [void]

使用data数组的值在数据库中建立新用户。data数组的每一个索引对应于用户表中的一个列,在simpleauth_users_table配置中定义

例:

$this->simple_auth->createUser(
    [
        'first_name' => 'Admin',
        'last_name'  => 'Admin',
        'username'   => 'admin',
        'email'      => 'admin@admin.com',
        'password'   => 'admin',
        'gender'     => 'm',
        'role'       => 'admin',
        'verified'   => 1
    ]
);
复制代码

若是列的名称与simpleauth_password_col配置中设置的名称匹配,则此函数会自动建立密码哈希

意见和翻译 Views and translations

SimpleAuth使您能够在预约的设计(皮肤)之间进行选择或使用您本身的视图。SimpleAuth中包含的设计具备翻译成多种语言的优势。目前,支持的语言以下:

  • English
  • Spanish

设置SimpleAuth外观 Setting the SimpleAuth skin

要更改视图中使用的外观,请修改simpleauth_skinSimpleAuth配置文件中的选项:

# application/config/auth.php

$config['simpleauth_skin'] = 'default';
复制代码

设置SimpleAuth语言 Setting the SimpleAuth language

外观使用的语言取决于framework()主配置文件的languageoption($config['language'])的值application/config/config.php。若是在SimpleAuth支持的语言中找不到当前语言,english则将使用English()。

使用您本身的观点 Using your own views

您可使用本身的视图,而无需覆盖SimpleAuth驱动程序方法。SimpleAuth总共使用了6个视图:

  • login.php: 登陆视图
  • signup.php: 用户注册视图
  • password_prompt.php: 当前密码确认视图(“提醒我”功能)
  • password_reset.php: 密码重置请求表单的视图
  • password_reset_form.php: 密码重置表单的视图
  • message.php: 通用消息的视图

所以,要使用您本身的视图,只需在文件夹中建立一个文件,其中包含要替换的视图的名称simpleauth(若是它不存在,您必须先建立它)views。例如:

application/views/simpleauth/login.php
application/views/simpleauth/message.php
application/views/simpleauth/password_prompt.php
application/views/simpleauth/password_reset.php
application/views/simpleauth/password_reset_form.php
application/views/simpleauth/signup.php
复制代码

SimpleAuth配置 SimpleAuth configuration

SimpleAuth配置位于application/config/auth.php文件中。接下来,简要说明每一个元素:

General configuration

  • auth_login_route: *[string]*登陆路径。若是使用该Route::auth()方法定义SimpleAuth路由,则将忽略此值。
  • auth_logout_route: [string] 注销路径。若是使用该Route::auth()方法定义SimpleAuth路由,则将忽略此值。
  • auth_login_route_redirect: [string] 成功登陆时的重定向路径
  • auth_logout_route_redirect: [string] 注销后当即重定向路径。
  • auth_route_auto_redirect: [array] auth_login_route_redirect在用户已通过身份验证的状况下将激活自动重定向到路径的路由。
  • auth_form_username_field: [string] 与要进行身份验证的用户名/电子邮件对应的登陆表单字段的名称。
  • auth_form_username_field: [string] 与要验证的用户密码对应的登陆表单字段的名称。
  • auth_session_var: [string] Luthier CI身份验证模块使用的会话变量的名称。

启用/禁用功能 Enabling/Disabling features

  • simpleauth_enable_signup: [bool] 激活用户注册表单。
  • simpleauth_enable_password_reset: [bool] 激活密码重置表单。
  • simpleauth_enable_remember_me: [bool] 根据cookie激活“记住我”功能。
  • simpleauth_enable_email_verification: [bool] 在用户注册过程当中激活电子邮件验证。要使其正常工做,必须正确配置框架的电子邮件。
  • simpleauth_enforce_email_verification: [bool] 当此选项TRUE为时,SimpleAuth将拒绝登陆没有通过验证的电子邮件账户的用户。
  • simpleauth_enable_brute_force_protection: [bool] 启用暴力登陆攻击防护。
  • simpleauth_enable_acl: [bool] 激活访问控制列表(ACL)

视图配置 Views configuration

  • simpleauth_skin: [string] SimpleAuth包含的视图中使用的皮肤。默认状况下是default。
  • simpleauth_assets_dir: [string] 相对于将保存SimpleAuth视图的资源(css,js等)的应用程序的公共URL。

访问控制列表(ACL)的配置 Configuration of Access Control Lists (ACL)

  • simpleauth_acl_map: [array] 与访问控制列表使用的类别和权限类别组的名称和ID的关联排列。配置这会大大减小数据库中的查询数量,尤为是当您拥有深度权限树时。

电子邮件配置 Email configuration

  • simpleauth_email_configuration: [array | null] 使用在SimpleAuth电子邮件的电子邮件库初始化期间提供的自定义配置进行修复。请null继续使用相同的应用程序。
  • simpleauth_email_address: [string] 将出如今fromSimpleAuth发送的电子邮件字段中的电子邮件地址。
  • simpleauth_email_name: [string] 将出现from在SimpleAuth发送的电子邮件中字段旁边的名称。
  • simpleauth_email_verification_message: *[string | null]*自动消息,其中包含在应用程序中成功注册后发送给用户的电子邮件验证说明。保留它null以使用默认的SimpleAuth消息,该消息被转换为应用程序的当前语言。注意:为了正确显示包含HTML的邮件,必须首先配置电子邮件库。
  • simpleauth_password_reset_message: *[string | null]*带有密码重置说明的自动消息。保留null使用转换为应用程序当前语言的默认SimpleAuth消息。注意:为了正确显示包含HTML的邮件,必须首先配置电子邮件库。

配置“提醒我”功能 Configuration of the "Remind me" functionality

  • simpleauth_remember_me_field: [string] 与“提醒我”功能对应的登陆表单的字段名称。
  • simpleauth_remember_me_cookie: [string] 用于“提醒我”功能的cookie的名称。

数据库配置 Database configuration

  • simpleauth_user_provider: [string] SimepleAuth使用的用户提供程序。
  • simpleauth_users_table: [string] 存储用户的表的名称。
  • simpleauth_users_email_verification_table: [string] 存储电子邮件验证令牌的表的名称。
  • simpleauth_password_resets_table: [string] 存储密码重置令牌的表的名称。
  • impleauth_login_attempts_table: [string] 存储登陆尝试失败的表的名称,用于防护暴力登陆攻击。
  • simpleauth_users_acl_table: [string] 存储授予的用户权限的表的名称,由访问控制列表(ACL)使用。
  • simpleauth_users_acl_categories_table: *[string]*存储访问控制列表(ACL)使用的权限树的表的名称。
  • simpleauth_id_col: [string] 用户表的标识列的名称。
  • simpleauth_username_col: [string] 与用户表的用户名对应的列的名称。此列是在用户身份验证过程当中使用的列。
  • simpleauth_email_col: [string] 与用户表的电子邮件对应的列的名称。此列是将用于来自库的电子邮件的列。
  • simpleauth_email_first_name_col: [string] 与用户表的名字(或名称)对应的列的名称。此列是将用于来自库的电子邮件的列。
  • simpleauth_password_col: [string] 相应列的名称,用户表中的密码。此列是在用户身份验证过程当中使用的列。
  • simpleauth_role_col: [string] 与用户表中的角色对应的列的名称。此列将用于检查库中的用户角色。
  • simpleauth_active_col: [string] 与用户状态对应的列的名称。在数据库中,它必须定义为INT类型的列,其中值0对应于禁用的用户和激活1的用户。它在登陆会话期间使用。
  • simpleauth_verified_col: [string] 与用户电子邮件的验证状态对应的列的名称。在数据库中,它必须定义为INT类型的列,其中值0对应于禁用的用户和激活1的用户。它在登陆会话期间使用。
  • simpleauth_remember_me_col: [string] 存储“记住我”功能使用的令牌的列的名称(若是已激活)。
相关文章
相关标签/搜索