From 34535262ebbe006639f0c050d735737ef1c0fd24 Mon Sep 17 00:00:00 2001 From: lbw Date: Sun, 9 Apr 2023 11:39:57 +0800 Subject: [PATCH] =?UTF-8?q?:recycle:=20Refactoring=20code.=20=E9=80=82?= =?UTF-8?q?=E9=85=8D=20v5=20pigx-app?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pigx/app/handler/MiniAppLoginHandler.java | 16 +- .../app/service/impl/AppUserServiceImpl.java | 10 - .../pigx/auth/endpoint/PigxTokenEndpoint.java | 309 +++++++++--------- .../component/PigxBearerTokenExtractor.java | 6 +- 4 files changed, 170 insertions(+), 171 deletions(-) diff --git a/pigx-app-server/pigx-app-server-biz/src/main/java/com/pig4cloud/pigx/app/handler/MiniAppLoginHandler.java b/pigx-app-server/pigx-app-server-biz/src/main/java/com/pig4cloud/pigx/app/handler/MiniAppLoginHandler.java index 4dd2fbca8..149513326 100644 --- a/pigx-app-server/pigx-app-server-biz/src/main/java/com/pig4cloud/pigx/app/handler/MiniAppLoginHandler.java +++ b/pigx-app-server/pigx-app-server-biz/src/main/java/com/pig4cloud/pigx/app/handler/MiniAppLoginHandler.java @@ -79,8 +79,8 @@ public class MiniAppLoginHandler extends AbstractLoginHandler { AppUser user = appUserService.getOne(Wrappers.query().lambda().eq(AppUser::getWxOpenid, openId)); if (user == null) { - log.info("微信小程序未绑定:{}", openId); - return null; + log.info("微信小程序未绑定:{},创建新的用户", openId); + return createAndSaveAppUserInfo(openId); } return appUserService.findUserInfo(user); } @@ -98,4 +98,16 @@ public class MiniAppLoginHandler extends AbstractLoginHandler { return true; } + private AppUserInfo createAndSaveAppUserInfo(String openId) { + AppUser appUser = new AppUser(); + appUser.setUsername(openId); + appUser.setWxOpenid(openId); + appUser.setPassword(openId); + appUserService.saveOrUpdate(appUser, Wrappers.lambdaQuery().eq(AppUser::getUsername, openId)); + + AppUserInfo appUserDTO = new AppUserInfo(); + appUserDTO.setAppUser(appUser); + return appUserDTO; + } + } diff --git a/pigx-app-server/pigx-app-server-biz/src/main/java/com/pig4cloud/pigx/app/service/impl/AppUserServiceImpl.java b/pigx-app-server/pigx-app-server-biz/src/main/java/com/pig4cloud/pigx/app/service/impl/AppUserServiceImpl.java index 824fa79a5..49babcc56 100644 --- a/pigx-app-server/pigx-app-server-biz/src/main/java/com/pig4cloud/pigx/app/service/impl/AppUserServiceImpl.java +++ b/pigx-app-server/pigx-app-server-biz/src/main/java/com/pig4cloud/pigx/app/service/impl/AppUserServiceImpl.java @@ -176,17 +176,7 @@ public class AppUserServiceImpl extends ServiceImpl impl @CacheEvict(value = CacheConstants.USER_DETAILS_MINI, key = "#userDto.username") public R updateUserInfo(AppUserDTO userDto) { AppUser appUser = baseMapper.selectById(userDto.getUserId()); - if (!ENCODER.matches(userDto.getPassword(), appUser.getPassword())) { - log.info("原密码错误,修改个人信息失败:{}", userDto.getUsername()); - return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_UPDATE_PASSWORDERROR)); - } - BeanUtils.copyProperties(userDto, appUser); - // 防止把前端传过来的密码设置上 - appUser.setPassword(null); - if (StrUtil.isNotBlank(userDto.getNewpassword1())) { - appUser.setPassword(ENCODER.encode(userDto.getNewpassword1())); - } return R.ok(this.updateById(appUser)); } diff --git a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/endpoint/PigxTokenEndpoint.java b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/endpoint/PigxTokenEndpoint.java index dcac9bb14..801913c78 100644 --- a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/endpoint/PigxTokenEndpoint.java +++ b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/endpoint/PigxTokenEndpoint.java @@ -78,188 +78,183 @@ import java.util.stream.Collectors; @RequestMapping("/token") public class PigxTokenEndpoint { - private final PigxAuthenticationFailureEventHandler authenticationFailureHandler; + private final PigxAuthenticationFailureEventHandler authenticationFailureHandler; - private final OAuth2AuthorizationService authorizationService; + private final OAuth2AuthorizationService authorizationService; - private final RemoteClientDetailsService clientDetailsService; + private final RemoteClientDetailsService clientDetailsService; - private final RedisTemplate redisTemplate; + private final RedisTemplate redisTemplate; - private final RemoteTenantService tenantService; + private final RemoteTenantService tenantService; - private final KeyStrResolver tenantKeyStrResolver; + private final KeyStrResolver tenantKeyStrResolver; - private final CacheManager cacheManager; + private final CacheManager cacheManager; - /** - * 认证页面 - * - * @param modelAndView - * @param error 表单登录失败处理回调的错误信息 - * @return ModelAndView - */ - @GetMapping("/login") - public ModelAndView require(ModelAndView modelAndView, @RequestParam(required = false) String error) { - modelAndView.setViewName("ftl/login"); - modelAndView.addObject("error", error); + /** + * 认证页面 + * @param modelAndView + * @param error 表单登录失败处理回调的错误信息 + * @return ModelAndView + */ + @GetMapping("/login") + public ModelAndView require(ModelAndView modelAndView, @RequestParam(required = false) String error) { + modelAndView.setViewName("ftl/login"); + modelAndView.addObject("error", error); - R> tenantList = tenantService.list(SecurityConstants.FROM_IN); - modelAndView.addObject("tenantList", tenantList.getData()); - return modelAndView; - } + R> tenantList = tenantService.list(SecurityConstants.FROM_IN); + modelAndView.addObject("tenantList", tenantList.getData()); + return modelAndView; + } - @GetMapping("/confirm_access") - public ModelAndView confirm(Principal principal, ModelAndView modelAndView, - @RequestParam(OAuth2ParameterNames.CLIENT_ID) String clientId, - @RequestParam(OAuth2ParameterNames.SCOPE) String scope, - @RequestParam(OAuth2ParameterNames.STATE) String state) { - SysOauthClientDetails clientDetails = RetOps - .of(clientDetailsService.getClientDetailsById(clientId, SecurityConstants.FROM_IN)).getData() - .orElseThrow(() -> new OAuthClientException("clientId 不合法")); + @GetMapping("/confirm_access") + public ModelAndView confirm(Principal principal, ModelAndView modelAndView, + @RequestParam(OAuth2ParameterNames.CLIENT_ID) String clientId, + @RequestParam(OAuth2ParameterNames.SCOPE) String scope, + @RequestParam(OAuth2ParameterNames.STATE) String state) { + SysOauthClientDetails clientDetails = RetOps + .of(clientDetailsService.getClientDetailsById(clientId, SecurityConstants.FROM_IN)).getData() + .orElseThrow(() -> new OAuthClientException("clientId 不合法")); - Set authorizedScopes = StringUtils.commaDelimitedListToSet(clientDetails.getScope()); - modelAndView.addObject("clientId", clientId); - modelAndView.addObject("state", state); - modelAndView.addObject("scopeList", authorizedScopes); - modelAndView.addObject("principalName", principal.getName()); - modelAndView.setViewName("ftl/confirm"); - return modelAndView; - } + Set authorizedScopes = StringUtils.commaDelimitedListToSet(clientDetails.getScope()); + modelAndView.addObject("clientId", clientId); + modelAndView.addObject("state", state); + modelAndView.addObject("scopeList", authorizedScopes); + modelAndView.addObject("principalName", principal.getName()); + modelAndView.setViewName("ftl/confirm"); + return modelAndView; + } - /** - * 退出并删除token - * - * @param authHeader Authorization - */ - @DeleteMapping("/logout") - public R logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) { - if (StrUtil.isBlank(authHeader)) { - return R.ok(); - } + /** + * 退出并删除token + * @param authHeader Authorization + */ + @DeleteMapping("/logout") + public R logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) { + if (StrUtil.isBlank(authHeader)) { + return R.ok(); + } - String tokenValue = authHeader.replace(OAuth2AccessToken.TokenType.BEARER.getValue(), StrUtil.EMPTY).trim(); - return removeToken(tokenValue); - } + String tokenValue = authHeader.replace(OAuth2AccessToken.TokenType.BEARER.getValue(), StrUtil.EMPTY).trim(); + return removeToken(tokenValue); + } - /** - * 校验token - * - * @param token 令牌 - * @return - */ - @SneakyThrows - @GetMapping("/check_token") - public R checkToken(String token, HttpServletResponse response, HttpServletRequest request) { - ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); + /** + * 校验token + * @param token 令牌 + * @return + */ + @SneakyThrows + @GetMapping("/check_token") + public R checkToken(String token, HttpServletResponse response, HttpServletRequest request) { + ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); - if (StrUtil.isBlank(token)) { - httpResponse.setStatusCode(HttpStatus.UNAUTHORIZED); - this.authenticationFailureHandler.onAuthenticationFailure(request, response, - new InvalidBearerTokenException(OAuth2ErrorCodesExpand.TOKEN_MISSING)); - return R.failed(); - } - OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); + if (StrUtil.isBlank(token)) { + httpResponse.setStatusCode(HttpStatus.UNAUTHORIZED); + this.authenticationFailureHandler.onAuthenticationFailure(request, response, + new InvalidBearerTokenException(OAuth2ErrorCodesExpand.TOKEN_MISSING)); + return R.failed(); + } + OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); - // 如果令牌不存在 返回401 - if (authorization == null || authorization.getAccessToken() == null) { - this.authenticationFailureHandler.onAuthenticationFailure(request, response, - new InvalidBearerTokenException(OAuth2ErrorCodesExpand.INVALID_BEARER_TOKEN)); - } + // 如果令牌不存在 返回401 + if (authorization == null || authorization.getAccessToken() == null) { + this.authenticationFailureHandler.onAuthenticationFailure(request, response, + new InvalidBearerTokenException(OAuth2ErrorCodesExpand.INVALID_BEARER_TOKEN)); + } - // 获取令牌 - return R.ok(Objects.requireNonNull(authorization).getAccessToken().getToken()); - } + // 获取令牌 + return R.ok(Objects.requireNonNull(authorization).getAccessToken().getToken()); + } - /** - * 令牌管理调用 - * - * @param token token - */ - @Inner - @DeleteMapping("/{token}") - public R removeToken(@PathVariable("token") String token) { - OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); - if (authorization == null) { - return R.ok(); - } + /** + * 令牌管理调用 + * @param token token + */ + @Inner + @DeleteMapping("/{token}") + public R removeToken(@PathVariable("token") String token) { + OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); + if (authorization == null) { + return R.ok(); + } - OAuth2Authorization.Token accessToken = authorization.getAccessToken(); - if (accessToken == null || StrUtil.isBlank(accessToken.getToken().getTokenValue())) { - return R.ok(); - } - // 清空用户信息 - cacheManager.getCache(CacheConstants.USER_DETAILS).evict(authorization.getPrincipalName()); - // 清空access token - authorizationService.remove(authorization); - // 处理自定义退出事件,保存相关日志 - SpringContextHolder.publishEvent(new LogoutSuccessEvent(new PreAuthenticatedAuthenticationToken( - authorization.getPrincipalName(), authorization.getRegisteredClientId()))); - return R.ok(); - } + OAuth2Authorization.Token accessToken = authorization.getAccessToken(); + if (accessToken == null || StrUtil.isBlank(accessToken.getToken().getTokenValue())) { + return R.ok(); + } + // 清空用户信息 + cacheManager.getCache(CacheConstants.USER_DETAILS).evict(authorization.getPrincipalName()); + // 清空access token + authorizationService.remove(authorization); + // 处理自定义退出事件,保存相关日志 + SpringContextHolder.publishEvent(new LogoutSuccessEvent(new PreAuthenticatedAuthenticationToken( + authorization.getPrincipalName(), authorization.getRegisteredClientId()))); + return R.ok(); + } - /** - * 查询token - * - * @param params 分页参数 - * @return - */ - @Inner - @PostMapping("/page") - public R> tokenList(@RequestBody Map params) { - // 根据分页参数获取对应数据 - String key = String.format("%s::%s::*", tenantKeyStrResolver.key(), CacheConstants.PROJECT_OAUTH_ACCESS); - int current = MapUtil.getInt(params, CommonConstants.CURRENT); - int size = MapUtil.getInt(params, CommonConstants.SIZE); - Set keys = redisTemplate.keys(key); - List pages = keys.stream().skip((current - 1) * size).limit(size).collect(Collectors.toList()); - Page result = new Page(current, size); + /** + * 查询token + * @param params 分页参数 + * @return + */ + @Inner + @PostMapping("/page") + public R> tokenList(@RequestBody Map params) { + // 根据分页参数获取对应数据 + String key = String.format("%s::%s::*", tenantKeyStrResolver.key(), CacheConstants.PROJECT_OAUTH_ACCESS); + int current = MapUtil.getInt(params, CommonConstants.CURRENT); + int size = MapUtil.getInt(params, CommonConstants.SIZE); + Set keys = redisTemplate.keys(key); + List pages = keys.stream().skip((current - 1) * size).limit(size).collect(Collectors.toList()); + Page result = new Page(current, size); - List tokenVoList = redisTemplate.opsForValue().multiGet(pages).stream().map(obj -> { - OAuth2Authorization authorization = (OAuth2Authorization) obj; - TokenVo tokenVo = new TokenVo(); - tokenVo.setClientId(authorization.getRegisteredClientId()); - tokenVo.setId(authorization.getId()); - tokenVo.setUsername(authorization.getPrincipalName()); - OAuth2Authorization.Token accessToken = authorization.getAccessToken(); - tokenVo.setAccessToken(accessToken.getToken().getTokenValue()); + List tokenVoList = redisTemplate.opsForValue().multiGet(pages).stream().map(obj -> { + OAuth2Authorization authorization = (OAuth2Authorization) obj; + TokenVo tokenVo = new TokenVo(); + tokenVo.setClientId(authorization.getRegisteredClientId()); + tokenVo.setId(authorization.getId()); + tokenVo.setUsername(authorization.getPrincipalName()); + OAuth2Authorization.Token accessToken = authorization.getAccessToken(); + tokenVo.setAccessToken(accessToken.getToken().getTokenValue()); - String expiresAt = TemporalAccessorUtil.format(accessToken.getToken().getExpiresAt(), - DatePattern.NORM_DATETIME_PATTERN); - tokenVo.setExpiresAt(expiresAt); + String expiresAt = TemporalAccessorUtil.format(accessToken.getToken().getExpiresAt(), + DatePattern.NORM_DATETIME_PATTERN); + tokenVo.setExpiresAt(expiresAt); - String issuedAt = TemporalAccessorUtil.format(accessToken.getToken().getIssuedAt(), - DatePattern.NORM_DATETIME_PATTERN); - tokenVo.setIssuedAt(issuedAt); + String issuedAt = TemporalAccessorUtil.format(accessToken.getToken().getIssuedAt(), + DatePattern.NORM_DATETIME_PATTERN); + tokenVo.setIssuedAt(issuedAt); - Map attributes = authorization.getAttributes(); - Authentication authentication = (Authentication) attributes.get(Principal.class.getName()); + Map attributes = authorization.getAttributes(); + Authentication authentication = (Authentication) attributes.get(Principal.class.getName()); - if (Objects.isNull(authentication)) { - return tokenVo; - } + if (Objects.isNull(authentication)) { + return tokenVo; + } - PigxUser pigxUser = (PigxUser) authentication.getPrincipal(); - tokenVo.setUserId(pigxUser.getId()); - return tokenVo; - }).filter(tokenVo -> { - // 根据用户名过滤 - String username = MapUtil.getStr(params, SecurityConstants.DETAILS_USERNAME); - if (StrUtil.isBlank(username)) { - return true; - } - return tokenVo.getUsername().contains(username); - }).collect(Collectors.toList()); - result.setRecords(tokenVoList); - result.setTotal(keys.size()); - return R.ok(result); - } + PigxUser pigxUser = (PigxUser) authentication.getPrincipal(); + tokenVo.setUserId(pigxUser.getId()); + return tokenVo; + }).filter(tokenVo -> { + // 根据用户名过滤 + String username = MapUtil.getStr(params, SecurityConstants.DETAILS_USERNAME); + if (StrUtil.isBlank(username)) { + return true; + } + return tokenVo.getUsername().contains(username); + }).collect(Collectors.toList()); + result.setRecords(tokenVoList); + result.setTotal(keys.size()); + return R.ok(result); + } - @Inner - @GetMapping("/query-token") - public R queryToken(String token) { - OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); - return R.ok(authorization); - } + @Inner + @GetMapping("/query-token") + public R queryToken(String token) { + OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); + return R.ok(authorization); + } } diff --git a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxBearerTokenExtractor.java b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxBearerTokenExtractor.java index 03b547165..cc62cc62a 100644 --- a/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxBearerTokenExtractor.java +++ b/pigx-common/pigx-common-security/src/main/java/com/pig4cloud/pigx/common/security/component/PigxBearerTokenExtractor.java @@ -55,8 +55,10 @@ public class PigxBearerTokenExtractor implements BearerTokenResolver { @Override public String resolve(HttpServletRequest request) { - boolean match = urlProperties.getIgnoreUrls().stream() - .anyMatch(url -> pathMatcher.match(url, request.getRequestURI())); + String requestUri = request.getRequestURI(); + String relativePath = requestUri.substring(request.getContextPath().length()); + + boolean match = urlProperties.getIgnoreUrls().stream().anyMatch(url -> pathMatcher.match(url, relativePath)); if (match) { return null;