UserInfoServiceImpl.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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 loginSms(String phone, String code, String sessionId) throws LoginException {
  222. logger.info("loginSms");
  223. SMSVerifyCodeResult sMSVerifyCodeResult;
  224. try {
  225. sMSVerifyCodeResult = rongCloud.sms.verifyCode(sessionId, code);
  226. } catch (Exception e) {
  227. e.printStackTrace();
  228. throw new LoginException("验证码错误");
  229. }
  230. if (200 == sMSVerifyCodeResult.getCode()) {
  231. Boolean success = sMSVerifyCodeResult.getSuccess();
  232. if (success) {
  233. UserInfo userInfo = new UserInfo();
  234. userInfo.setPhone(phone);
  235. userInfo = getUserInfo(userInfo);
  236. if (userInfo == null) {
  237. userInfo = new UserInfo();
  238. userInfo.setPhone(phone);
  239. userInfo.setUsername(phone);
  240. userInfo.setNickname(phone);
  241. userInfo.setIcon("https://microball.oss-cn-hangzhou.aliyuncs.com/huanbaojia/icon_morentouxiang.png");
  242. if (!createUserInfo(userInfo)) {
  243. throw new LoginException("登录失败");
  244. }
  245. }
  246. return userInfo;
  247. }
  248. }
  249. throw new LoginException("验证码错误");
  250. }
  251. @Override
  252. public UserInfo loginAppToken(String token) {
  253. logger.info("loginAppToken");
  254. UserInfo userInfo = null;
  255. try {
  256. // AppToken appToken = sysAppTokenMapper.getToken(token);
  257. // if (appToken != null) {
  258. SecretKey key = Keys.hmacShaKeyFor(Base64.getDecoder().decode(PropertiesFileLoader.getProperties("jwtsecret").getBytes()));
  259. Jwt jwt = Jwts.parser()
  260. .setSigningKey(key)
  261. .parse(token);
  262. Claims claims = (Claims) jwt.getBody();
  263. if (claims.getExpiration() != null) {
  264. if (claims.getExpiration().before(new Date())) {
  265. return null;
  266. }
  267. }
  268. if (claims.getSubject().equals("guest")) {
  269. userInfo = new UserInfo();
  270. } else {
  271. userInfo = getUserInfoById(claims.getSubject());
  272. }
  273. // }
  274. } catch (Exception e) {
  275. logger.error("loginAppToken", e);
  276. }
  277. return userInfo;
  278. }
  279. @Override
  280. public List<String> findDepartLeader(String userId) {
  281. logger.info("findDepartLeader");
  282. try {
  283. return userInfoMapper.findDepartLeader(userId);
  284. } catch (Exception e) {
  285. logger.error("findDepartLeader", e);
  286. }
  287. return null;
  288. }
  289. @Override
  290. public List<String> findUserByRoleName(String roleName) {
  291. logger.info("findUserByRoleName");
  292. try {
  293. return userInfoMapper.findUserByRoleName(roleName);
  294. } catch (Exception e) {
  295. logger.error("findUserByRoleName", e);
  296. }
  297. return null;
  298. }
  299. public class LoginException extends Exception {
  300. public LoginException(String message) {
  301. super(message);
  302. }
  303. }
  304. @Override
  305. public UserInfo loginWechat(String code) {
  306. try {
  307. final String APP_ID = PropertiesFileLoader.getProperties("weixinappid");
  308. final String APP_SECRET = PropertiesFileLoader.getProperties("weixinsecret");
  309. String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SECRET + "&code=" + code
  310. + "&grant_type=authorization_code";
  311. JSONObject data = WeixinUtil.loadJSON(accessTokenUrl);
  312. logger.debug("微信授权获取access_token:\n" + data.toString(4));
  313. String openId = data.getString("openid");
  314. String access_token = data.getString("access_token");
  315. String userDataUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openId;
  316. JSONObject userData = WeixinUtil.loadJSON(userDataUrl);
  317. logger.debug("微信授权获取用户信息:\n" + userData.toString(4));
  318. UserInfo userInfo = new UserInfo();
  319. userInfo.setOpenId(openId);
  320. userInfo = getUserInfo(userInfo);
  321. if (userInfo != null) {
  322. return userInfo;
  323. }
  324. userInfo = new UserInfo();
  325. userInfo.setOpenId(openId);
  326. String nickname = userData.getString("nickname");
  327. userInfo.setNickname(nickname);
  328. userInfo.setUsername(nickname);
  329. try {
  330. String country = userData.getString("country");
  331. userInfo.setCountry(country);
  332. } catch (JSONException ignored) {
  333. }
  334. try {
  335. String province = userData.getString("province");
  336. userInfo.setProvince(province);
  337. } catch (JSONException ignored) {
  338. }
  339. try {
  340. String city = userData.getString("city");
  341. userInfo.setCity(city);
  342. } catch (JSONException ignored) {
  343. }
  344. int sex = 1;
  345. try {
  346. sex = userData.getInt("sex");
  347. } catch (JSONException ignored) {
  348. }
  349. userInfo.setSex(sex == 1 ? "男" : "女");
  350. String headimgurl = null;
  351. try {
  352. headimgurl = userData.getString("headimgurl");
  353. } catch (JSONException ignored) {
  354. }
  355. userInfo.setIcon(saveAvatar(headimgurl));
  356. if (createUserInfo(userInfo)) {
  357. return userInfo;
  358. }
  359. } catch (Exception e) {
  360. logger.error("loginWechat", e);
  361. }
  362. return null;
  363. }
  364. private String saveAvatar(String url) {
  365. String path;
  366. HttpURLConnection httpUrl = null;
  367. URL iconUrl = null;
  368. try {
  369. iconUrl = new URL(url);
  370. httpUrl = (HttpURLConnection) iconUrl.openConnection();
  371. httpUrl.connect();
  372. Random random = new Random();
  373. StringBuilder randomCode = new StringBuilder();
  374. for (int i = 0; i < 8; i++) {
  375. randomCode.append(Integer.toString(random.nextInt(36), 36));
  376. }
  377. String uploadPath = String.format("images/%s-%s.jpg", new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss").format(new Date()), randomCode);
  378. path = ossFileService.upload(httpUrl.getInputStream(), uploadPath);
  379. } catch (IOException e) {
  380. path = "https://microball.oss-cn-hangzhou.aliyuncs.com/huanbaojia/icon_morentouxiang.png";
  381. e.printStackTrace();
  382. } finally {
  383. if (httpUrl != null) {
  384. httpUrl.disconnect();
  385. }
  386. }
  387. return path;
  388. }
  389. /**
  390. * <p>支付宝支付成功回调接口。充值</p>
  391. *
  392. * @param tradeNo
  393. * @param tradeStatus
  394. */
  395. @Override
  396. public void alipaySuccess(String tradeNo, String tradeStatus) {
  397. logger.info("alipaySuccess:支付宝支付成功回调接口 tradeNo:" + tradeNo + ", tradeStatus:" + tradeStatus);
  398. try {
  399. AlipayTemp alipayTemp = new AlipayTemp();
  400. alipayTemp.setOutTradeNo(tradeNo);
  401. alipayTemp = alipayTempMapper.queryAlipayTemp(alipayTemp);
  402. if (alipayTemp != null) {
  403. if (!AppConstant.Aliapi.TRADE_SUCCESS.equals(alipayTemp.getTradeStatus())) {
  404. UserInfo userInfo = this.getUserInfoById(alipayTemp.getOrderId());
  405. int cashPledge = userInfo.getCashPledge();
  406. UserInfo updateUser = new UserInfo();
  407. updateUser.setId(userInfo.getId());
  408. updateUser.setCashPledge(cashPledge + alipayTemp.getTotalAmount().intValue());
  409. if (userInfo.getApproveStep() == 3) {
  410. //如果是交押金状态,更新为完成。
  411. updateUser.setApproveStep(4);
  412. }
  413. this.updateUserInfo(updateUser);
  414. alipayTemp.setTradeStatus(tradeStatus);
  415. alipayTempMapper.updateByPrimaryKeySelective(alipayTemp);
  416. }
  417. }
  418. } catch (Exception e) {
  419. logger.error("alipaySuccess:支付宝支付成功回调接口异常 tradeNo:" + tradeNo + ", tradeStatus:" + tradeStatus, e);
  420. }
  421. }
  422. }