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']){
//将用户数据写入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();

View File

@ -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 {

View File

@ -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);
}