google2fa = Api::user()->google2fa; if (blank($this->google2fa)) { throw new Exception('必须先初始化密钥'); } } /** * Notes : 短信验证码校验 * * @Date : 2022/12/2 12:12 * @Author : * @throws Exception */ protected function checkSmsVerify(): void { $verify = request('verify'); if (strlen($verify) != Sms::getConfig('length')) { throw new Exception('请输入短信验证码'); } $check = Sms::checkCode(Api::user()->getUsername(), $verify, 'G2FA'); if (! $check) { throw new Exception('短信验证码不正确'); } } /** * Notes : 校验两步验证码 * * @Date : 2022/12/2 12:23 * @Author : * @return void * @throws Exception */ public function checkG2FAVerify(): void { $this->needInitialize(); $code = request('code'); if (strlen($code) != 6) { throw new Exception('请输入动态口令'); } if (! $this->google2fa->verify($code)) { if (config('app.debug')) { throw new Exception('动态口令不正确'.app('g2fa')->getCurrentOtp($this->google2fa->google2fa_secret)); } else { throw new Exception('动态口令不正确'); } } } /** * Notes : 获取密钥-需要短信 * * @Date : 2022/12/1 14:31 * @Author : * @return JsonResponse * @throws Exception */ public function index(): JsonResponse { $this->needInitialize(); $this->checkSmsVerify(); return $this->success($this->google2fa->google2fa_secret); } /** * Notes : 获取密钥二维码地址-需要短信 * * @Date : 2022/12/1 14:31 * @Author : * @return JsonResponse * @throws Exception */ public function qrCodeUrl(): JsonResponse { $this->needInitialize(); $this->checkSmsVerify(); return $this->success($this->google2fa->getQrCodeUrl()); } /** * Notes : 开启两步验证-需要短信 * * @Date : 2022/12/1 15:42 * @Author : * @return JsonResponse * @throws Exception */ public function open(): JsonResponse { $this->needInitialize(); if ($this->google2fa->status) { return $this->failed('请勿重复开启'); } $this->checkSmsVerify(); if ($this->google2fa->open()) { return $this->success('两步验证开启成功'); } else { return $this->failed('开启失败'); } } /** * Notes : 关闭两步验证-需要短信-需要动态口令 * * @Date : 2022/12/2 12:20 * @Author : * @return JsonResponse * @throws Exception */ public function close(): JsonResponse { $this->needInitialize(); if (! $this->google2fa->status) { return $this->failed('请勿重复关闭'); } $this->checkSmsVerify(); $this->checkG2FAVerify(); if ($this->google2fa->close()) { return $this->success('关闭两步验证成功'); } else { return $this->failed('关闭两步验证失败'); } } /** * Notes : 更新密钥-需要短信-需要动态口令 * * @Date : 2022/12/1 15:29 * @Author : * @return JsonResponse * @throws Exception */ public function update(): JsonResponse { $this->needInitialize(); $this->checkSmsVerify(); $this->checkG2FAVerify(); if ($this->google2fa->upgrade()) { return $this->success('更新成功'); } else { return $this->failed('更新失败'); } } }