AdminController.java 12 KB

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