Laravel 單使用者登入

Destiny發表於2016-09-25

單使用者登入這個術語大家都聽說過, 為什麼要單使用者登入? 比如: 視訊網站, 如果一個帳號充值了 VIP, 然後在把自己的帳號共享給其他人, 那其他人也會有 VIP 特權, 那公司的利益就受到了損失, 那帳號如果分給 1000 人, 10000 人, 這損失就不小, 那麼今天帶著大家做一下單使用者登入.

涉及技術

  • Laravel
  • 路由
  • 中介軟體
  • Redis

這裡我使用的 Laravel 5.1 LTS 框架, 登入邏輯, 挺簡單的這裡就簡單的闡述下, 我們只要在登入成功之後做一點 手腳

登入

// 登入驗證
$result = \DB::table('user_login')->where(['username' => $input['username'], 'password' => $input['pass']])->find()
if ($result) {
   # 登入成功
   // 製作 token
   $time = time();
   // md5 加密
   $singleToken = md5($request->getClientIp() . $result->guid . $time);
   // 當前 time 存入 Redis
   \Redis::set(STRING_SINGLETOKEN_ . $result->guid, $time);
   // 使用者資訊存入 Session
   \Session::put('user_login', $result);
   // 跳轉到首頁, 並附帶 Cookie
   return response()->view('index')->withCookie('SINGLETOKEN', $singletoken);
} else {
   # 登入失敗邏輯處理
}

我來解釋一下: 首先登入成功之後, 得到目前時間戳, 通過 IP, time, 和 查詢得出使用者的 Guid 進行 MD5 加密, 得到 TOKEN 然後我們將剛剛得到的時間戳, 存入 Redis Redis Key 為字串拼接上 Guid, 方便後面中介軟體的 TOKEN 驗證, 然後我們把使用者資訊存入 Session 最後我們把計算的 TOKENCookie 傳送給客戶端.

中介軟體

我們再來製作一箇中介軟體, 讓我們使用者每一次操作都在我們掌控之中.

// 專案根目錄執行
php artisan make:middleware SsoMiddleware

上面個命令會在 app/Http/Middleware 下面生成一個 SsoMiddleware.php 檔案, 將中介軟體新增到 Kernel.php

    /**
     * The application's route middleware.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'SsoMiddleware' => \App\Http\Middleware\index\SsoMiddleware::class,
    ];

現在到中介軟體中寫程式 app/Http/Middleware/SsoMiddleware.php, 在檔案中有 handle 方法, 我們在這個方法中寫邏輯.

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $userInfo = \Session::get('user_login');
        if ($userInfo) {
            // 獲取 Cookie 中的 token
            $singletoken = $request->cookie('SINGLETOKEN');
            if ($singletoken) {
                // 從 Redis 獲取 time
                $redisTime = \Redis::get(STRING_SINGLETOKEN_ . $userInfo->guid);
                // 重新獲取加密引數加密
                $ip = $request->getClientIp();
                $secret = md5($ip . $userInfo->guid . $redisTime);
                if ($singletoken != $secret) {              
                    // 記錄此次異常登入記錄
                    \DB::table('data_login_exception')->insert(['guid' => $userInfo->guid, 'ip' => $ip, 'addtime' => time()]);
                    // 清除 session 資料
                    \Session::forget('indexlogin');
                    return view('/403')->with(['Msg' => '您的帳號在另一個地點登入..']);
                }
                return $next($request);
            } else {
                return redirect('/login');
            }
        } else {
            return redirect('/login');
        }
    }

上面中介軟體之中做的事情是: 獲取使用者存在 Session 之中的資料作為第一重判斷, 如果通過判斷, 進入第二重判斷, 先獲取我們登入之後傳送給使用者的 CookieCookie 之中會有我們登入成功後傳到客戶端的 SINGLETOKEN 我們要做的事情就是重新獲取存入 Redis 的時間戳, 取出來安順序和 IP, Guid, time MD5 加密, 加密後和客戶端得到的 Cookie 之中的 SINGLETOKEN 對比.

路由組

我們邏輯寫完了, 最後一步就是將使用者登入後的每一步操作都掌控在自己手裡, 這裡我們就需要路由組

// 有 Sso 中介軟體的路由組
Route::group(['middleware' => 'SsoMiddleware'], function() {
      # 使用者登入成功後的路由
}

PS

我的技術部落格 : http://aabvip.com 歡迎大家來一起學習, 謝謝, 支援!

將來的你一定會感謝現在努力的自己!

相關文章