login cookiesafe

This commit is contained in:
toogee 2020-10-16 13:51:56 +08:00
parent dc2e799604
commit 51a1358df5
3 changed files with 30 additions and 12 deletions

View File

@ -53,11 +53,15 @@ class User extends Model
if($user['password'] == $data['password']){ if($user['password'] == $data['password']){
//将用户数据写入Session //将用户数据写入Session
Session::set('user_id',$user['id']); //Session::set('user_id',$user['id']);
Session::set('user_name',$user['name']); //Session::set('user_name',$user['name']);
if(!empty($data['remember'])){ if(isset($data['remember'])){
Cookie::set('user_id', $user['id'], 604800); $salt = 'taoler';
Cookie::set('user_name', $user['name'], 604800); //加密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(); $ip = request()->ip();

View File

@ -200,8 +200,9 @@ class User extends BaseController
public function logout() public function logout()
{ {
Session::clear(); Session::clear();
Cookie::delete('user_name'); Cookie::delete('auth');
Cookie::delete('user_id'); //Cookie::delete('user_name');
//Cookie::delete('user_id');
if(Session::has('user_id')){ if(Session::has('user_id')){
return json(['code' => -1, 'msg' => '退出失败']); return json(['code' => -1, 'msg' => '退出失败']);
} else { } else {

View File

@ -3,16 +3,29 @@
namespace app\middleware; namespace app\middleware;
use think\facade\Session; use think\facade\Session;
use think\facade\Cookie; use think\facade\Cookie;
use think\facade\Db;
class LoginCookie class LoginCookie
{ {
public function handle($request, \Closure $next) public function handle($request, \Closure $next)
{ {
//登陆前Cookie检测 //登陆前获取加密的Cookie
if(Cookie::get('user_id')){ $cooAuth = Cookie::get('auth');
//dump(Cookie::get('user_id')); if(!empty($cooAuth)){
Session::set('user_id',Cookie::get('user_id')); $resArr = explode(':',$cooAuth);
Session::set('user_name',Cookie::get('user_name')); $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); return $next($request);
} }