UserInfoServiceImpl.java 13 KB

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