一、修改后端api登录
在根目录下app文件夹下controller文件夹下common文件夹下Login.php文件下,修改doLogin方法,代码如下:
//登录public function doLogin(){$param = $this->request->param();$validate = new \app\validate\common\Login;$result = $validate->check($param);//参数验证if (!$result) return err($validate->getError());//验证码的正确性if (!app()->make(\Other\Captcha::class)->check($param['captcha_code'])) return err('验证码错误');if (time() + 5 < strtotime($param['login_time'])) return err('非法登录');$resData = Admin::dataFind(['email' => trim($param['username'])], 'id,realname,password,ip,status', true);//用户信息的正确性if (empty($resData) && empty($resData['id'])) return err('用户不存在');if ($resData['status'] !== 1) return err('该账号已被禁用');$systemParam = SystemModel::dataFind(['id' => 1],'security_password,platform_token_expira');if ($resData['password'] !== sha1($param['password'] . $systemParam['security_password'])) return err('账号对应的密码错误');$loginIp = $this->request->header('x-real-ip');if(!empty($resData['ip'])){if($resData['ip'] != $loginIp)return err('禁止访问,不在IP白名单中');}// 获取浏览器版本$browserId = Browser::getVersion();// 获取该用户是否在登录状态下$tokenId = Redis::select(config('cache.stores.redis.token_db'))->get('token_' . $resData['id']);// 如果在登录状态下,需要确认IP是否一致if(!empty($tokenId)){// 读取用户之前登录的IP及浏览器$resTokenLogin = TokenModel::dataFind(['token' => $tokenId,'token_type' => 1],'browser_id,login_ip',true);// 如果之前登录的IP存在 之前登录的IP与现在登录的IP进行对比if(!empty($resTokenLogin)){// 如果不相等的情况下,需要告知之前的浏览器做退出动作if($loginIp != $resTokenLogin['login_ip']){GatewayWork::getClientIdByUid($resData['id']);}else{// 如果相等的情况下,就需要判断浏览器是否相等啦,如果不相等的情况下,也是需要让之前的账号多退出的动作if($browserId != $resTokenLogin['browser_id']){GatewayWork::getClientIdByUid($resData['id']);}}}}//写入Token日志$data['token_type'] = 1;$data['menu_name'] = 'CommonLoginDoLogin';$data['admin_id'] = $resData['id'];$data['random_number'] = alnum();$data['browser_id'] = $browserId;$data['login_ip'] = $loginIp;$data['create_time'] = date('Y-m-d',strtotime($param['login_time']));$data['login_time'] = $param['login_time'];$data['expire_time'] = strtotime($param['login_time']) + $systemParam['platform_token_expira'];$token = $data['admin_id'] . $data['random_number'];$data['token'] = sha1(sha1($token) . strtotime($data['login_time']));TokenModel::save($data,[]);//加入跨站攻击验证队列Redis::select(config('cache.stores.redis.token_db'))->setex('token_' . $data['token'],$systemParam['platform_token_expira'],$resData['id']);Redis::select(config('cache.stores.redis.token_db'))->setex('token_' . $resData['id'],$systemParam['platform_token_expira'],Encrypt::encryptRsa($data['token']));/*$emailSender = new EmailSender();$emailSender::send($param['username'],'登录系统',$resData['realname'].'于'.$param['login_time'].'登录系统');*/return succ('登录成功',Encrypt::encryptRsa($token));}
二、修改数据库token操作表
表结构如下: