單用戶登錄這個(gè)術(shù)語(yǔ)大家都聽說(shuō)過(guò), 為什么要單用戶登錄? 比如: 視頻網(wǎng)站, 如果一個(gè)帳號(hào)充值了 VIP, 然后在把自己的帳號(hào)共享給其他人, 那其他人也會(huì)有 VIP 特權(quán), 那公司的利益就受到了損失, 那帳號(hào)如果分給 1000 人, 10000 人, 這損失就不小, 那么今天帶著大家做一下單用戶登錄.
登錄
// 登錄驗(yàn)證
$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);
// 當(dāng)前 time 存入 Redis
\Redis::set(STRING_SINGLETOKEN_ . $result->guid, $time);
// 用戶信息存入 Session
\Session::put('user_login', $result);
// 跳轉(zhuǎn)到首頁(yè), 并附帶 Cookie
return response()->view('index')->withCookie('SINGLETOKEN', $singletoken);
} else {
# 登錄失敗邏輯處理
}
業(yè)務(wù)邏輯: 首先登錄成功之后, 得到目前時(shí)間戳, 通過(guò) IP, time, 和 查詢得出用戶的 Guid 進(jìn)行 MD5 加密, 得到 TOKEN 然后我們將剛剛得到的時(shí)間戳, 存入 Redis Redis Key 為字符串拼接上 Guid, 方便后面中間件的 TOKEN 驗(yàn)證, 然后我們把用戶信息存入 Session 最后我們把計(jì)算的 TOKEN 以 Cookie 發(fā)送給客戶端.
中間件
我們?cè)賮?lái)制作一個(gè)中間件, 讓我們用戶每一次操作都在我們掌控之中.
// 項(xiàng)目根目錄運(yùn)行
php artisan make:middleware SsoMiddleware
上面?zhèn)€命令會(huì)在 app/Http/Middleware
下面生成一個(gè) 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, // 單用戶登錄中間件
];
現(xiàn)在到中間件中寫程序 app/Http/Middleware/SsoMiddleware.php
, 在文件中有 handle 方法, 我們?cè)谶@個(gè)方法中寫邏輯.
/**
* 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);
// 重新獲取加密參數(shù)加密
$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 數(shù)據(jù)
\Session::forget('indexlogin');
return view('/403')->with(['Msg' => '您的帳號(hào)在另一個(gè)地點(diǎn)登錄..']);
}
return $next($request);
} else {
return redirect('/login');
}
} else {
return redirect('/login');
}
}
上面中間件之中做的事情是: 獲取用戶存在 Session 之中的數(shù)據(jù)作為第一重判斷, 如果通過(guò)判斷, 進(jìn)入第二重判斷, 先獲取我們登錄之后發(fā)送給用戶的 Cookie 在 Cookie 之中會(huì)有我們登錄成功后傳到客戶端的 SINGLETOKEN 我們要做的事情就是重新獲取存入 Redis 的時(shí)間戳, 取出來(lái)安順序和 IP, Guid, time MD5 加密, 加密后和客戶端得到的 Cookie 之中的 SINGLETOKEN 對(duì)比.
路由組
我們邏輯寫完了, 最后一步就是將用戶登錄后的每一步操作都掌控在自己手里, 這里我們就需要路由組
// 有 Sso 中間件的路由組
Route::group(['middleware' => 'SsoMiddleware'], function() {
# 用戶登錄成功后的路由
}