SaasLoginController.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. String redirectUrl = this.validSaasSSO(loginVO);
  88. LambdaQueryWrapper<SaasAccount> queryWrapper = new SaasAccount.Builder().createQueryWrapper().usernameEq(loginVO.getUsername()).passwordEq(loginVO.getPassword()).builderQueryWrapper();
  89. List<SaasAccount> accounts = this.saasAccountService.list(queryWrapper);
  90. if (CollectionUtil.isEmpty(accounts) || accounts.size() > 1) {
  91. return ResponseResultUtil.errorResult(ResponseCode.A0220.getCode(), "用户名/密码错误");
  92. }
  93. SaasAccount account = accounts.get(0);
  94. // 验证此账号是否可用
  95. if (SaasCommonConstant.STATUS_1 != account.getValid()) {
  96. return ResponseResultUtil.errorResult(ResponseCode.A0220.getCode(), "此账号已停用");
  97. }
  98. /*if (!account.getTerminal().contains(loginVO.getAppId())) {
  99. return ResponseResultUtil.errorResult(ResponseCode.A0220.getCode(), "此账号不允许在此端登录");
  100. }*/
  101. // 验证是否在有效期内
  102. if (SaasCommonConstant.STR_STATUS_0.equals(account.getValidLast())) {
  103. Date date = new Date();
  104. Date validEndTime = account.getValidEndTime();
  105. if (date.after(validEndTime)) {
  106. return ResponseResultUtil.errorResult(ResponseCode.A0220.getCode(), "此账号已停用");
  107. }
  108. }
  109. // 如果是业务系统账号,集团编码必须存在
  110. if (SaasCommonConstant.STR_STATUS_1.equals(account.getAccountBelong()) && StringUtil.isBlank(account.getGroupCode())) {
  111. return ResponseResultUtil.errorResult(ResponseCode.C0341.getCode(), "业务系统账号,集团编码不可为空");
  112. }
  113. // 获取集团名称
  114. if (StringUtil.isNotBlank(account.getGroupCode())) {
  115. SaasGroup saasGroup = this.saasGroupService.getOne(account.getGroupCode());
  116. account.setGroupName(saasGroup == null ? null : saasGroup.getGroupName());
  117. }
  118. // 更新账号登录时间,及IP
  119. String address = RequestUtil.getIpAddress(request);
  120. LambdaUpdateWrapper<SaasAccount> updateWrapper = new SaasAccount.Builder().createUpdateWrapper()
  121. .idEq(account.getId()).groupCodeEq(account.getGroupCode())
  122. .validEq(SaasCommonConstant.STATUS_1).builderUpdateWrapper();
  123. updateWrapper.set(SaasAccount::getLastLoginTime, new Date());
  124. updateWrapper.set(SaasAccount::getLastLoginIp, address);
  125. boolean result = this.saasAccountService.update(updateWrapper);
  126. if (!result) {
  127. return ResponseResultUtil.errorResult("登录信息更新失败");
  128. }
  129. account.setPassword(null);
  130. // 判断是否需要获取菜单权限树
  131. if (loginVO.isAuths()) {
  132. List<SaasMenu> menuTree = this.querySaasMenuTree(account, loginVO.getAppId());
  133. account.setAuths(menuTree);
  134. }
  135. account.setAppId(loginVO.getAppId());
  136. String token = this.setRedisToken(account, loginVO.getAppId(), loginVO.isRemember(), false);
  137. // 判断是否需要重定向
  138. if (StringUtil.isNotBlank(redirectUrl)) {
  139. String code = this.saasAuthHandler.getCode(loginVO.getClientId(), loginVO.getRedirectUrl(), account.getId(), account.getGroupCode(), loginVO.getAppId());
  140. redirectUrl = redirectUrl + "&code=" + code;
  141. Map<String, String> temp = new HashMap<String, String>();
  142. temp.put("redirectUrl", redirectUrl);
  143. return ResponseResultUtil.successResult(temp);
  144. }
  145. response.setHeader(CipherConstants.TOKEN_HEADER, token);
  146. return ResponseResultUtil.successResult(account);
  147. }
  148. /**
  149. * 能够进来,说明已经经过token验证,且通过,查询出账号信息,并返回即可
  150. *
  151. * @param queryVO
  152. * @return
  153. * @throws NumberFormatException
  154. * @throws UnsupportedEncodingException
  155. */
  156. @ApiOperation(value = "记住登录")
  157. @RequestMapping(value = "saas/remember", method = RequestMethod.POST)
  158. public ResponseResult saasAccountLogin(@RequestBody @Validated SaasAccountQueryVO queryVO, HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, UnsupportedEncodingException {
  159. SaasAccount account = this.saasAccountService.getOne(queryVO.getAccountId(), null, queryVO.getUsername());
  160. if (account == null) {
  161. return ResponseResultUtil.errorResult(ResponseCode.A0402.getCode(), "账号信息不存在");
  162. }
  163. // 获取集团名称
  164. if (StringUtil.isNotBlank(account.getGroupCode())) {
  165. SaasGroup saasGroup = this.saasGroupService.getOne(account.getGroupCode());
  166. account.setGroupName(saasGroup == null ? null : saasGroup.getGroupName());
  167. }
  168. String token = this.setRedisToken(account, queryVO.getAppId(), true, true);
  169. response.setHeader(CipherConstants.TOKEN_HEADER, token);
  170. return ResponseResultUtil.successResult(account);
  171. }
  172. /**
  173. * 退出登录,清空token,因为网关以确保token值必须于此账号,这里直接清空
  174. *
  175. * @param queryVO
  176. * @return
  177. * @throws NumberFormatException
  178. * @throws UnsupportedEncodingException
  179. */
  180. @ApiOperation(value = "退出登录")
  181. @RequestMapping(value = "account/logout", method = RequestMethod.POST)
  182. public ResponseResult accountLogout(@RequestBody @Validated SaasAccountQueryVO queryVO) throws NumberFormatException, UnsupportedEncodingException {
  183. if (StringUtil.isBlank(queryVO.getAccountId())) {
  184. return ResponseResultUtil.errorResult(ResponseCode.A0402.getCode(), "账号ID,不可为空");
  185. }
  186. // 从redis中清空此账号的sign信息
  187. boolean remove = this.bouncycastleCipher.remove(queryVO.getAccountId());
  188. return remove ? ResponseResultUtil.successResult("退出成功") : ResponseResultUtil.errorResult("退出失败");
  189. }
  190. /**
  191. * 外部账号登录验证
  192. * @return
  193. */
  194. public boolean validExternalAccount(String accountSource) {
  195. if ("201".equals(accountSource)) {
  196. // 获取code
  197. 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";
  198. Map<String, Object> params = new HashMap<String, Object>();
  199. params.put("code", "code");
  200. params.put("client_id", "client_id");
  201. params.put("client_secret", "client_secret");
  202. params.put("redirect_uri", "redirect_uri");
  203. params.put("grant_type", "authorization_code");
  204. String post = HttpUtil.post(url, params, 60000);
  205. log.info(post);
  206. // 获取token
  207. url = "http://sso4dev.wanda-dev.cn/oauth2/GetToken";
  208. params = new HashMap<String, Object>();
  209. params.put("code", "code");
  210. params.put("client_id", "client_id");
  211. params.put("client_secret", "client_secret");
  212. params.put("redirect_uri", "redirect_uri");
  213. params.put("grant_type", "authorization_code");
  214. post = HttpUtil.post(url, params, 60000);
  215. log.info(post);
  216. // 根据token获取用户信息
  217. url = "http://sso4dev.wanda-dev.cn/oauth2/GetUserInfo";
  218. post = HttpUtil.get(url, 60000);
  219. log.info(post);
  220. }
  221. return true;
  222. }
  223. /**
  224. * 验证是否需要重定向
  225. * @param loginVO
  226. * @return 为空时,说明不需要
  227. * @throws UnsupportedEncodingException
  228. */
  229. private String validSaasSSO(SaasAccountLoginVO loginVO) throws UnsupportedEncodingException {
  230. String state = loginVO.getState();
  231. String clientId = loginVO.getClientId();
  232. String redirectUrl = loginVO.getRedirectUrl();
  233. if (StringUtil.isAllBlank(state, clientId, redirectUrl)) {
  234. return null;
  235. }
  236. if (StringUtil.isBlank(clientId)) {
  237. throw new BusinessException(ResponseCode.A0402.getCode(), "客户端ID,不可为空");
  238. }
  239. if (StringUtil.isBlank(redirectUrl)) {
  240. throw new BusinessException(ResponseCode.A0402.getCode(), "重定向URL,不可为空");
  241. }
  242. // 验证clientId,是否存在
  243. // 验证redirectUrl的有效性
  244. if (redirectUrl.indexOf(HTTP_PREFIX) >= 0 || redirectUrl.indexOf(HTTPS_PREFIX) >= 0) {
  245. redirectUrl = URLEncoder.encode(redirectUrl, StandardCharsets.UTF_8.name());
  246. if (redirectUrl.indexOf("?") > 0) {
  247. redirectUrl = redirectUrl + "&clientId=" + clientId + "&state=" + state;
  248. } else {
  249. redirectUrl = redirectUrl + "?clientId=" + clientId + "&state=" + state;
  250. }
  251. return redirectUrl;
  252. }
  253. throw new BusinessException(ResponseCode.A0402.getCode(), "重定向URL,格式错误");
  254. }
  255. /**
  256. * 获取此账号的菜单权限树
  257. *
  258. * @param account
  259. * @param loginApp
  260. * @return
  261. */
  262. private List<SaasMenu> querySaasMenuTree(SaasAccount account, String loginApp) {
  263. SaasMenuQueryVO queryVO = new SaasMenuQueryVO();
  264. queryVO.setAccountId(account.getId());
  265. queryVO.setGroupCode(account.getGroupCode());
  266. queryVO.setAppId(loginApp);
  267. List<SaasMenu> menuTree = this.saasRoleMenuHandler.querySaasMenuTree(queryVO);
  268. return menuTree;
  269. }
  270. /**
  271. * 设置此账号的token,存入redis,如果redis中已存在,只追加有效期
  272. * @param account
  273. * @param loginApp
  274. * @param remember
  275. * @param isEqual 是否验证一致
  276. * @return
  277. * @throws UnsupportedEncodingException
  278. */
  279. private String setRedisToken(SaasAccount account, String loginApp, boolean remember, boolean isEqual) throws UnsupportedEncodingException {
  280. // 生成token,并验证之前登录是否为记住登录
  281. SecureAES aes = new SecureAES(properties.getAesKey(), properties.getAesIv());
  282. // 对称性加密用户信息
  283. String data = aes.encryptAccount(this.tokenAccountInfo(account, loginApp, remember));
  284. // token存在判断
  285. String sign = (String)this.redisTemplate.opsForValue().get(account.getId());
  286. if (sign != null) {
  287. if (isEqual) {
  288. // 判断是否与redis中一致,不一致,返回错误信息
  289. boolean result = this.bouncycastleCipher.isEqual(sign, account.getId());
  290. if (!result) {
  291. throw new BusinessException(ResponseCode.A0301.getCode(), ResponseCode.A0301.getDesc());
  292. }
  293. }
  294. this.redisTemplate.expire(account.getId(), Long.parseLong(this.properties.getTokenExpire()), TimeUnit.SECONDS);
  295. } else {
  296. // 加密串MD5加密转为sign,redis:key-账号ID,value-sign(data-MD5加密后)
  297. sign = this.bouncycastleCipher.encrypt(this.tokenInfo(data, loginApp), account.getId(), DigestAlgorithm.MD5, Long.parseLong(this.properties.getTokenExpire()), TimeUnit.SECONDS);
  298. }
  299. // token=data.sign
  300. String token = data + CipherConstants.POINT_JOIN_SYMBOL + sign;
  301. return token;
  302. }
  303. /**
  304. * 账号信息
  305. *
  306. * @param saasAccount
  307. * @param loginApp
  308. * @param remember
  309. * @return
  310. */
  311. private JSONObject tokenAccountInfo(SaasAccount saasAccount, String loginApp, boolean remember) {
  312. JSONObject object = new JSONObject();
  313. object.put(SaasCommonConstant.REMEMBER, remember);
  314. object.put(CipherConstants.APP_ID, loginApp);
  315. object.put(CipherConstants.GROUP_CODE, saasAccount.getGroupCode());
  316. object.put(CipherConstants.ACCOUNT_ID, saasAccount.getId());
  317. return object;
  318. }
  319. /**
  320. * 账号信息
  321. *
  322. * @param groupCode
  323. * @param loginApp
  324. * @return
  325. */
  326. private String tokenInfo(String content, String loginApp) {
  327. JSONObject object = new JSONObject();
  328. object.put(CipherConstants.APP_ID, loginApp);
  329. object.put("date", System.currentTimeMillis());
  330. object.put("content", content);
  331. return object.toJSONString();
  332. }
  333. }