UserInfoServiceImpl.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. package com.izouma.awesomeadmin.service.impl;
  2. import com.izouma.awesomeadmin.constant.AppConstant;
  3. import com.izouma.awesomeadmin.dao.*;
  4. import com.izouma.awesomeadmin.dto.Page;
  5. import com.izouma.awesomeadmin.model.AlipayTemp;
  6. import com.izouma.awesomeadmin.model.UserInfo;
  7. import com.izouma.awesomeadmin.service.OSSFileService;
  8. import com.izouma.awesomeadmin.service.UserInfoService;
  9. import com.izouma.awesomeadmin.util.MD5Util;
  10. import com.izouma.awesomeadmin.util.PropertiesFileLoader;
  11. import com.izouma.awesomeadmin.util.WeixinUtil;
  12. import io.jsonwebtoken.Claims;
  13. import io.jsonwebtoken.Jwt;
  14. import io.jsonwebtoken.Jwts;
  15. import io.jsonwebtoken.security.Keys;
  16. import io.rong.RongCloud;
  17. import io.rong.models.SMSVerifyCodeResult;
  18. import org.apache.commons.lang.StringUtils;
  19. import org.apache.log4j.Logger;
  20. import org.json.JSONException;
  21. import org.json.JSONObject;
  22. import org.springframework.beans.factory.annotation.Autowired;
  23. import org.springframework.stereotype.Service;
  24. import javax.crypto.SecretKey;
  25. import java.io.IOException;
  26. import java.net.HttpURLConnection;
  27. import java.net.URL;
  28. import java.text.SimpleDateFormat;
  29. import java.util.*;
  30. /**
  31. * user_info service接口实现类
  32. * Tue Apr 17 10:32:49 CST 2018 Suo Chen Cheng
  33. */
  34. @Service
  35. public class UserInfoServiceImpl implements UserInfoService {
  36. private static Logger logger = Logger.getLogger(UserInfoServiceImpl.class);
  37. private RongCloud rongCloud = RongCloud.getInstance(PropertiesFileLoader.getProperties("rongyunappkey"), PropertiesFileLoader.getProperties("rongyunappsecret"));
  38. @Autowired
  39. private UserInfoMapper userInfoMapper;
  40. @Autowired
  41. private SysRoleMapper sysRoleMapper;
  42. @Autowired
  43. private DepartInfoMapper departInfoMapper;
  44. @Autowired
  45. private SysAppTokenMapper sysAppTokenMapper;
  46. @Autowired
  47. private OSSFileService ossFileService;
  48. @Autowired
  49. private AlipayTempMapper alipayTempMapper;
  50. @Override
  51. public List<UserInfo> getUserInfoList(UserInfo record) {
  52. logger.info("getUserInfoList");
  53. try {
  54. return userInfoMapper.queryAllUserInfo(record);
  55. } catch (Exception e) {
  56. logger.error("getUserInfoList", e);
  57. }
  58. return null;
  59. }
  60. @Override
  61. public List<UserInfo> getUserInfoByPage(Page page, UserInfo record) {
  62. logger.info("getUserInfoByPage");
  63. try {
  64. Map<String, Object> parameter = new HashMap<String, Object>();
  65. parameter.put("record", record);
  66. parameter.put(AppConstant.PAGE, page);
  67. return userInfoMapper.queryUserInfosByPage(parameter);
  68. } catch (Exception e) {
  69. logger.error("getUserInfoByPage", e);
  70. }
  71. return null;
  72. }
  73. @Override
  74. public UserInfo getUserInfoById(String id) {
  75. logger.info("getUserInfoById");
  76. try {
  77. return userInfoMapper.selectByPrimaryKey(Integer.valueOf(id));
  78. } catch (Exception e) {
  79. logger.error("getUserInfoById", e);
  80. }
  81. return null;
  82. }
  83. @Override
  84. public UserInfo getUserInfo(UserInfo record) {
  85. logger.info("getUserInfo");
  86. try {
  87. return userInfoMapper.queryUserInfo(record);
  88. } catch (Exception e) {
  89. logger.error("getUserInfo", e);
  90. }
  91. return null;
  92. }
  93. @Override
  94. public UserInfo getSingleUserInfo(UserInfo record) {
  95. logger.info("getSingleUserInfo");
  96. try {
  97. return userInfoMapper.querySingleUserInfo(record);
  98. } catch (Exception e) {
  99. logger.error("getSingleUserInfo", e);
  100. }
  101. return null;
  102. }
  103. @Override
  104. public boolean createUserInfo(UserInfo record) {
  105. logger.info("createUserInfo");
  106. try {
  107. if (StringUtils.isNotEmpty(record.getPassword())) {
  108. record.setPassword(MD5Util.getMD5(record.getPassword()));
  109. }
  110. int updates = userInfoMapper.insertSelective(record);
  111. if (updateUserRolesAndDeparts(record, updates)) return true;
  112. } catch (Exception e) {
  113. logger.error("createUserInfo", e);
  114. }
  115. return false;
  116. }
  117. private boolean updateUserRolesAndDeparts(UserInfo record, int updates) {
  118. if (updates > 0) {
  119. if (record.getDepartId() != null) {
  120. departInfoMapper.clearUserDeparts(record.getId());
  121. departInfoMapper.setUserDeparts(record.getId(), Arrays.asList(record.getDepartId().split(",")));
  122. }
  123. if (record.getRoleId() != null) {
  124. sysRoleMapper.clearUserRoles(record.getId());
  125. sysRoleMapper.setUserRoles(record.getId(), Arrays.asList(record.getRoleId().split(",")));
  126. }
  127. return true;
  128. }
  129. return false;
  130. }
  131. @Override
  132. public boolean deleteUserInfo(String id) {
  133. logger.info("deleteUserInfo");
  134. try {
  135. int updates = userInfoMapper.delete(id);
  136. departInfoMapper.clearUserDeparts(Integer.valueOf(id));
  137. sysRoleMapper.clearUserRoles(Integer.valueOf(id));
  138. if (updates > 0) {
  139. return true;
  140. }
  141. } catch (Exception e) {
  142. logger.error("deleteUserInfo", e);
  143. }
  144. return false;
  145. }
  146. @Override
  147. public boolean updateUserInfo(UserInfo record) {
  148. logger.info("updateUserInfo");
  149. try {
  150. int updates = userInfoMapper.updateByPrimaryKeySelective(record);
  151. if (updateUserRolesAndDeparts(record, updates)) return true;
  152. } catch (Exception e) {
  153. logger.error("updateUserInfo", e);
  154. }
  155. return false;
  156. }
  157. @Override
  158. public boolean updatePassword(UserInfo record) {
  159. logger.info("updatePassword");
  160. try {
  161. if (StringUtils.isNotEmpty(record.getPassword())) {
  162. record.setPassword(MD5Util.getMD5(record.getPassword()));
  163. }
  164. int updates = userInfoMapper.updatePassword(record);
  165. if (updates > 0) {
  166. return true;
  167. }
  168. } catch (Exception e) {
  169. logger.error("updatePassword", e);
  170. }
  171. return false;
  172. }
  173. @Override
  174. public UserInfo login(String username, String password) {
  175. logger.info("login");
  176. try {
  177. Map<String, Object> map = new HashMap<>();
  178. map.put("username", username);
  179. map.put("password", MD5Util.getMD5(password));
  180. UserInfo result = userInfoMapper.login(map);
  181. return result;
  182. } catch (Exception e) {
  183. logger.error("login", e);
  184. }
  185. return null;
  186. }
  187. @Override
  188. public UserInfo loginSms(String phone, String code, String sessionId) throws LoginException {
  189. logger.info("loginSms");
  190. // SMSVerifyCodeResult sMSVerifyCodeResult;
  191. // try {
  192. // sMSVerifyCodeResult = rongCloud.sms.verifyCode(sessionId, code);
  193. // } catch (Exception e) {
  194. // e.printStackTrace();
  195. // throw new LoginException("验证码错误");
  196. // }
  197. try {
  198. if (code.toLowerCase().equals(sessionId)) {
  199. UserInfo userInfo = new UserInfo();
  200. userInfo.setPhone(phone);
  201. userInfo = getUserInfo(userInfo);
  202. if (userInfo == null) {
  203. userInfo = new UserInfo();
  204. userInfo.setPhone(phone);
  205. userInfo.setUsername(phone);
  206. userInfo.setNickname(phone);
  207. userInfo.setIcon("https://microball.oss-cn-hangzhou.aliyuncs.com/huanbaojia/icon_morentouxiang.png");
  208. if (!createUserInfo(userInfo)) {
  209. throw new LoginException("登录失败");
  210. }
  211. }
  212. return userInfo;
  213. }
  214. } catch (Exception e) {
  215. e.printStackTrace();
  216. throw new LoginException("验证码错误");
  217. }
  218. throw new LoginException("验证码错误");
  219. }
  220. @Override
  221. public UserInfo loginAppToken(String token) {
  222. logger.info("loginAppToken");
  223. UserInfo userInfo = null;
  224. try {
  225. // AppToken appToken = sysAppTokenMapper.getToken(token);
  226. // if (appToken != null) {
  227. SecretKey key = Keys.hmacShaKeyFor(Base64.getDecoder().decode(PropertiesFileLoader.getProperties("jwtsecret").getBytes()));
  228. Jwt jwt = Jwts.parser()
  229. .setSigningKey(key)
  230. .parse(token);
  231. Claims claims = (Claims) jwt.getBody();
  232. if (claims.getExpiration() != null) {
  233. if (claims.getExpiration().before(new Date())) {
  234. return null;
  235. }
  236. }
  237. if (claims.getSubject().equals("guest")) {
  238. userInfo = new UserInfo();
  239. } else {
  240. userInfo = getUserInfoById(claims.getSubject());
  241. }
  242. // }
  243. } catch (Exception e) {
  244. logger.error("loginAppToken", e);
  245. }
  246. return userInfo;
  247. }
  248. @Override
  249. public List<String> findDepartLeader(String userId) {
  250. logger.info("findDepartLeader");
  251. try {
  252. return userInfoMapper.findDepartLeader(userId);
  253. } catch (Exception e) {
  254. logger.error("findDepartLeader", e);
  255. }
  256. return null;
  257. }
  258. @Override
  259. public List<String> findUserByRoleName(String roleName) {
  260. logger.info("findUserByRoleName");
  261. try {
  262. return userInfoMapper.findUserByRoleName(roleName);
  263. } catch (Exception e) {
  264. logger.error("findUserByRoleName", e);
  265. }
  266. return null;
  267. }
  268. public class LoginException extends Exception {
  269. public LoginException(String message) {
  270. super(message);
  271. }
  272. }
  273. @Override
  274. public UserInfo loginWechat(String code) {
  275. try {
  276. final String APP_ID = PropertiesFileLoader.getProperties("weixinappid");
  277. final String APP_SECRET = PropertiesFileLoader.getProperties("weixinsecret");
  278. String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SECRET + "&code=" + code
  279. + "&grant_type=authorization_code";
  280. JSONObject data = WeixinUtil.loadJSON(accessTokenUrl);
  281. logger.debug("微信授权获取access_token:\n" + data.toString(4));
  282. String openId = data.getString("openid");
  283. String access_token = data.getString("access_token");
  284. String userDataUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openId;
  285. JSONObject userData = WeixinUtil.loadJSON(userDataUrl);
  286. logger.debug("微信授权获取用户信息:\n" + userData.toString(4));
  287. UserInfo userInfo = new UserInfo();
  288. userInfo.setOpenId(openId);
  289. userInfo = getUserInfo(userInfo);
  290. if (userInfo != null) {
  291. return userInfo;
  292. }
  293. userInfo = new UserInfo();
  294. userInfo.setOpenId(openId);
  295. String nickname = userData.getString("nickname");
  296. userInfo.setNickname(nickname);
  297. userInfo.setUsername(nickname);
  298. try {
  299. String country = userData.getString("country");
  300. userInfo.setCountry(country);
  301. } catch (JSONException ignored) {
  302. }
  303. try {
  304. String province = userData.getString("province");
  305. userInfo.setProvince(province);
  306. } catch (JSONException ignored) {
  307. }
  308. try {
  309. String city = userData.getString("city");
  310. userInfo.setCity(city);
  311. } catch (JSONException ignored) {
  312. }
  313. int sex = 1;
  314. try {
  315. sex = userData.getInt("sex");
  316. } catch (JSONException ignored) {
  317. }
  318. userInfo.setSex(sex == 1 ? "男" : "女");
  319. String headimgurl = null;
  320. try {
  321. headimgurl = userData.getString("headimgurl");
  322. } catch (JSONException ignored) {
  323. }
  324. userInfo.setIcon(saveAvatar(headimgurl));
  325. if (createUserInfo(userInfo)) {
  326. return userInfo;
  327. }
  328. } catch (Exception e) {
  329. logger.error("loginWechat", e);
  330. }
  331. return null;
  332. }
  333. private String saveAvatar(String url) {
  334. String path;
  335. HttpURLConnection httpUrl = null;
  336. URL iconUrl = null;
  337. try {
  338. iconUrl = new URL(url);
  339. httpUrl = (HttpURLConnection) iconUrl.openConnection();
  340. httpUrl.connect();
  341. Random random = new Random();
  342. StringBuilder randomCode = new StringBuilder();
  343. for (int i = 0; i < 8; i++) {
  344. randomCode.append(Integer.toString(random.nextInt(36), 36));
  345. }
  346. String uploadPath = String.format("images/%s-%s.jpg", new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss").format(new Date()), randomCode);
  347. path = ossFileService.upload(httpUrl.getInputStream(), uploadPath);
  348. } catch (IOException e) {
  349. path = "https://microball.oss-cn-hangzhou.aliyuncs.com/huanbaojia/icon_morentouxiang.png";
  350. e.printStackTrace();
  351. } finally {
  352. if (httpUrl != null) {
  353. httpUrl.disconnect();
  354. }
  355. }
  356. return path;
  357. }
  358. /**
  359. * <p>支付宝支付成功回调接口。充值</p>
  360. *
  361. * @param tradeNo
  362. * @param tradeStatus
  363. */
  364. @Override
  365. public void alipaySuccess(String tradeNo, String tradeStatus) {
  366. logger.info("alipaySuccess:支付宝支付成功回调接口 tradeNo:" + tradeNo + ", tradeStatus:" + tradeStatus);
  367. try {
  368. AlipayTemp alipayTemp = new AlipayTemp();
  369. alipayTemp.setOutTradeNo(tradeNo);
  370. alipayTemp = alipayTempMapper.queryAlipayTemp(alipayTemp);
  371. if (alipayTemp != null) {
  372. if (!AppConstant.Aliapi.TRADE_SUCCESS.equals(alipayTemp.getTradeStatus())) {
  373. UserInfo userInfo = this.getUserInfoById(alipayTemp.getOrderId());
  374. int cashPledge = userInfo.getCashPledge();
  375. UserInfo updateUser = new UserInfo();
  376. updateUser.setId(userInfo.getId());
  377. updateUser.setCashPledge(cashPledge + alipayTemp.getTotalAmount().intValue());
  378. if (userInfo.getApproveStep() == 3) {
  379. //如果是交押金状态,更新为完成。
  380. updateUser.setApproveStep(4);
  381. }
  382. this.updateUserInfo(updateUser);
  383. alipayTemp.setTradeStatus(tradeStatus);
  384. alipayTempMapper.updateByPrimaryKeySelective(alipayTemp);
  385. }
  386. }
  387. } catch (Exception e) {
  388. logger.error("alipaySuccess:支付宝支付成功回调接口异常 tradeNo:" + tradeNo + ", tradeStatus:" + tradeStatus, e);
  389. }
  390. }
  391. }