關於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] 存儲「記住我」功能使用的令牌的列的名稱(若是已激活)。
相關文章
相關標籤/搜索