Laravel 5.2 新特性系列 —— 多用戶認證功能實現(xiàn)詳解
Laravel 5.2新增多用戶認證支持针肥,即同時允許不同數(shù)據(jù)表用戶(如前臺用戶、后臺用戶)登錄認證香伴。下面我們就來簡單介紹多用戶登錄及注冊功能實現(xiàn)慰枕。
1 生成認證腳手架
首先我們使用Laravel 5.2提供的認證腳手架完成初始化工作:
php artisan make:auth
該Artisan命令會生成用戶認證所需的路由、視圖以及HomeController:
去查看路由文件routes.php即纲,會發(fā)現(xiàn)該文件已經(jīng)被更新:
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/home', 'HomeController@index');
});
其中Route::auth()
定義了注冊登錄路由具帮,/home
為認證通過后跳轉(zhuǎn)路由。
2 實現(xiàn)前臺用戶登錄
接下來我們先實現(xiàn)前臺用戶登錄,也就是Laravel自帶的User用戶登錄蜂厅。通過上面的腳手架匪凡,我們已經(jīng)生成了認證所需的所有代碼,剩下要做的就是使用遷移命令創(chuàng)建用戶認證相關(guān)表:
php artisan migrate
該命令執(zhí)行后生成users表和password_resets表掘猿,分別為用戶主表和密碼重置表锹雏。
然后我們就可以在瀏覽器中輸入 http://laravel.app/register
來注冊新用戶。
3 編輯認證配置文件
要實現(xiàn)多用戶認證术奖,首先要配置認證配置文件auth.php
礁遵,這里我們實現(xiàn)的功能是前后臺用戶登錄,所以對應配置如下:
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
認證是由guard和provider兩部分構(gòu)成的采记,所以我們在這兩個配置項中分別新增了admin和admins選項佣耐。
4 創(chuàng)建后臺用戶模型
接下來我們來實現(xiàn)后臺用戶登錄,首先使用如下Artisan
命令生成后臺用戶模型:
php artisan make:model Admin --migration
帶上--migration選項會生成對應用戶表admins
唧龄,我們定義該數(shù)據(jù)表字段和users
一樣:
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
然后通過運行遷移命令生成該表:
php artisan migrate
然后更新Admin模型類如下:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
5 定義后臺用戶認證路由及控制器
接下來我們來定義后臺用戶認證路由兼砖,修改routes.php
代碼如下:
Route::group(['middleware' => ['auth:admin']], function () { //調(diào)用auth中間件時傳遞一個admin參數(shù)
Route::auth();
Route::get('home', 'HomeController@index');
Route::get('admin/login', 'Admin\AuthController@getLogin');
Route::post('admin/login', 'Admin\AuthController@postLogin');
Route::get('admin/register', 'Admin\AuthController@getRegister');
Route::post('admin/register', 'Admin\AuthController@postRegister');
Route::get('admin', 'AdminController@index');
});
然后使用Artisan
命令創(chuàng)建對應控制器:
php artisan make:controller Admin/AuthController
php artisan make:controller AdminController
編輯Admin/AuthController.php
代碼如下:
<?php
namespace App\Http\Controllers\Admin;
use App\Admin;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/admin';
protected $guard = 'admin';
protected $loginView = 'admin.login';
protected $registerView = 'admin.register';
public function __construct()
{
$this->middleware('guest:admin', ['except' => 'logout']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:admins',
'password' => 'required|confirmed|min:6',
]);
}
protected function create(array $data)
{
return Admin::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
編輯AdminController.php代碼如下:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;
class AdminController extends Controller
{
public function __construct()
{
$this->middleware('auth:admin');
}
public function index()
{
$admin = Auth::guard('admin')->user();
return $admin->name;
}
}
6 視圖文件創(chuàng)建及修改
最后我們要創(chuàng)建后臺用戶認證對應視圖文件,這里我們簡單拷貝前臺用戶視圖模板并稍作修改即可:
cp -r resources/views/auth resources/views/admin
修改resources/views/admin目錄下登錄及注冊表單提交地址:
/login -> /admin/login
/register -> /admin/register
7 修改 Middleware 文件夾中 Authenticate.php
文件既棺,設(shè)置登錄跳轉(zhuǎn)相應頁面讽挟,代碼如下:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest($guard.'/login'); //此行進行修改
}
}
return $next($request);
}