统一基础配置名

This commit is contained in:
ronger 2019-12-02 09:39:23 +08:00
parent 2c65a03a4f
commit 4e0e91071e
16 changed files with 72 additions and 100 deletions

View File

@ -4,7 +4,7 @@ import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.rymcu.vertical.core.exception.ServiceException; import com.rymcu.vertical.core.exception.ServiceException;
import com.rymcu.vertical.core.result.GlobalResult; import com.rymcu.vertical.core.result.GlobalResult;
import com.rymcu.vertical.core.result.ResultCode; import com.rymcu.vertical.core.result.ResultCode;
import com.rymcu.vertical.web.api.exception.MallApiException; import com.rymcu.vertical.web.api.exception.BaseApiException;
import org.apache.shiro.authz.UnauthenticatedException; import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException; import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -25,16 +25,16 @@ import java.util.Map;
* 全局异常处理器 * 全局异常处理器
* */ * */
@RestControllerAdvice @RestControllerAdvice
public class HpeisExceptionHandler { public class BaseExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(HpeisExceptionHandler.class); private final Logger logger = LoggerFactory.getLogger(BaseExceptionHandler.class);
@SuppressWarnings("Duplicates") @SuppressWarnings("Duplicates")
@ExceptionHandler(Exception.class) @ExceptionHandler(Exception.class)
public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){ public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){
if(isAjax(request)){ if(isAjax(request)){
GlobalResult result = new GlobalResult(); GlobalResult result = new GlobalResult();
if (ex instanceof MallApiException){ if (ex instanceof BaseApiException){
result.setCode(401); result.setCode(401);
result.setMessage("用户未登录"); result.setMessage("用户未登录");
logger.info("用户未登录"); logger.info("用户未登录");
@ -79,7 +79,7 @@ public class HpeisExceptionHandler {
ModelAndView mv = new ModelAndView(); ModelAndView mv = new ModelAndView();
FastJsonJsonView view = new FastJsonJsonView(); FastJsonJsonView view = new FastJsonJsonView();
Map<String, Object> attributes = new HashMap(); Map<String, Object> attributes = new HashMap();
if (ex instanceof MallApiException){ if (ex instanceof BaseApiException){
attributes.put("code", "401"); attributes.put("code", "401");
attributes.put("message", "用户未登录"); attributes.put("message", "用户未登录");
} else if (ex instanceof UnauthenticatedException) { } else if (ex instanceof UnauthenticatedException) {

View File

@ -9,12 +9,12 @@ import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; import javax.servlet.ServletResponse;
import java.io.Serializable; import java.io.Serializable;
public class HpeisSessionManager extends DefaultWebSessionManager { public class BaseSessionManager extends DefaultWebSessionManager {
private static final String AUTHORIZATION = "Authorization"; private static final String AUTHORIZATION = "Authorization";
private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request"; private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";
public HpeisSessionManager() { public BaseSessionManager() {
super(); super();
} }

View File

@ -21,11 +21,11 @@ import java.util.Set;
/** /**
* Shiro静态资源配置 * Shiro静态资源配置
* */ * */
public class HpeisShiroFilterFactoryBean extends ShiroFilterFactoryBean { public class BaseShiroFilterFactoryBean extends ShiroFilterFactoryBean {
// 对ShiroFilter来说需要直接忽略的请求 // 对ShiroFilter来说需要直接忽略的请求
private Set<String> ignoreExt; private Set<String> ignoreExt;
public HpeisShiroFilterFactoryBean() { public BaseShiroFilterFactoryBean() {
super(); super();
ignoreExt = new HashSet<>(); ignoreExt = new HashSet<>();
ignoreExt.add(".svg"); ignoreExt.add(".svg");
@ -56,12 +56,12 @@ public class HpeisShiroFilterFactoryBean extends ShiroFilterFactoryBean {
PathMatchingFilterChainResolver chainResolver = new PathMatchingFilterChainResolver(); PathMatchingFilterChainResolver chainResolver = new PathMatchingFilterChainResolver();
chainResolver.setFilterChainManager(manager); chainResolver.setFilterChainManager(manager);
return new HpeisSpringShiroFilter((WebSecurityManager) securityManager, chainResolver); return new BaseSpringShiroFilter((WebSecurityManager) securityManager, chainResolver);
} }
private final class HpeisSpringShiroFilter extends AbstractShiroFilter { private final class BaseSpringShiroFilter extends AbstractShiroFilter {
protected HpeisSpringShiroFilter(WebSecurityManager webSecurityManager, FilterChainResolver resolver) { protected BaseSpringShiroFilter(WebSecurityManager webSecurityManager, FilterChainResolver resolver) {
super(); super();
if (webSecurityManager == null) { if (webSecurityManager == null) {
throw new IllegalArgumentException("WebSecurityManager property cannot be null."); throw new IllegalArgumentException("WebSecurityManager property cannot be null.");

View File

@ -30,7 +30,7 @@ import java.util.List;
* @since 2018/05/28 11:00 * @since 2018/05/28 11:00
* 自定义权限匹配和账号密码匹配 * 自定义权限匹配和账号密码匹配
* */ * */
public class HpeisShiroRealm extends AuthorizingRealm { public class BaseShiroRealm extends AuthorizingRealm {
@Resource @Resource
private RoleService roleService; private RoleService roleService;

View File

@ -35,7 +35,7 @@ public class ShiroConfig implements EnvironmentAware {
@Bean @Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) { public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new HpeisShiroFilterFactoryBean(); ShiroFilterFactoryBean shiroFilterFactoryBean = new BaseShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager); shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(); Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
@ -50,16 +50,8 @@ public class ShiroConfig implements EnvironmentAware {
filterChainDefinitionMap.put("/uploadFile/**", "anon"); filterChainDefinitionMap.put("/uploadFile/**", "anon");
filterChainDefinitionMap.put("/login", "anon"); filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/swagger-ui.html", "anon");
filterChainDefinitionMap.put("/swagger-resources", "anon");
filterChainDefinitionMap.put("/swagger-resources/configuration/security", "anon");
filterChainDefinitionMap.put("/swagger-resources/configuration/ui", "anon");
filterChainDefinitionMap.put("/v2/api-docs", "anon");
filterChainDefinitionMap.put("/webjars/springfox-swagger-ui/**", "anon");
filterChainDefinitionMap.put("/api/**", "anon"); filterChainDefinitionMap.put("/api/**", "anon");
// filterChainDefinitionMap.put("/**", "authc"); filterChainDefinitionMap.put("/**", "auth");
filterChainDefinitionMap.put("/**", "authc");
//配置shiro默认登录界面地址前后端分离中登录界面跳转应由前端路由控制后台仅返回json数据 //配置shiro默认登录界面地址前后端分离中登录界面跳转应由前端路由控制后台仅返回json数据
shiroFilterFactoryBean.setLoginUrl("/login"); shiroFilterFactoryBean.setLoginUrl("/login");
// 登录成功后要跳转的链接 // 登录成功后要跳转的链接
@ -69,10 +61,10 @@ public class ShiroConfig implements EnvironmentAware {
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
Map<String, Filter> filtersMap = new LinkedHashMap<>(); Map<String, Filter> filtersMap = new LinkedHashMap<>();
filtersMap.put("authc",hpeisFormAuthenticationFilter()); filtersMap.put("auth", baseFormAuthenticationFilter());
shiroFilterFactoryBean.setFilters(filtersMap); shiroFilterFactoryBean.setFilters(filtersMap);
filterChainDefinitionMap.put("/**", "authc"); filterChainDefinitionMap.put("/**", "auth");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean; return shiroFilterFactoryBean;
@ -88,14 +80,16 @@ public class ShiroConfig implements EnvironmentAware {
@Bean @Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() { public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("SHA-1");//散列算法:这里使用MD5算法; // 散列算法:这里使用MD5算法;
hashedCredentialsMatcher.setHashIterations(1024);//散列的次数比如散列两次相当于 md5(md5("")); hashedCredentialsMatcher.setHashAlgorithmName("SHA-1");
// 散列的次数比如散列两次相当于 md5(md5(""));
hashedCredentialsMatcher.setHashIterations(1024);
return hashedCredentialsMatcher; return hashedCredentialsMatcher;
} }
@Bean @Bean
public HpeisShiroRealm hpeisShiroRealm() { public BaseShiroRealm baseShiroRealm() {
HpeisShiroRealm shiroRealm = new HpeisShiroRealm(); BaseShiroRealm shiroRealm = new BaseShiroRealm();
shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher()); shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return shiroRealm; return shiroRealm;
} }
@ -104,18 +98,18 @@ public class ShiroConfig implements EnvironmentAware {
@Bean @Bean
public SecurityManager securityManager() { public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(hpeisShiroRealm()); securityManager.setRealm(baseShiroRealm());
// 自定义session管理 使用redis // 自定义session管理 使用redis
securityManager.setSessionManager(sessionManager()); securityManager.setSessionManager(sessionManager());
// 自定义缓存实现 使用redis
//securityManager.setCacheManager(cacheManager());
return securityManager; return securityManager;
} }
//自定义sessionManager /**
* 自定义sessionManager
* */
@Bean @Bean
public SessionManager sessionManager() { public SessionManager sessionManager() {
HpeisSessionManager sessionManager = new HpeisSessionManager(); BaseSessionManager sessionManager = new BaseSessionManager();
sessionManager.setSessionDAO(redisSessionDAO()); sessionManager.setSessionDAO(redisSessionDAO());
sessionManager.setSessionIdUrlRewritingEnabled(false); sessionManager.setSessionIdUrlRewritingEnabled(false);
sessionManager.setGlobalSessionTimeout(21600000L); sessionManager.setGlobalSessionTimeout(21600000L);
@ -169,9 +163,6 @@ public class ShiroConfig implements EnvironmentAware {
RedisSessionDAO redisSessionDAO = new RedisSessionDAO(); RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
redisSessionDAO.setRedisManager(redisManager()); redisSessionDAO.setRedisManager(redisManager());
redisSessionDAO.setExpire(21600); redisSessionDAO.setExpire(21600);
// Custom your redis key prefix for session management, if you doesn't define this parameter,
// shiro-redis will use 'shiro_redis_session:' as default prefix
// redisSessionDAO.setKeyPrefix("");
return redisSessionDAO; return redisSessionDAO;
} }
@ -197,21 +188,13 @@ public class ShiroConfig implements EnvironmentAware {
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){ public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
return new LifecycleBeanPostProcessor(); return new LifecycleBeanPostProcessor();
} }
//
// /**
// * 开启Shiro的注解(@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证
// * 配置以下两个bean(DefaultAdvisorAutoProxyCreator(可选)和AuthorizationAttributeSourceAdvisor)即可实现此功能
// *
// * @return
// */
// @Bean
// @DependsOn({"lifecycleBeanPostProcessor"})
// public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
// DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
// advisorAutoProxyCreator.setProxyTargetClass(true);
// return advisorAutoProxyCreator;
// }
/**
* 开启Shiro的注解(@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证
* 配置以下两个bean(DefaultAdvisorAutoProxyCreator(可选)和AuthorizationAttributeSourceAdvisor)即可实现此功能
*
* @return
*/
@Bean @Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() { public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
@ -219,7 +202,7 @@ public class ShiroConfig implements EnvironmentAware {
return authorizationAttributeSourceAdvisor; return authorizationAttributeSourceAdvisor;
} }
public FormAuthenticationFilter hpeisFormAuthenticationFilter(){ public FormAuthenticationFilter baseFormAuthenticationFilter(){
FormAuthenticationFilter formAuthenticationFilter = new ShiroLoginFilter(); FormAuthenticationFilter formAuthenticationFilter = new ShiroLoginFilter();
return formAuthenticationFilter; return formAuthenticationFilter;
} }
@ -227,22 +210,9 @@ public class ShiroConfig implements EnvironmentAware {
@Bean @Bean
public FilterRegistrationBean someFilterRegistration() { public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean(); FilterRegistrationBean registration = new FilterRegistrationBean();
FormAuthenticationFilter hpeisFormAuthenticationFilter = new ShiroLoginFilter(); FormAuthenticationFilter baseFormAuthenticationFilter = new ShiroLoginFilter();
registration.setFilter(hpeisFormAuthenticationFilter); registration.setFilter(baseFormAuthenticationFilter);
registration.setEnabled(false); registration.setEnabled(false);
return registration; return registration;
} }
/**
* 注册全局异常处理
*
* @return
*/
/*@Bean(name = "exceptionHandler")
public HandlerExceptionResolver handlerExceptionResolver() {
return new HpeisExceptionHandler();
}*/
} }

View File

@ -10,6 +10,9 @@ import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author ronger
*/
@Configuration @Configuration
@EnableSwagger2 @EnableSwagger2
public class Swagger2Configuration { public class Swagger2Configuration {
@ -19,7 +22,7 @@ public class Swagger2Configuration {
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()) .apiInfo(apiInfo())
.select() .select()
.apis(RequestHandlerSelectors.basePackage("com.rymcu.vertical.web.api"))//这是注意的代码 .apis(RequestHandlerSelectors.basePackage("com.rymcu.vertical.web.api"))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build(); .build();
} }

View File

@ -7,7 +7,7 @@ import com.rymcu.vertical.jwt.model.TokenModel;
import com.rymcu.vertical.jwt.service.TokenManager; import com.rymcu.vertical.jwt.service.TokenManager;
import com.rymcu.vertical.jwt.util.oConvertUtils; import com.rymcu.vertical.jwt.util.oConvertUtils;
import com.rymcu.vertical.web.api.exception.ErrorCode; import com.rymcu.vertical.web.api.exception.ErrorCode;
import com.rymcu.vertical.web.api.exception.MallApiException; import com.rymcu.vertical.web.api.exception.BaseApiException;
import io.jsonwebtoken.Claims; import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException; import io.jsonwebtoken.SignatureException;
@ -44,19 +44,19 @@ public class RestAuthTokenInterceptor implements HandlerInterceptor {
authHeader = request.getHeader(JwtConstants.UPLOAD_TOKEN); authHeader = request.getHeader(JwtConstants.UPLOAD_TOKEN);
} }
if (StringUtils.isBlank(authHeader)) { if (StringUtils.isBlank(authHeader)) {
throw new MallApiException(ErrorCode.UNAUTHORIZED); throw new BaseApiException(ErrorCode.UNAUTHORIZED);
} }
// 验证token // 验证token
Claims claims = null; Claims claims = null;
try { try {
claims = Jwts.parser().setSigningKey(JwtConstants.JWT_SECRET).parseClaimsJws(authHeader).getBody(); claims = Jwts.parser().setSigningKey(JwtConstants.JWT_SECRET).parseClaimsJws(authHeader).getBody();
}catch (final SignatureException e) { }catch (final SignatureException e) {
throw new MallApiException(ErrorCode.INVALID_TOKEN); throw new BaseApiException(ErrorCode.INVALID_TOKEN);
} }
Object username = claims.getId(); Object username = claims.getId();
if (oConvertUtils.isEmpty(username)) { if (oConvertUtils.isEmpty(username)) {
throw new MallApiException(ErrorCode.INVALID_TOKEN); throw new BaseApiException(ErrorCode.INVALID_TOKEN);
} }
TokenModel model = manager.getToken(authHeader,username.toString()); TokenModel model = manager.getToken(authHeader,username.toString());
if (manager.checkToken(model)) { if (manager.checkToken(model)) {
@ -66,7 +66,7 @@ public class RestAuthTokenInterceptor implements HandlerInterceptor {
request.setAttribute(JwtConstants.CURRENT_USER_NAME, model.getUsername()); request.setAttribute(JwtConstants.CURRENT_USER_NAME, model.getUsername());
return true; return true;
} else { } else {
throw new MallApiException(ErrorCode.TOKEN_); throw new BaseApiException(ErrorCode.TOKEN_);
} }
} }

View File

@ -3,7 +3,7 @@ package com.rymcu.vertical.service;
import com.rymcu.vertical.core.service.Service; import com.rymcu.vertical.core.service.Service;
import com.rymcu.vertical.dto.ArticleDTO; import com.rymcu.vertical.dto.ArticleDTO;
import com.rymcu.vertical.entity.Article; import com.rymcu.vertical.entity.Article;
import com.rymcu.vertical.web.api.exception.MallApiException; import com.rymcu.vertical.web.api.exception.BaseApiException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
@ -21,5 +21,5 @@ public interface ArticleService extends Service<Article> {
List<ArticleDTO> findUserArticlesByIdUser(Integer idUser); List<ArticleDTO> findUserArticlesByIdUser(Integer idUser);
Map postArticle(ArticleDTO article, HttpServletRequest request) throws UnsupportedEncodingException, MallApiException; Map postArticle(ArticleDTO article, HttpServletRequest request) throws UnsupportedEncodingException, BaseApiException;
} }

View File

@ -3,11 +3,11 @@ package com.rymcu.vertical.service;
import com.rymcu.vertical.core.service.Service; import com.rymcu.vertical.core.service.Service;
import com.rymcu.vertical.entity.Article; import com.rymcu.vertical.entity.Article;
import com.rymcu.vertical.entity.Tag; import com.rymcu.vertical.entity.Tag;
import com.rymcu.vertical.web.api.exception.MallApiException; import com.rymcu.vertical.web.api.exception.BaseApiException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
public interface TagService extends Service<Tag> { public interface TagService extends Service<Tag> {
void saveTagArticle(Article article) throws UnsupportedEncodingException, MallApiException; void saveTagArticle(Article article) throws UnsupportedEncodingException, BaseApiException;
} }

View File

@ -13,7 +13,7 @@ import com.rymcu.vertical.service.UserService;
import com.rymcu.vertical.util.Html2TextUtil; import com.rymcu.vertical.util.Html2TextUtil;
import com.rymcu.vertical.util.UserUtils; import com.rymcu.vertical.util.UserUtils;
import com.rymcu.vertical.util.Utils; import com.rymcu.vertical.util.Utils;
import com.rymcu.vertical.web.api.exception.MallApiException; import com.rymcu.vertical.web.api.exception.BaseApiException;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -79,7 +79,7 @@ public class ArticleServiceImpl extends AbstractService<Article> implements Arti
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public Map postArticle(ArticleDTO article, HttpServletRequest request) throws UnsupportedEncodingException, MallApiException { public Map postArticle(ArticleDTO article, HttpServletRequest request) throws UnsupportedEncodingException, BaseApiException {
Map map = new HashMap(1); Map map = new HashMap(1);
if(StringUtils.isBlank(article.getArticleTitle())){ if(StringUtils.isBlank(article.getArticleTitle())){
map.put("message","标题不能为空!"); map.put("message","标题不能为空!");

View File

@ -7,7 +7,7 @@ import com.rymcu.vertical.entity.User;
import com.rymcu.vertical.mapper.TagMapper; import com.rymcu.vertical.mapper.TagMapper;
import com.rymcu.vertical.service.TagService; import com.rymcu.vertical.service.TagService;
import com.rymcu.vertical.util.UserUtils; import com.rymcu.vertical.util.UserUtils;
import com.rymcu.vertical.web.api.exception.MallApiException; import com.rymcu.vertical.web.api.exception.BaseApiException;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -25,7 +25,7 @@ public class TagServiceImpl extends AbstractService<Tag> implements TagService {
@Override @Override
@Transactional @Transactional
public void saveTagArticle(Article article) throws UnsupportedEncodingException, MallApiException { public void saveTagArticle(Article article) throws UnsupportedEncodingException, BaseApiException {
User user = UserUtils.getWxCurrentUser(); User user = UserUtils.getWxCurrentUser();
String articleTags = article.getArticleTags(); String articleTags = article.getArticleTags();
if(StringUtils.isNotBlank(articleTags)){ if(StringUtils.isNotBlank(articleTags)){

View File

@ -7,7 +7,7 @@ import com.rymcu.vertical.jwt.model.TokenModel;
import com.rymcu.vertical.jwt.service.TokenManager; import com.rymcu.vertical.jwt.service.TokenManager;
import com.rymcu.vertical.mapper.UserMapper; import com.rymcu.vertical.mapper.UserMapper;
import com.rymcu.vertical.web.api.exception.ErrorCode; import com.rymcu.vertical.web.api.exception.ErrorCode;
import com.rymcu.vertical.web.api.exception.MallApiException; import com.rymcu.vertical.web.api.exception.BaseApiException;
import io.jsonwebtoken.Claims; import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException; import io.jsonwebtoken.SignatureException;
@ -22,7 +22,7 @@ public class UserUtils {
* 通过token获取当前用户的信息 * 通过token获取当前用户的信息
* @return * @return
*/ */
public static User getWxCurrentUser() throws MallApiException { public static User getWxCurrentUser() throws BaseApiException {
String authHeader = ContextHolderUtils.getRequest().getHeader(JwtConstants.AUTHORIZATION); String authHeader = ContextHolderUtils.getRequest().getHeader(JwtConstants.AUTHORIZATION);
if (authHeader == null) { if (authHeader == null) {
return null; return null;
@ -32,7 +32,7 @@ public class UserUtils {
try { try {
claims = Jwts.parser().setSigningKey(JwtConstants.JWT_SECRET).parseClaimsJws(authHeader).getBody(); claims = Jwts.parser().setSigningKey(JwtConstants.JWT_SECRET).parseClaimsJws(authHeader).getBody();
} catch (final SignatureException e) { } catch (final SignatureException e) {
throw new MallApiException(ErrorCode.UNAUTHORIZED); throw new BaseApiException(ErrorCode.UNAUTHORIZED);
} }
Object account = claims.getId(); Object account = claims.getId();
if (!oConvertUtils.isEmpty(account)) { if (!oConvertUtils.isEmpty(account)) {
@ -41,7 +41,7 @@ public class UserUtils {
return userMapper.findByAccount(account.toString()); return userMapper.findByAccount(account.toString());
} }
} else { } else {
throw new MallApiException(ErrorCode.UNAUTHORIZED); throw new BaseApiException(ErrorCode.UNAUTHORIZED);
} }
return null; return null;
} }

View File

@ -4,7 +4,7 @@ import com.rymcu.vertical.core.result.GlobalResult;
import com.rymcu.vertical.core.result.GlobalResultGenerator; import com.rymcu.vertical.core.result.GlobalResultGenerator;
import com.rymcu.vertical.dto.ArticleDTO; import com.rymcu.vertical.dto.ArticleDTO;
import com.rymcu.vertical.service.ArticleService; import com.rymcu.vertical.service.ArticleService;
import com.rymcu.vertical.web.api.exception.MallApiException; import com.rymcu.vertical.web.api.exception.BaseApiException;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import javax.annotation.Resource;
@ -20,13 +20,13 @@ public class ArticleController {
private ArticleService articleService; private ArticleService articleService;
@PostMapping("/post") @PostMapping("/post")
public GlobalResult postArticle(@RequestBody ArticleDTO article, HttpServletRequest request) throws MallApiException, UnsupportedEncodingException { public GlobalResult postArticle(@RequestBody ArticleDTO article, HttpServletRequest request) throws BaseApiException, UnsupportedEncodingException {
Map map = articleService.postArticle(article,request); Map map = articleService.postArticle(article,request);
return GlobalResultGenerator.genSuccessResult(map); return GlobalResultGenerator.genSuccessResult(map);
} }
@PutMapping("/post") @PutMapping("/post")
public GlobalResult updateArticle(@RequestBody ArticleDTO article, HttpServletRequest request) throws MallApiException, UnsupportedEncodingException { public GlobalResult updateArticle(@RequestBody ArticleDTO article, HttpServletRequest request) throws BaseApiException, UnsupportedEncodingException {
Map map = articleService.postArticle(article,request); Map map = articleService.postArticle(article,request);
return GlobalResultGenerator.genSuccessResult(map); return GlobalResultGenerator.genSuccessResult(map);
} }

View File

@ -8,13 +8,12 @@ import com.rymcu.vertical.util.FileUtils;
import com.rymcu.vertical.util.UserUtils; import com.rymcu.vertical.util.UserUtils;
import com.rymcu.vertical.util.Utils; import com.rymcu.vertical.util.Utils;
import com.rymcu.vertical.web.api.exception.ErrorCode; import com.rymcu.vertical.web.api.exception.ErrorCode;
import com.rymcu.vertical.web.api.exception.MallApiException; import com.rymcu.vertical.web.api.exception.BaseApiException;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.util.FileCopyUtils; import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -124,10 +123,10 @@ public class UploadController {
} }
@GetMapping("/token") @GetMapping("/token")
public GlobalResult uploadToken(HttpServletRequest request) throws MallApiException { public GlobalResult uploadToken(HttpServletRequest request) throws BaseApiException {
String authHeader = request.getHeader(JwtConstants.AUTHORIZATION); String authHeader = request.getHeader(JwtConstants.AUTHORIZATION);
if(StringUtils.isBlank(authHeader)){ if(StringUtils.isBlank(authHeader)){
throw new MallApiException(ErrorCode.UNAUTHORIZED); throw new BaseApiException(ErrorCode.UNAUTHORIZED);
} }
TUser tUser = UserUtils.getTUser(authHeader); TUser tUser = UserUtils.getTUser(authHeader);
Map map = new HashMap(2); Map map = new HashMap(2);

View File

@ -3,12 +3,12 @@ package com.rymcu.vertical.web.api.exception;
/** /**
* 服务业务异常如 账号或密码错误 该异常只做INFO级别的日志记录 @see WebMvcConfigurer * 服务业务异常如 账号或密码错误 该异常只做INFO级别的日志记录 @see WebMvcConfigurer
*/ */
public class MallApiException extends Exception { public class BaseApiException extends Exception {
private int code; private int code;
private String message; private String message;
public MallApiException(ErrorCode errorCode) { public BaseApiException(ErrorCode errorCode) {
super(errorCode.getMessage()); super(errorCode.getMessage());
this.code = errorCode.getCode(); this.code = errorCode.getCode();
this.message = errorCode.getMessage(); this.message = errorCode.getMessage();

View File

@ -1,6 +1,6 @@
package com.rymcu.vertical.web.api.exception; package com.rymcu.vertical.web.api.exception;
import com.rymcu.vertical.config.HpeisExceptionHandler; import com.rymcu.vertical.config.BaseExceptionHandler;
import com.rymcu.vertical.core.result.GlobalResult; import com.rymcu.vertical.core.result.GlobalResult;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -12,17 +12,17 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
@ControllerAdvice(basePackages = {"com.rymcu.vertical.web.api", "com.rymcu.vertical.jwt"} ) @ControllerAdvice(basePackages = {"com.rymcu.vertical.web.api", "com.rymcu.vertical.jwt"} )
public class MallApiExceptionHandler { public class BaseApiExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(HpeisExceptionHandler.class); private final Logger logger = LoggerFactory.getLogger(BaseExceptionHandler.class);
@ExceptionHandler(MallApiException.class) @ExceptionHandler(BaseApiException.class)
@ResponseBody @ResponseBody
public GlobalResult handlerException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { public GlobalResult handlerException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
logger.error(ex.getMessage()); logger.error(ex.getMessage());
GlobalResult result = new GlobalResult(); GlobalResult result = new GlobalResult();
if (ex instanceof MallApiException) { if (ex instanceof BaseApiException) {
result.setCode(((MallApiException) ex).getCode()); result.setCode(((BaseApiException) ex).getCode());
result.setMessage(ex.getMessage()); result.setMessage(ex.getMessage());
} /*else if (ex instanceof Exception) { } /*else if (ex instanceof Exception) {
result.setCode(ErrorCode.INTERNAL_SERVER_ERROR.getCode()); result.setCode(ErrorCode.INTERNAL_SERVER_ERROR.getCode());