From 51a1358df5de8c647328bcaf074985bc5dcc5abd Mon Sep 17 00:00:00 2001 From: toogee Date: Fri, 16 Oct 2020 13:51:56 +0800 Subject: [PATCH] login cookiesafe --- app/common/model/User.php | 14 +++++++++----- app/index/controller/User.php | 5 +++-- app/middleware/LoginCookie.php | 23 ++++++++++++++++++----- 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/app/common/model/User.php b/app/common/model/User.php index 8db188e..f660a40 100644 --- a/app/common/model/User.php +++ b/app/common/model/User.php @@ -53,11 +53,15 @@ class User extends Model if($user['password'] == $data['password']){ //将用户数据写入Session - Session::set('user_id',$user['id']); - Session::set('user_name',$user['name']); - if(!empty($data['remember'])){ - Cookie::set('user_id', $user['id'], 604800); - Cookie::set('user_name', $user['name'], 604800); + //Session::set('user_id',$user['id']); + //Session::set('user_name',$user['name']); + if(isset($data['remember'])){ + $salt = 'taoler'; + //加密auth存入cookie + $auth = md5($user['name'].$salt).":".$user['id']; + Cookie::set('auth',$auth,604800); + //Cookie::set('user_id', $user['id'], 604800); + //Cookie::set('user_name', $user['name'], 604800); } $ip = request()->ip(); diff --git a/app/index/controller/User.php b/app/index/controller/User.php index 5cc2c22..e4b8dd9 100644 --- a/app/index/controller/User.php +++ b/app/index/controller/User.php @@ -200,8 +200,9 @@ class User extends BaseController public function logout() { Session::clear(); - Cookie::delete('user_name'); - Cookie::delete('user_id'); + Cookie::delete('auth'); + //Cookie::delete('user_name'); + //Cookie::delete('user_id'); if(Session::has('user_id')){ return json(['code' => -1, 'msg' => '退出失败']); } else { diff --git a/app/middleware/LoginCookie.php b/app/middleware/LoginCookie.php index da79c72..654b956 100644 --- a/app/middleware/LoginCookie.php +++ b/app/middleware/LoginCookie.php @@ -3,16 +3,29 @@ namespace app\middleware; use think\facade\Session; use think\facade\Cookie; +use think\facade\Db; class LoginCookie { public function handle($request, \Closure $next) { - //登陆前Cookie检测 - if(Cookie::get('user_id')){ - //dump(Cookie::get('user_id')); - Session::set('user_id',Cookie::get('user_id')); - Session::set('user_name',Cookie::get('user_name')); + //登陆前获取加密的Cookie + $cooAuth = Cookie::get('auth'); + if(!empty($cooAuth)){ + $resArr = explode(':',$cooAuth); + $userId = end($resArr); + //检验用户 + $user = Db::name('user')->where('id',$userId)->find(); + if($user){ + //验证cookie + $salt = 'taoler'; + $auth = md5($user['name'].$salt).":".$userId; + if($auth==$cooAuth){ + Session::set('user_name',$user['name']); + Session::set('user_id',$userId); + } + } + } return $next($request); }