'require|/\S+/', 'password' => 'require|/\S+/', ]); if (!$validate->check($params)) { throw new \Exception($validate->getError(), 400); } return $this; } /** * 获取管理员信息 * * @param array $params * @return object|AdministratorModel * @throws \Exception */ protected function getAdministrator(array $params): AdministratorModel { extract($params); $admin = AdministratorModel::where(['account' => $account])->find(); if (!$admin || $admin->password !== $password || $admin->deleteTime ) { throw new \Exception('账号不存在或密码错误', 404); } if (!$admin->status) { throw new \Exception('账号已禁用', 404); } return $admin; } /** * 更新登录信息 * * @param AdministratorModel $admin * @return $this */ protected function saveLoginInfo(AdministratorModel $admin): self { $admin->lastLoginTime = time(); $admin->lastLoginIp = $this->request->ip(); if (!$admin->save()) { throw new \Exception('拒绝登录', 403); } return $this; } /** * 管理员登录 * * @return \think\response\Json */ public function index() { try { $params = $this->request->only(['account', 'password']); $admin = $this->dataValidate($params)->getAdministrator($params); $this->saveLoginInfo($admin); // 生成 JWT 令牌(默认有效期 24 小时) $expire = 86400; $payload = [ 'id' => $admin->id, 'account' => $admin->account, 'username' => $admin->username, 'authId' => $admin->authId ?? 0, 'role' => 'superadmin', ]; $token = JwtUtil::createToken($payload, $expire); return ResponseHelper::success([ 'id' => $admin->id, 'name' => $admin->username, 'account' => $admin->account, 'authId' => $admin->authId ?? 0, 'token' => $token, 'token_expired' => time() + $expire, ]); } catch (\Exception $e) { return ResponseHelper::error($e->getMessage(), $e->getCode()); } } }