Laravel 5.5 不同使用者表登入認證 (前後臺分離)

lqylearnku發表於2019-10-22

Auth 認證原理簡述

Laravel 的認證是使用 guard 與 provider 配合完成, guard 負責認證的業務邏輯,認證資訊的服務端儲存等; provider 負責提供認證資訊的持久化資料提供。
請求提交給 guard, guard 從 provider 裡取出資料(類似使用者名稱、密碼等),驗證輸入資料與伺服器端儲存的資料是否吻合。如果提交的資料正確,再做 session 等業務的處理(如有需要)。

認證腳手架

首先我們匯入 Laravel 的自帶的認證腳手架

composer create-project --prefer-dist laravel/laravel==5.5 lv55 -vvv
cd lv55
php artisan key:generate
php artisan make:auth

執行資料庫遷移:

php artisan migrate

修改 Auth 認證的配置檔案 config/auth.php

在 gurads 處,新增 admin guard 用於後臺管理員認證

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],

在 providers 處新增 admins provider,使用 Admin 模型

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],

        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],
    ],

建立後臺管理員模型

我們再建立一個 Admin 模型,用於後臺管理員登入驗證。

php artisan make:model Admin -m

-m 引數會同時生成資料庫遷移檔案 xxxx_create_admins_table

修改 app/Admin.php 模型檔案

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

編輯 xxxx_create_admins_table 檔案,後臺管理員模型結構與前臺使用者差不多,去掉 email 欄位,name 欄位設為 unique

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAdminsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('admins', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('admins');
    }
}

管理員模型填充資料

定義一個資料模型工廠,在 database/factories/ModelFactory.php 中新增如下程式碼

<?php
use Faker\Generator as Faker;

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
*/
$factory->define(App\Admin::class, function (Faker $faker) {
    static $password;
    return [
        'name' => $faker->name,
        'password' =>  $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

使用 Faker 隨機填充使用者名稱
在 database/seeds 目錄下生成 AdminsTableSeeder.php 檔案。

php artisan make:seeder AdminsTableSeeder

編輯 database/seeds/AdminsTableSeeder.php 檔案的 run 方法,新增3個管理員使用者,密碼為 123456

public function run()
     {
          factory('App\Admin', 3)->create([
            'password' => bcrypt('123456')
             ]);
     }

在 database/seeds/DatabaseSeeder.php 的 run 方法裡呼叫 AdminsTableSeeder 類

public function run()
     {
         $this->call(AdminsTableSeeder::class);
     }

執行資料庫遷移命令

 php artisan migrate --seed

資料庫裡會建立 admins 表,並且生成了3條資料

建立後臺頁面

建立控制器

php artisan make:controller Admin/LoginController    
php artisan make:controller Admin/IndexController

其中, Admin/LoginController 負責登入邏輯; Admin/IndexController 管理登入後的首頁。

編輯 Admin/LoginController.php

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/admin';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest.admin', ['except' => 'logout']);
    }

    /**
     * 顯示後臺登入模板
     */
    public function showLoginForm()
    {
        return view('admin.login');
    }

    /**
     * 使用 admin guard
     */
    protected function guard()
    {
        return auth()->guard('admin');
    }

    /**
     * 重寫驗證時使用的使用者名稱欄位
     */
    public function username()
    {
        return 'name';
    }
}

編輯 Admin/IndexController.php

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class IndexController extends Controller
{
    /**
     * 顯示後臺管理模板首頁
     */
    public function index()
    {
        return view('admin.index');
    }
}

後臺顯示模板

複製 views/layouts/app.blade.php 成 views/layouts/admin.blade.php

編輯後臺管理佈局模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }} - Admin</title>

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-default navbar-static-top">
    <div class="container">
        <div class="navbar-header">

            <!-- Collapsed Hamburger -->
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#app-navbar-collapse">
                <span class="sr-only">Toggle Navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>

            <!-- Branding Image -->
            <a class="navbar-brand" href="{{ url('/') }}">
                {{ config('app.name', 'Laravel') }}
            </a>
        </div>

        <div class="collapse navbar-collapse" id="app-navbar-collapse">
            <!-- Left Side Of Navbar -->
            <ul class="nav navbar-nav">
                &nbsp;
            </ul>

            <!-- Right Side Of Navbar -->
            <ul class="nav navbar-nav navbar-right">
                <!-- Authentication Links -->
                @if (auth()->guard('admin')->guest())
                    <li><a href="{{ url('/admin/login') }}">Login</a></li>
                    {{--<li><a href="{{ route('register') }}">Register</a></li>--}}
                @else
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"
                           aria-expanded="false" aria-haspopup="true">
                            {{ auth()->guard('admin')->user()->name }} <span class="caret"></span>
                        </a>

                        <ul class="dropdown-menu">
                            <li>
                                <a href="{{ url('/admin/logout')}}"
                                   onclick="event.preventDefault();
                                                 document.getElementById('logout-form').submit();">
                                    Logout
                                </a>

                                <form id="logout-form" action="{{ url('/admin/logout')}}" method="POST"
                                      style="display: none;">
                                    {{ csrf_field() }}
                                </form>
                            </li>
                        </ul>
                    </li>
                @endif
            </ul>
        </div>
    </div>
</nav>

@yield('content')

<!-- Scripts -->
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>

複製 views/auth/login.blade.php 成 views/admin/login.blade.php
編輯該模板,更改佈局檔案為 layouts.admin, 把表單的提交 url 改為 admin/login,email 欄位改成 name欄位,去掉找回密碼的部分

@extends('layouts.admin')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">Admin Login</div>
                    <div class="panel-body">
                        <form class="form-horizontal" role="form" method="POST" action="{{ url('/admin/login') }}">
                            {{ csrf_field() }}

                            <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                                <label for="name" class="col-md-4 control-label">Name</label>

                                <div class="col-md-6">
                                    <input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus>

                                    @if ($errors->has('name'))
                                        <span class="help-block">
                                        <strong>{{ $errors->first('name') }}</strong>
                                    </span>
                                    @endif
                                </div>
                            </div>

                            <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
                                <label for="password" class="col-md-4 control-label">Password</label>

                                <div class="col-md-6">
                                    <input id="password" type="password" class="form-control" name="password" required>

                                    @if ($errors->has('password'))
                                        <span class="help-block">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                                    @endif
                                </div>
                            </div>

                            <div class="form-group">
                                <div class="col-md-6 col-md-offset-4">
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" name="remember"> Remember Me
                                        </label>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <div class="col-md-8 col-md-offset-4">
                                    <button type="submit" class="btn btn-primary">
                                        Login
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

複製 views/home.blade.php 成 views/admin/index.blade.php
編輯該模板

@extends('layouts.admin')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Dashboard</div>

                <div class="panel-body">
                    You are logged in admin dashboard!
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

新增後臺路由

編輯 routes/web.php, 新增以下內容

Route::group(['prefix' => 'admin'], function () {
    Route::group(['middleware' => 'auth.admin'], function () {
        Route::get('/', 'Admin\IndexController@index');
    });

    Route::get('login', 'Admin\LoginController@showLoginForm')->name('admin.login');
    Route::post('login', 'Admin\LoginController@login');
    Route::post('logout', 'Admin\LoginController@logout');
});

後臺管理認證中介軟體

建立後臺管理認證中介軟體

php artisan make:middleware AuthAdmin

編輯 AuthAdmin

<?php

namespace App\Http\Middleware;

use Closure;

class AuthAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (auth()->guard('admin')->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('admin/login');
            }
        }

        return $next($request);
    }
}

建立後臺管理登入跳轉中介軟體,用於有些操作在登入之後的跳轉

php artisan make:middleware GuestAdmin

編輯該中介軟體的 handle 方法

public function handle($request, Closure $next)
    {
        if (auth()->guard('admin')->check()) {
            return redirect('/admin');
        }

        return $next($request);
    }

在 app/Http/Kernel.php 中註冊以上中介軟體

     protected $routeMiddleware = [ 
         ......
         'auth.admin' => \App\Http\Middleware\AuthAdmin::class,
         'guest.admin' => \App\Http\Middleware\GuestAdmin::class,
     ];

處理登出

經過上面的步驟,已經實現了前後臺分離登入,但是不管是在前臺登出,還是在後臺登出,都銷燬了所有的 session,導致前後臺登出連在一起。所以我們還要對登出的方法處理一下。
原來的 logout 方法是這樣寫的,在 Illuminate\Foundation\Auth\AuthenticatesUsers 裡

public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->flush();

        $request->session()->regenerate();

        return redirect('/');
    }

注意這一句

 $request->session()->flush();

將所有的 session 全部清除,這裡不分前臺、後臺,所以要對這裡進行改造。
因為前臺、後臺登出都要修改,所以我們新建一個 trait,前後臺都可以使用。
新建一個檔案 app/Extensions/AuthenticatesLogout.php

<?php
namespace App\Extensions;

namespace App\Exceptions;

use Exception;
use Illuminate\Http\Request;

trait AuthenticatesLogout

{
    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->forget($this->guard()->getName());

        $request->session()->regenerate();

        return redirect('/');
    }
}

我們將上面的那一句改成

$request->session()->forget($this->guard()->getName());

只是刪除掉當前 guard 所建立的 session,這樣就達到了分別登出的目的。
修改 Auth/LoginController.php 和 Admin/LoginController.php,將

 class LoginController extends Controller
 {
     use AuthenticatesUsers;

改掉,在檔案的前面別忘了加上 use 語句

use App\Exceptions\AuthenticatesLogout;
...
class LoginController extends Controller
{
    use AuthenticatesUsers, AuthenticatesLogout {
        AuthenticatesLogout::logout insteadof AuthenticatesUsers;
    }
...

到這裡,就完成了整個不同使用者表登入認證的過程。
轉載,做了些優化處理了些錯誤

認真學習,努力工作。拼!命!玩!

相關文章