AdminController.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. package com.cyksj.web.controller.manage;
  2. import cn.dev33.satoken.stp.StpUtil;
  3. import cn.hutool.core.date.DateTime;
  4. import cn.hutool.core.date.DateUtil;
  5. import cn.hutool.core.lang.Validator;
  6. import cn.hutool.core.util.StrUtil;
  7. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  8. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  9. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  10. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  11. import com.cyksj.common.constant.WeChatTemplateConst;
  12. import com.cyksj.common.exception.BusinessRuntimeException;
  13. import com.cyksj.common.util.Codec;
  14. import com.cyksj.common.util.Jsons;
  15. import com.cyksj.dto.Result;
  16. import com.cyksj.enums.GatewayResponse;
  17. import com.cyksj.mapper.CustomerServiceMapper;
  18. import com.cyksj.mapper.PhoneCodeMapper;
  19. import com.cyksj.model.dto.WxMpTemplateData;
  20. import com.cyksj.model.dto.WxMpTemplateMessage;
  21. import com.cyksj.model.entity.PhoneCode;
  22. import com.cyksj.model.manage.dto.AdminInfo;
  23. import com.cyksj.model.manage.entity.Admin;
  24. import com.cyksj.service.mange.AdminService;
  25. import com.cyksj.service.wechat.WeChatService;
  26. import lombok.RequiredArgsConstructor;
  27. import lombok.extern.slf4j.Slf4j;
  28. import org.apache.commons.lang3.StringUtils;
  29. import org.springframework.validation.annotation.Validated;
  30. import org.springframework.web.bind.annotation.*;
  31. import javax.servlet.http.HttpServletRequest;
  32. import java.io.BufferedReader;
  33. import java.io.IOException;
  34. import java.util.Date;
  35. import java.util.Enumeration;
  36. import java.util.List;
  37. import java.util.Map;
  38. /**
  39. * @description
  40. * @author chan
  41. * @date 2021-10-11 下午11:02
  42. */
  43. @RestController
  44. @RequestMapping("/manage/admin")
  45. @RequiredArgsConstructor
  46. @Slf4j
  47. public class AdminController {
  48. private final AdminService adminService;
  49. private final HttpServletRequest request;
  50. private final WeChatService weChatService;
  51. private final CustomerServiceMapper customerServiceMapper;
  52. private final PhoneCodeMapper phoneCodeMapper;
  53. private static final List<String> SEND_LIST = List.of("o_i5g6V5z5uDpx_SBhJ4ePek8g8k","o_i5g6X99wu2OmC4DcQKXKNmJexA");
  54. @PostMapping(value = "/login")
  55. public Result<String> login(@RequestBody Admin adminRequest) throws Exception {
  56. Admin admin = adminService.getOne(
  57. new QueryWrapper<Admin>().lambda().eq(Admin::getPhone,adminRequest.getPhone()));
  58. if (null == admin) {
  59. throw BusinessRuntimeException.getInstance("该用户不存在.");
  60. }
  61. if (null == admin.getStatus() || !admin.getStatus()) {
  62. throw BusinessRuntimeException.getInstance("无登录权限.");
  63. }
  64. // 对比密码
  65. String encodePasscode = Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.SHA256).setStringData(adminRequest.getPassWord()).toBase64String();
  66. if (!StringUtils.equals(admin.getPassWord(), encodePasscode)) {
  67. throw BusinessRuntimeException.getInstance("密码有误.");
  68. }
  69. return GatewayResponse.SUCCESS.newBuilder().toResult();
  70. }
  71. @PostMapping("/post")
  72. public Result<String> saveAdmin(@RequestBody @Validated Admin admin) throws Exception {
  73. Long adminId = StpUtil.getLoginIdAsLong();
  74. Admin exist = adminService.getById(adminId);
  75. if (exist == null) {
  76. throw BusinessRuntimeException.getInstance("账号不存在,请重新登录");
  77. }
  78. if (exist.getCategory() != Admin.Category.superoot) {
  79. throw BusinessRuntimeException.getInstance("无超级管理员权限");
  80. }
  81. if (StringUtils.isNotBlank(admin.getPassWord())) {
  82. admin.setPassWord(Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.SHA256).setStringData(admin.getPassWord()).toBase64String());
  83. }
  84. if (admin.getId() == null) {
  85. Admin ad = adminService.getOne(new LambdaQueryWrapper<Admin>().eq(Admin::getPhone, admin.getPhone()));
  86. if (ad != null) {
  87. throw BusinessRuntimeException.getInstance("该账号已存在.");
  88. }
  89. }
  90. boolean mobile = Validator.isMobile(admin.getPhone());
  91. if (!mobile) {
  92. throw BusinessRuntimeException.getInstance("请输入正确的手机号");
  93. }
  94. adminService.saveOrUpdate(admin);
  95. return GatewayResponse.SUCCESS.newBuilder().toResult();
  96. }
  97. /**
  98. * 删除管理员
  99. */
  100. @DeleteMapping("/delete/{id}")
  101. public Result<String> deleteAdminById(@PathVariable Long id) {
  102. adminService.removeById(id);
  103. return GatewayResponse.SUCCESS.newBuilder().toResult("删除成功");
  104. }
  105. /**
  106. * 编辑管理员
  107. */
  108. @PutMapping("/put")
  109. public Result<String> editAdmin(@RequestBody Admin admin) throws Exception {
  110. Long adminId = StpUtil.getLoginIdAsLong();
  111. Admin exist = adminService.getById(adminId);
  112. if (exist == null) {
  113. throw BusinessRuntimeException.getInstance("账号不存在,请重新登录");
  114. }
  115. if (exist.getCategory() != Admin.Category.superoot) {
  116. throw BusinessRuntimeException.getInstance("无超级管理员权限");
  117. }
  118. if (admin.getId() == null || adminService.getById(admin.getId()) == null) {
  119. throw BusinessRuntimeException.getInstance("账号不存在");
  120. }
  121. if (StrUtil.isNotEmpty(admin.getPhone())) {
  122. boolean mobile = Validator.isMobile(admin.getPhone());
  123. if (!mobile) {
  124. throw BusinessRuntimeException.getInstance("请输入正确的手机号");
  125. }
  126. }
  127. if (StrUtil.isNotEmpty(admin.getPassWord())) {
  128. String encodePasscode = Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.SHA256).setStringData(admin.getPassWord()).toBase64String();
  129. admin.setPassWord(encodePasscode);
  130. }
  131. adminService.saveOrUpdate(admin);
  132. StpUtil.logoutByLoginId(admin.getId());
  133. return GatewayResponse.SUCCESS.newBuilder().toResult("编辑成功");
  134. }
  135. /**
  136. * 校验手机号获取登录信息
  137. */
  138. @GetMapping("/get/loginInfo")
  139. public Result<AdminInfo> getLoginInfo(String phone, String code) {
  140. Admin admin = adminService.getOne(
  141. new QueryWrapper<Admin>().lambda().eq(Admin::getPhone, phone));
  142. if (null == admin) {
  143. throw BusinessRuntimeException.getInstance("该用户不存在.");
  144. }
  145. if (StrUtil.hasEmpty(phone, code)) {
  146. throw BusinessRuntimeException.getInstance("请输入对应信息");
  147. }
  148. DateTime now = DateTime.now();
  149. PhoneCode phoneCode = phoneCodeMapper.selectOne(Wrappers.lambdaQuery(PhoneCode.class).eq(PhoneCode::getPhone, phone).last("limit 1"));
  150. if (phoneCode == null || StrUtil.isEmpty(phoneCode.getCode())) {
  151. throw BusinessRuntimeException.getInstance("请重新获取手机验证码");
  152. }
  153. //3分钟失效
  154. Date updateTime = phoneCode.getUpdateTime();
  155. DateTime afterFiveMinutes = DateUtil.offsetMinute(updateTime, 3);
  156. if (now.isAfter(afterFiveMinutes)) {
  157. throw BusinessRuntimeException.getInstance("手机验证码已失效,请重新获取");
  158. }
  159. if (!StrUtil.equals(code, phoneCode.getCode())) {
  160. throw BusinessRuntimeException.getInstance("手机验证码错误,请重新输入");
  161. }
  162. // 生成token
  163. StpUtil.login(admin.getId());
  164. String token = StpUtil.getTokenValue();
  165. admin.setPassWord("");
  166. AdminInfo info = new AdminInfo();
  167. info.setInfo(admin);
  168. info.setToken(token);
  169. return GatewayResponse.SUCCESS.newBuilder().toResult(info);
  170. }
  171. @GetMapping("/get/list")
  172. public Result<Page<Admin>> list(@RequestParam(defaultValue = "1") Integer start, @RequestParam(defaultValue = "5") Integer limit) {
  173. Page<Admin> page = adminService.page(new Page<>(start, limit), new LambdaQueryWrapper<Admin>().eq(Admin::getStatus, true));
  174. return GatewayResponse.SUCCESS.newBuilder().toResult(page);
  175. }
  176. @GetMapping("/send/template")
  177. public Result<String> sendTemplate(String title, String channel) throws Exception {
  178. for (String openId : SEND_LIST) {
  179. WxMpTemplateMessage templateMessage = new WxMpTemplateMessage()
  180. .setToUser(openId)
  181. .setTemplateId(WeChatTemplateConst.VDIEO_NOTIFY)
  182. .setUrl(" ");
  183. WxMpTemplateMessage.TemplateData data = templateMessage.getData();
  184. data.setFirst(new WxMpTemplateData("youtube频道有更新"));
  185. data.setKeyword1(new WxMpTemplateData(title));
  186. data.setKeyword2(new WxMpTemplateData(channel));
  187. data.setKeyword3(new WxMpTemplateData(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")));
  188. data.setKeyword4(new WxMpTemplateData("默认"));
  189. data.setRemark(new WxMpTemplateData("您订阅的频道有新内容发布"));
  190. log.info("发送video模板消息至客服:{}","磨牙怪");
  191. weChatService.sendTemplateMessage(weChatService.getAccessToken(), Jsons.toJson(templateMessage));
  192. }
  193. return GatewayResponse.SUCCESS.newBuilder().toResult();
  194. }
  195. @RequestMapping("/callback")
  196. public String youtubeCallback(HttpServletRequest request, @RequestHeader Map<String, String> headers) throws IOException {
  197. log.info("----------------打印请求全部消息开始----------------");
  198. Enumeration<String> headerNames = request.getHeaderNames();
  199. while (headerNames.hasMoreElements()) {
  200. String name = headerNames.nextElement();
  201. log.info("{} - {}", name, request.getHeader(name));
  202. }
  203. log.info("----------------打印请求全部消息结束----------------");
  204. log.info("-----------------打印请求头消息开始-----------------");
  205. headers.forEach((String key, String value) -> log.info(String.format("Header '%s' = %s", key, value)));
  206. log.info("-----------------打印请求头消息结束-----------------");
  207. Map<String, String[]> parameterMap = request.getParameterMap();
  208. log.info("------------------打印全部参数开始------------------");
  209. String result = "";
  210. if (parameterMap.isEmpty()) {
  211. log.info("请求参数为空");
  212. }else {
  213. parameterMap.forEach((String key, String[] value) -> {
  214. for (String s : value) {
  215. log.info("Param '{}' = {}", key, s);
  216. }
  217. });
  218. result = parameterMap.get("hub.challenge")[0];
  219. }
  220. log.info("------------------打印全部参数结束------------------");
  221. log.info("-----------------打印Reader数据开始----------------");
  222. StringBuilder buffer = new StringBuilder();
  223. try (BufferedReader reader = request.getReader()){
  224. String line;
  225. while ((line = reader.readLine()) != null) {
  226. buffer.append(line);
  227. }
  228. } catch (IOException e) {
  229. log.error(e.getMessage(), e);
  230. }
  231. log.info("reader -> {}", buffer);
  232. log.info("-----------------打印Reader数据结束----------------");
  233. return result;
  234. }
  235. }