SaasLoginController.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. package com.persagy.account.controller;
  2. import java.io.IOException;
  3. import java.io.UnsupportedEncodingException;
  4. import java.net.URLEncoder;
  5. import java.nio.charset.StandardCharsets;
  6. import java.util.Date;
  7. import java.util.HashMap;
  8. import java.util.List;
  9. import java.util.Map;
  10. import java.util.concurrent.TimeUnit;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.data.redis.core.RedisTemplate;
  15. import org.springframework.validation.annotation.Validated;
  16. import org.springframework.web.bind.annotation.RequestBody;
  17. import org.springframework.web.bind.annotation.RequestMapping;
  18. import org.springframework.web.bind.annotation.RequestMethod;
  19. import org.springframework.web.bind.annotation.RestController;
  20. import com.alibaba.fastjson.JSONObject;
  21. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  22. import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
  23. import com.persagy.account.config.ApplicationProperties;
  24. import com.persagy.account.manage.SaasAuthHandler;
  25. import com.persagy.account.manage.SaasRoleMenuHandler;
  26. import com.persagy.account.pojo.dto.SaasAccount;
  27. import com.persagy.account.pojo.dto.SaasGroup;
  28. import com.persagy.account.pojo.dto.SaasMenu;
  29. import com.persagy.account.pojo.vo.account.SaasAccountLoginVO;
  30. import com.persagy.account.pojo.vo.account.SaasAccountQueryVO;
  31. import com.persagy.account.pojo.vo.menu.SaasMenuQueryVO;
  32. import com.persagy.account.service.ISaasAccountService;
  33. import com.persagy.account.service.ISaasGroupService;
  34. import com.persagy.common.constant.SaasCommonConstant;
  35. import com.persagy.common.enums.ResponseCode;
  36. import com.persagy.common.exception.BusinessException;
  37. import com.persagy.common.utils.ResponseResult;
  38. import com.persagy.common.utils.ResponseResultUtil;
  39. import com.persagy.common.utils.StringUtil;
  40. import com.persagy.log.core.util.RequestUtil;
  41. import com.persagy.security.constant.CipherConstants;
  42. import com.persagy.security.util.BouncycastleCipher;
  43. import com.persagy.security.util.SecureAES;
  44. import cn.hutool.core.collection.CollectionUtil;
  45. import cn.hutool.crypto.digest.DigestAlgorithm;
  46. import cn.hutool.http.HttpUtil;
  47. import io.swagger.annotations.Api;
  48. import io.swagger.annotations.ApiOperation;
  49. import lombok.extern.slf4j.Slf4j;
  50. /**
  51. * 登录
  52. *
  53. * @version 1.0.0
  54. * @company persagy
  55. * @author zhangqiankun
  56. * @date 2021-03-13 15:29:50
  57. */
  58. @Slf4j
  59. @Api(tags = "账号信息")
  60. @RestController
  61. public class SaasLoginController {
  62. private static final String HTTP_PREFIX = "http://";
  63. private static final String HTTPS_PREFIX = "https://";
  64. @Autowired
  65. private SaasAuthHandler saasAuthHandler;
  66. @Autowired
  67. private ApplicationProperties properties;
  68. @Autowired
  69. private ISaasGroupService saasGroupService;
  70. @Autowired
  71. private BouncycastleCipher bouncycastleCipher;
  72. @Autowired
  73. private ISaasAccountService saasAccountService;
  74. @Autowired
  75. private SaasRoleMenuHandler saasRoleMenuHandler;
  76. @Autowired
  77. private RedisTemplate<String, Object> redisTemplate;
  78. /**
  79. * 运维系统账号登录,这里的登录失败次数验证,若后续账号用户名,非全局唯一,这里需要改动
  80. *
  81. * @throws NumberFormatException
  82. * @throws IOException
  83. */
  84. @ApiOperation(value = "运维系统账号登录")
  85. @RequestMapping(value = "saas/login", method = RequestMethod.POST)
  86. public ResponseResult saasAccountLogin(@RequestBody @Validated SaasAccountLoginVO loginVO, HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, IOException {
  87. // 如果是单点登录,验证重定向URL
  88. String redirectUrl = this.validSaasSSO(loginVO);
  89. // 获取账号信息
  90. LambdaQueryWrapper<SaasAccount> queryWrapper = new SaasAccount.Builder().createQueryWrapper().usernameEq(loginVO.getUsername()).builderQueryWrapper();
  91. List<SaasAccount> accounts = this.saasAccountService.list(queryWrapper);
  92. if (CollectionUtil.isEmpty(accounts) || accounts.size() > 1) {
  93. return ResponseResultUtil.errorResult(ResponseCode.A0220.getCode(), "无效账号");
  94. }
  95. SaasAccount account = accounts.get(0);
  96. // 验证此账号是否可用
  97. if (SaasCommonConstant.STATUS_1 != account.getValid()) {
  98. return ResponseResultUtil.errorResult(ResponseCode.A0220.getCode(), "此账号已被冻结,请联系管理员解冻");
  99. }
  100. // 验证密码
  101. if (!loginVO.getPassword().equals(account.getPassword())) {
  102. // 更新失败次数
  103. Integer loginFailNum = properties.getLoginFailNum() == null ? 0 : properties.getLoginFailNum();
  104. LambdaUpdateWrapper<SaasAccount> updateWrapper = new SaasAccount.Builder().createUpdateWrapper().idEq(account.getId()).builderUpdateWrapper();
  105. if (account.getLoginFail() >= loginFailNum) {
  106. updateWrapper.setSql("LOGIN_FAIL = LOGIN_FAIL + 1, VALID = 0");
  107. this.saasAccountService.update(updateWrapper);
  108. return ResponseResultUtil.errorResult(ResponseCode.A0220.getCode(), "此账号已被冻结,请联系管理员解冻");
  109. }
  110. updateWrapper.setSql("LOGIN_FAIL = LOGIN_FAIL + 1");
  111. this.saasAccountService.update(updateWrapper);
  112. return ResponseResultUtil.errorResult(ResponseCode.A0220.getCode(), "用户名/密码错误");
  113. }
  114. /*if (!account.getTerminal().contains(loginVO.getAppId())) {
  115. return ResponseResultUtil.errorResult(ResponseCode.A0220.getCode(), "此账号不允许在此端登录");
  116. }*/
  117. // 验证是否在有效期内
  118. if (SaasCommonConstant.STR_STATUS_0.equals(account.getValidLast())) {
  119. Date date = new Date();
  120. Date validEndTime = account.getValidEndTime();
  121. if (date.after(validEndTime)) {
  122. return ResponseResultUtil.errorResult(ResponseCode.A0220.getCode(), "此账号已停用");
  123. }
  124. }
  125. // 如果是业务系统账号,集团编码必须存在
  126. if (SaasCommonConstant.STR_STATUS_1.equals(account.getAccountBelong()) && StringUtil.isBlank(account.getGroupCode())) {
  127. return ResponseResultUtil.errorResult(ResponseCode.C0341.getCode(), "业务系统账号,集团编码不可为空");
  128. }
  129. // 获取集团名称
  130. if (StringUtil.isNotBlank(account.getGroupCode())) {
  131. SaasGroup saasGroup = this.saasGroupService.getOne(account.getGroupCode());
  132. account.setGroupName(saasGroup == null ? null : saasGroup.getGroupName());
  133. }
  134. // 更新账号登录时间,及IP
  135. String address = RequestUtil.getIpAddress(request);
  136. LambdaUpdateWrapper<SaasAccount> updateWrapper = new SaasAccount.Builder().createUpdateWrapper()
  137. .idEq(account.getId()).groupCodeEq(account.getGroupCode())
  138. .validEq(SaasCommonConstant.STATUS_1).builderUpdateWrapper();
  139. updateWrapper.set(SaasAccount::getLastLoginTime, new Date());
  140. updateWrapper.set(SaasAccount::getLastLoginIp, address);
  141. updateWrapper.set(SaasAccount::getLoginFail, 0);
  142. boolean result = this.saasAccountService.update(updateWrapper);
  143. if (!result) {
  144. return ResponseResultUtil.errorResult("登录信息更新失败");
  145. }
  146. account.setPassword(null);
  147. // 判断是否需要获取菜单权限树
  148. if (loginVO.isAuths()) {
  149. List<SaasMenu> menuTree = this.querySaasMenuTree(account, loginVO.getAppId());
  150. account.setAuths(menuTree);
  151. }
  152. account.setAppId(loginVO.getAppId());
  153. String token = this.setRedisToken(account, loginVO.getAppId(), loginVO.isRemember(), false);
  154. // 判断是否需要重定向
  155. if (StringUtil.isNotBlank(redirectUrl)) {
  156. String code = this.saasAuthHandler.getCode(loginVO.getClientId(), loginVO.getRedirectUrl(), account.getId(), account.getGroupCode(), loginVO.getAppId());
  157. redirectUrl = redirectUrl + "&code=" + code;
  158. Map<String, String> temp = new HashMap<String, String>();
  159. temp.put("redirectUrl", redirectUrl);
  160. return ResponseResultUtil.successResult(temp);
  161. }
  162. response.setHeader(CipherConstants.TOKEN_HEADER, token);
  163. return ResponseResultUtil.successResult(account);
  164. }
  165. /**
  166. * 能够进来,说明已经经过token验证,且通过,查询出账号信息,并返回即可
  167. *
  168. * @param queryVO
  169. * @return
  170. * @throws NumberFormatException
  171. * @throws UnsupportedEncodingException
  172. */
  173. @ApiOperation(value = "记住登录")
  174. @RequestMapping(value = "saas/remember", method = RequestMethod.POST)
  175. public ResponseResult saasAccountLogin(@RequestBody @Validated SaasAccountQueryVO queryVO, HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, UnsupportedEncodingException {
  176. SaasAccount account = this.saasAccountService.getOne(queryVO.getAccountId(), null, queryVO.getUsername());
  177. if (account == null) {
  178. return ResponseResultUtil.errorResult(ResponseCode.A0402.getCode(), "账号信息不存在");
  179. }
  180. // 获取集团名称
  181. if (StringUtil.isNotBlank(account.getGroupCode())) {
  182. SaasGroup saasGroup = this.saasGroupService.getOne(account.getGroupCode());
  183. account.setGroupName(saasGroup == null ? null : saasGroup.getGroupName());
  184. }
  185. String token = this.setRedisToken(account, queryVO.getAppId(), true, true);
  186. response.setHeader(CipherConstants.TOKEN_HEADER, token);
  187. return ResponseResultUtil.successResult(account);
  188. }
  189. /**
  190. * 退出登录,清空token,因为网关以确保token值必须于此账号,这里直接清空
  191. *
  192. * @param queryVO
  193. * @return
  194. * @throws NumberFormatException
  195. * @throws UnsupportedEncodingException
  196. */
  197. @ApiOperation(value = "退出登录")
  198. @RequestMapping(value = "saas/logout", method = RequestMethod.POST)
  199. public ResponseResult saasLogout(@RequestBody @Validated SaasAccountQueryVO queryVO) throws NumberFormatException, UnsupportedEncodingException {
  200. if (StringUtil.isBlank(queryVO.getAccountId())) {
  201. return ResponseResultUtil.errorResult(ResponseCode.A0402.getCode(), "账号ID,不可为空");
  202. }
  203. // 从redis中清空此账号的sign信息
  204. boolean remove = this.bouncycastleCipher.remove(queryVO.getAccountId());
  205. return remove ? ResponseResultUtil.successResult("退出成功") : ResponseResultUtil.errorResult("退出失败");
  206. }
  207. /**
  208. * 退出登录,清空token,因为网关以确保token值必须于此账号,这里直接清空
  209. *
  210. * @param queryVO
  211. * @return
  212. * @throws NumberFormatException
  213. * @throws UnsupportedEncodingException
  214. */
  215. @ApiOperation(value = "退出登录")
  216. @RequestMapping(value = "account/logout", method = RequestMethod.POST)
  217. public ResponseResult accountLogout(@RequestBody @Validated SaasAccountQueryVO queryVO) throws NumberFormatException, UnsupportedEncodingException {
  218. if (StringUtil.isBlank(queryVO.getAccountId())) {
  219. return ResponseResultUtil.errorResult(ResponseCode.A0402.getCode(), "账号ID,不可为空");
  220. }
  221. // 从redis中清空此账号的sign信息
  222. boolean remove = this.bouncycastleCipher.remove(queryVO.getAccountId());
  223. return remove ? ResponseResultUtil.successResult("退出成功") : ResponseResultUtil.errorResult("退出失败");
  224. }
  225. /**
  226. * 外部账号登录验证
  227. * @return
  228. */
  229. public boolean validExternalAccount(String accountSource) {
  230. if ("201".equals(accountSource)) {
  231. // 获取code
  232. String url = "http://sso4dev.wanda-dev.cn/oauth2/Authorize?state=53f2495d7b435ac571&client_id=GRP999&response_type=code&scope=openid%20profile&redirect_uri=https://develop.persagy.com/saasframe3/login";
  233. Map<String, Object> params = new HashMap<String, Object>();
  234. params.put("code", "code");
  235. params.put("client_id", "client_id");
  236. params.put("client_secret", "client_secret");
  237. params.put("redirect_uri", "redirect_uri");
  238. params.put("grant_type", "authorization_code");
  239. String post = HttpUtil.post(url, params, 60000);
  240. log.info(post);
  241. // 获取token
  242. url = "http://sso4dev.wanda-dev.cn/oauth2/GetToken";
  243. params = new HashMap<String, Object>();
  244. params.put("code", "code");
  245. params.put("client_id", "client_id");
  246. params.put("client_secret", "client_secret");
  247. params.put("redirect_uri", "redirect_uri");
  248. params.put("grant_type", "authorization_code");
  249. post = HttpUtil.post(url, params, 60000);
  250. log.info(post);
  251. // 根据token获取用户信息
  252. url = "http://sso4dev.wanda-dev.cn/oauth2/GetUserInfo";
  253. post = HttpUtil.get(url, 60000);
  254. log.info(post);
  255. }
  256. return true;
  257. }
  258. /**
  259. * 验证是否需要重定向
  260. * @param loginVO
  261. * @return 为空时,说明不需要
  262. * @throws UnsupportedEncodingException
  263. */
  264. private String validSaasSSO(SaasAccountLoginVO loginVO) throws UnsupportedEncodingException {
  265. String state = loginVO.getState();
  266. String clientId = loginVO.getClientId();
  267. String redirectUrl = loginVO.getRedirectUrl();
  268. if (StringUtil.isAllBlank(state, clientId, redirectUrl)) {
  269. return null;
  270. }
  271. if (StringUtil.isBlank(clientId)) {
  272. throw new BusinessException(ResponseCode.A0402.getCode(), "客户端ID,不可为空");
  273. }
  274. if (StringUtil.isBlank(redirectUrl)) {
  275. throw new BusinessException(ResponseCode.A0402.getCode(), "重定向URL,不可为空");
  276. }
  277. // 验证clientId,是否存在
  278. // 验证redirectUrl的有效性
  279. if (redirectUrl.indexOf(HTTP_PREFIX) >= 0 || redirectUrl.indexOf(HTTPS_PREFIX) >= 0) {
  280. redirectUrl = URLEncoder.encode(redirectUrl, StandardCharsets.UTF_8.name());
  281. if (redirectUrl.indexOf("?") > 0) {
  282. redirectUrl = redirectUrl + "&clientId=" + clientId + "&state=" + state;
  283. } else {
  284. redirectUrl = redirectUrl + "?clientId=" + clientId + "&state=" + state;
  285. }
  286. return redirectUrl;
  287. }
  288. throw new BusinessException(ResponseCode.A0402.getCode(), "重定向URL,格式错误");
  289. }
  290. /**
  291. * 获取此账号的菜单权限树
  292. *
  293. * @param account
  294. * @param loginApp
  295. * @return
  296. */
  297. private List<SaasMenu> querySaasMenuTree(SaasAccount account, String loginApp) {
  298. SaasMenuQueryVO queryVO = new SaasMenuQueryVO();
  299. queryVO.setAccountId(account.getId());
  300. queryVO.setGroupCode(account.getGroupCode());
  301. queryVO.setAppId(loginApp);
  302. List<SaasMenu> menuTree = this.saasRoleMenuHandler.querySaasMenuTree(queryVO);
  303. return menuTree;
  304. }
  305. /**
  306. * 设置此账号的token,存入redis,如果redis中已存在,只追加有效期
  307. * @param account
  308. * @param loginApp
  309. * @param remember
  310. * @param isEqual 是否验证一致
  311. * @return
  312. * @throws UnsupportedEncodingException
  313. */
  314. private String setRedisToken(SaasAccount account, String loginApp, boolean remember, boolean isEqual) throws UnsupportedEncodingException {
  315. // 生成token,并验证之前登录是否为记住登录
  316. SecureAES aes = new SecureAES(this.bouncycastleCipher.getProperties().getKey(), this.bouncycastleCipher.getProperties().getIv());
  317. // 对称性加密用户信息
  318. String data = aes.encryptAccount(this.tokenAccountInfo(account, loginApp, remember));
  319. // token存在判断
  320. String sign = (String) this.redisTemplate.opsForValue().get(account.getId());
  321. if (sign != null) {
  322. if (isEqual) {
  323. // 判断是否与redis中一致,不一致,返回错误信息
  324. boolean result = this.bouncycastleCipher.isEqual(sign, account.getId());
  325. if (!result) {
  326. throw new BusinessException(ResponseCode.A0301.getCode(), ResponseCode.A0301.getDesc());
  327. }
  328. }
  329. this.redisTemplate.expire(account.getId(), Long.parseLong(this.properties.getTokenExpire()), TimeUnit.SECONDS);
  330. } else {
  331. // 加密串MD5加密转为sign,redis:key-账号ID,value-sign(data-MD5加密后)
  332. sign = this.bouncycastleCipher.encrypt(this.tokenInfo(data, loginApp), account.getId(), DigestAlgorithm.MD5, Long.parseLong(this.properties.getTokenExpire()), TimeUnit.SECONDS);
  333. }
  334. // token=data.sign
  335. String token = data + CipherConstants.POINT_JOIN_SYMBOL + sign;
  336. return token;
  337. }
  338. /**
  339. * 账号信息
  340. *
  341. * @param saasAccount
  342. * @param loginApp
  343. * @param remember
  344. * @return
  345. */
  346. private JSONObject tokenAccountInfo(SaasAccount saasAccount, String loginApp, boolean remember) {
  347. JSONObject object = new JSONObject();
  348. object.put(SaasCommonConstant.REMEMBER, remember);
  349. object.put(CipherConstants.APP_ID, loginApp);
  350. object.put(CipherConstants.GROUP_CODE, saasAccount.getGroupCode());
  351. object.put(CipherConstants.ACCOUNT_ID, saasAccount.getId());
  352. return object;
  353. }
  354. /**
  355. * 账号信息
  356. *
  357. * @param groupCode
  358. * @param loginApp
  359. * @return
  360. */
  361. private String tokenInfo(String content, String loginApp) {
  362. JSONObject object = new JSONObject();
  363. object.put(CipherConstants.APP_ID, loginApp);
  364. object.put("date", System.currentTimeMillis());
  365. object.put("content", content);
  366. return object.toJSONString();
  367. }
  368. }