package com.cyksj.web.controller.manage; import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.date.DateTime; import cn.hutool.core.date.DateUtil; import cn.hutool.core.lang.Validator; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.cyksj.common.constant.WeChatTemplateConst; import com.cyksj.common.exception.BusinessRuntimeException; import com.cyksj.common.util.Codec; import com.cyksj.common.util.Jsons; import com.cyksj.dto.Result; import com.cyksj.enums.GatewayResponse; import com.cyksj.mapper.CustomerServiceMapper; import com.cyksj.mapper.PhoneCodeMapper; import com.cyksj.model.dto.WxMpTemplateData; import com.cyksj.model.dto.WxMpTemplateMessage; import com.cyksj.model.entity.PhoneCode; import com.cyksj.model.manage.dto.AdminInfo; import com.cyksj.model.manage.entity.Admin; import com.cyksj.service.mange.AdminService; import com.cyksj.service.wechat.WeChatService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.IOException; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Map; /** * @description * @author chan * @date 2021-10-11 下午11:02 */ @RestController @RequestMapping("/manage/admin") @RequiredArgsConstructor @Slf4j public class AdminController { private final AdminService adminService; private final HttpServletRequest request; private final WeChatService weChatService; private final CustomerServiceMapper customerServiceMapper; private final PhoneCodeMapper phoneCodeMapper; private static final List SEND_LIST = List.of("o_i5g6V5z5uDpx_SBhJ4ePek8g8k","o_i5g6X99wu2OmC4DcQKXKNmJexA"); @PostMapping(value = "/login") public Result login(@RequestBody Admin adminRequest) throws Exception { Admin admin = adminService.getOne( new QueryWrapper().lambda().eq(Admin::getPhone,adminRequest.getPhone())); if (null == admin) { throw BusinessRuntimeException.getInstance("该用户不存在."); } if (null == admin.getStatus() || !admin.getStatus()) { throw BusinessRuntimeException.getInstance("无登录权限."); } // 对比密码 String encodePasscode = Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.SHA256).setStringData(adminRequest.getPassWord()).toBase64String(); if (!StringUtils.equals(admin.getPassWord(), encodePasscode)) { throw BusinessRuntimeException.getInstance("密码有误."); } return GatewayResponse.SUCCESS.newBuilder().toResult(); } @PostMapping("/post") public Result saveAdmin(@RequestBody @Validated Admin admin) throws Exception { Long adminId = StpUtil.getLoginIdAsLong(); Admin exist = adminService.getById(adminId); if (exist == null) { throw BusinessRuntimeException.getInstance("账号不存在,请重新登录"); } if (exist.getCategory() != Admin.Category.superoot) { throw BusinessRuntimeException.getInstance("无超级管理员权限"); } if (StringUtils.isNotBlank(admin.getPassWord())) { admin.setPassWord(Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.SHA256).setStringData(admin.getPassWord()).toBase64String()); } if (admin.getId() == null) { Admin ad = adminService.getOne(new LambdaQueryWrapper().eq(Admin::getPhone, admin.getPhone())); if (ad != null) { throw BusinessRuntimeException.getInstance("该账号已存在."); } } boolean mobile = Validator.isMobile(admin.getPhone()); if (!mobile) { throw BusinessRuntimeException.getInstance("请输入正确的手机号"); } adminService.saveOrUpdate(admin); return GatewayResponse.SUCCESS.newBuilder().toResult(); } /** * 删除管理员 */ @DeleteMapping("/delete/{id}") public Result deleteAdminById(@PathVariable Long id) { adminService.removeById(id); return GatewayResponse.SUCCESS.newBuilder().toResult("删除成功"); } /** * 编辑管理员 */ @PutMapping("/put") public Result editAdmin(@RequestBody Admin admin) throws Exception { Long adminId = StpUtil.getLoginIdAsLong(); Admin exist = adminService.getById(adminId); if (exist == null) { throw BusinessRuntimeException.getInstance("账号不存在,请重新登录"); } if (exist.getCategory() != Admin.Category.superoot) { throw BusinessRuntimeException.getInstance("无超级管理员权限"); } if (admin.getId() == null || adminService.getById(admin.getId()) == null) { throw BusinessRuntimeException.getInstance("账号不存在"); } if (StrUtil.isNotEmpty(admin.getPhone())) { boolean mobile = Validator.isMobile(admin.getPhone()); if (!mobile) { throw BusinessRuntimeException.getInstance("请输入正确的手机号"); } } if (StrUtil.isNotEmpty(admin.getPassWord())) { String encodePasscode = Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.SHA256).setStringData(admin.getPassWord()).toBase64String(); admin.setPassWord(encodePasscode); } adminService.saveOrUpdate(admin); StpUtil.logoutByLoginId(admin.getId()); return GatewayResponse.SUCCESS.newBuilder().toResult("编辑成功"); } /** * 校验手机号获取登录信息 */ @GetMapping("/get/loginInfo") public Result getLoginInfo(String phone, String code) { Admin admin = adminService.getOne( new QueryWrapper().lambda().eq(Admin::getPhone, phone)); if (null == admin) { throw BusinessRuntimeException.getInstance("该用户不存在."); } if (StrUtil.hasEmpty(phone, code)) { throw BusinessRuntimeException.getInstance("请输入对应信息"); } DateTime now = DateTime.now(); PhoneCode phoneCode = phoneCodeMapper.selectOne(Wrappers.lambdaQuery(PhoneCode.class).eq(PhoneCode::getPhone, phone).last("limit 1")); if (phoneCode == null || StrUtil.isEmpty(phoneCode.getCode())) { throw BusinessRuntimeException.getInstance("请重新获取手机验证码"); } //3分钟失效 Date updateTime = phoneCode.getUpdateTime(); DateTime afterFiveMinutes = DateUtil.offsetMinute(updateTime, 3); if (now.isAfter(afterFiveMinutes)) { throw BusinessRuntimeException.getInstance("手机验证码已失效,请重新获取"); } if (!StrUtil.equals(code, phoneCode.getCode())) { throw BusinessRuntimeException.getInstance("手机验证码错误,请重新输入"); } // 生成token StpUtil.login(admin.getId()); String token = StpUtil.getTokenValue(); admin.setPassWord(""); AdminInfo info = new AdminInfo(); info.setInfo(admin); info.setToken(token); return GatewayResponse.SUCCESS.newBuilder().toResult(info); } @GetMapping("/get/list") public Result> list(@RequestParam(defaultValue = "1") Integer start, @RequestParam(defaultValue = "5") Integer limit) { Page page = adminService.page(new Page<>(start, limit), new LambdaQueryWrapper().eq(Admin::getStatus, true)); return GatewayResponse.SUCCESS.newBuilder().toResult(page); } @GetMapping("/send/template") public Result sendTemplate(String title, String channel) throws Exception { for (String openId : SEND_LIST) { WxMpTemplateMessage templateMessage = new WxMpTemplateMessage() .setToUser(openId) .setTemplateId(WeChatTemplateConst.VDIEO_NOTIFY) .setUrl(" "); WxMpTemplateMessage.TemplateData data = templateMessage.getData(); data.setFirst(new WxMpTemplateData("youtube频道有更新")); data.setKeyword1(new WxMpTemplateData(title)); data.setKeyword2(new WxMpTemplateData(channel)); data.setKeyword3(new WxMpTemplateData(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"))); data.setKeyword4(new WxMpTemplateData("默认")); data.setRemark(new WxMpTemplateData("您订阅的频道有新内容发布")); log.info("发送video模板消息至客服:{}","磨牙怪"); weChatService.sendTemplateMessage(weChatService.getAccessToken(), Jsons.toJson(templateMessage)); } return GatewayResponse.SUCCESS.newBuilder().toResult(); } @RequestMapping("/callback") public String youtubeCallback(HttpServletRequest request, @RequestHeader Map headers) throws IOException { log.info("----------------打印请求全部消息开始----------------"); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); log.info("{} - {}", name, request.getHeader(name)); } log.info("----------------打印请求全部消息结束----------------"); log.info("-----------------打印请求头消息开始-----------------"); headers.forEach((String key, String value) -> log.info(String.format("Header '%s' = %s", key, value))); log.info("-----------------打印请求头消息结束-----------------"); Map parameterMap = request.getParameterMap(); log.info("------------------打印全部参数开始------------------"); String result = ""; if (parameterMap.isEmpty()) { log.info("请求参数为空"); }else { parameterMap.forEach((String key, String[] value) -> { for (String s : value) { log.info("Param '{}' = {}", key, s); } }); result = parameterMap.get("hub.challenge")[0]; } log.info("------------------打印全部参数结束------------------"); log.info("-----------------打印Reader数据开始----------------"); StringBuilder buffer = new StringBuilder(); try (BufferedReader reader = request.getReader()){ String line; while ((line = reader.readLine()) != null) { buffer.append(line); } } catch (IOException e) { log.error(e.getMessage(), e); } log.info("reader -> {}", buffer); log.info("-----------------打印Reader数据结束----------------"); return result; } }