/**
* 权限拦截器
*
* @author yanglizhe
*
*/
public class AuthorityInterceptor extends HandlerInterceptorAdapter{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
boolean checkAuth = true;
Method method = ((HandlerMethod) handler).getMethod();
/**
* 不限权限
*/
if(method.isAnnotationPresent(UnAuth.class)){
//AuthType 为 SETTING时,需要根据配置权限
if(!(getInvoke(method, UnAuth.class, "type").equals(AuthType.SETTING) && Constant.NEED_AUTH)){
checkAuth = false;
}
}
if(checkAuth && StringUtils.isNullOrEmpty(request.getHeader("Authorization"))){
String authorization = request.getParameter("Authorization");
if(authorization == null || SessionManager.getTokenSessionByAuthorization(authorization) == null){
throw new AuthorityException("无效的Authorization");
}
}
/**
* 角色限制
*/
if(method.isAnnotationPresent(Role.class) || !StringUtils.isNullOrEmpty(request.getHeader("ForceAuth"))){
if(StringUtils.isNullOrEmpty(request.getHeader("Authorization"))){
throw new AuthorityException("无效的Authorization");
}
TokenSession tokenSession = SessionManager.getTokenSessionByAuthorization(request.getHeader("Authorization"));
if(tokenSession == null){
throw new AuthorityException("请重新登录");
}
if(method.isAnnotationPresent(Role.class)){
RoleType[] roleTypes = (RoleType[])getInvoke(method, Role.class, "value");
boolean inRoles = false;
for(RoleType roleType : roleTypes){
if(roleType.equals(tokenSession.getRoleType())){
inRoles = true;
break;
}
}
if(!inRoles){
throw new AuthorityException("权限不足");
}
}
}*/
response.setHeader("Access-Control-Allow-Origin", "*");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
}
@SuppressWarnings("unchecked")
private Object getInvoke(Method method, Class clazz, String field) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
Annotation annotation = method.getAnnotation(clazz);
return annotation.annotationType().getMethod(field).invoke(annotation);
}
}