1.add user login pre condition in GlobalInterceptor

main
Gary 1 year ago
parent 495669ac84
commit a3d61686e6

@ -8,5 +8,7 @@ import java.lang.annotation.Target;
@Target(ElementType.METHOD) @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface GlobalInterceptor { public @interface GlobalInterceptor {
boolean checkLogin() default false;
boolean checkAdminLogin() default false;
boolean checkParam() default true; boolean checkParam() default true;
} }

@ -1,10 +1,11 @@
package com.luoo.user.aspect; package com.luoo.user.aspect;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Parameter; import java.lang.reflect.Parameter;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Aspect;
@ -12,82 +13,138 @@ import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature; import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.luoo.user.annotation.GlobalInterceptor; import com.luoo.user.annotation.GlobalInterceptor;
import com.luoo.user.annotation.VerifyParam; import com.luoo.user.annotation.VerifyParam;
import com.luoo.user.constants.Constants;
import com.luoo.user.util.VerifyUtils; import com.luoo.user.util.VerifyUtils;
import api.StatusCode; import api.StatusCode;
import dto.UserLoginDto;
import exception.BizException; import exception.BizException;
import util.JwtUtil;
import util.StringTools; import util.StringTools;
@Aspect @Aspect
@Component("operationAspect") @Component("operationAspect")
public class OperationAspect { public class OperationAspect {
static Logger logger= LoggerFactory.getLogger(OperationAspect.class); static Logger logger = LoggerFactory.getLogger(OperationAspect.class);
private static final String[] BASE_TYPE_ARRAY=new String[] {"java.lang.String","java.lang.Integer","java.lang.Long"}; private static final String[] BASE_TYPE_ARRAY = new String[] { "java.lang.String", "java.lang.Integer",
@Before("@annotation(com.luoo.user.annotation.GlobalInterceptor)") "java.lang.Long" };
public void interceptorDo(JoinPoint point) {
Object[] arguments=point.getArgs(); @Autowired
Method method=((MethodSignature)point.getSignature()).getMethod(); private JwtUtil jwtUtil;
GlobalInterceptor interceptor=method.getAnnotation(GlobalInterceptor.class);
if(null==interceptor) { @Before("@annotation(com.luoo.user.annotation.GlobalInterceptor)")
return; public void interceptorDo(JoinPoint point) {
} Object[] arguments = point.getArgs();
if(interceptor.checkParam()) { Method method = ((MethodSignature) point.getSignature()).getMethod();
validateParams(method,arguments); GlobalInterceptor interceptor = method.getAnnotation(GlobalInterceptor.class);
} if (null == interceptor) {
} return;
private void validateParams(Method method, Object[] arguments) { }
Parameter[] parameters=method.getParameters(); /**
for(int i=0;i<parameters.length;i++) { *
Parameter parameter=parameters[i]; */
Object value=arguments[i]; if (interceptor.checkLogin()) {
VerifyParam verifyParam=parameter.getAnnotation(VerifyParam.class); checkLogin();
if(null==verifyParam) { }
continue;
} /**
String paramTypeName=parameter.getParameterizedType().getTypeName(); *
if(ArrayUtils.contains(BASE_TYPE_ARRAY, paramTypeName)) { */
checkValue(value,verifyParam); if (interceptor.checkAdminLogin()) {
}else { checkAdminLogin();
checkObjValue(parameter,value); }
}
} /**
} *
private void checkObjValue(Parameter parameter,Object value) { */
try { if (interceptor.checkParam()) {
String typeName=parameter.getParameterizedType().getTypeName(); validateParams(method, arguments);
Class<?> clazz=Class.forName(typeName); }
Field[] fields= clazz.getDeclaredFields(); }
for(Field field:fields) {
VerifyParam fieldVerifyParam=field.getAnnotation(VerifyParam.class); private void checkAdminLogin() {
if(null==fieldVerifyParam) { UserLoginDto userLoginDto = getUserLoginDtoFromToken();
continue; if (userLoginDto == null) {
} throw new BizException(StatusCode.UNAUTHORIZED);
field.setAccessible(true); }
Object resultValue=field.get(value); if (!Constants.TOKEN_ROLE_ADMIN_USER.equals(userLoginDto.getRoles())) {
checkValue(resultValue,fieldVerifyParam); throw new BizException(StatusCode.FORBIDDEN);
} }
}
}catch(Exception e) {
logger.error(StatusCode.VALIDATE_FAILED.getMessage(),e.getMessage()); private void checkLogin() {
throw new BizException(StatusCode.VALIDATE_FAILED); UserLoginDto userLoginDto = getUserLoginDtoFromToken();
} if (userLoginDto == null) {
} throw new BizException(StatusCode.UNAUTHORIZED);
}
private void checkValue(Object value, VerifyParam verifyParam) { }
boolean isEmpty= null==value||StringTools.isEmpty(value.toString());
int length= null==value?0:value.toString().length(); private UserLoginDto getUserLoginDtoFromToken() {
if(isEmpty&&verifyParam.required()) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
throw new BizException(StatusCode.VALIDATE_FAILED); .getRequest();
} String token = request.getHeader("token");
if(!isEmpty&&(-1!=verifyParam.max()&&verifyParam.max()<length||-1!=verifyParam.min()&&verifyParam.min()>length)) { return jwtUtil.getUserLoginDto(token);
throw new BizException(StatusCode.VALIDATE_FAILED); }
}
if(!isEmpty&&!StringTools.isEmpty(verifyParam.regex().getRegex())&&!VerifyUtils.verify(verifyParam.regex(), String.valueOf(value))) { private void validateParams(Method method, Object[] arguments) {
throw new BizException(StatusCode.VALIDATE_FAILED); Parameter[] parameters = method.getParameters();
} for (int i = 0; i < parameters.length; i++) {
} Parameter parameter = parameters[i];
Object value = arguments[i];
VerifyParam verifyParam = parameter.getAnnotation(VerifyParam.class);
if (null == verifyParam) {
continue;
}
String paramTypeName = parameter.getParameterizedType().getTypeName();
if (ArrayUtils.contains(BASE_TYPE_ARRAY, paramTypeName)) {
checkValue(value, verifyParam);
} else {
checkObjValue(parameter, value);
}
}
}
private void checkObjValue(Parameter parameter, Object value) {
try {
String typeName = parameter.getParameterizedType().getTypeName();
Class<?> clazz = Class.forName(typeName);
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
VerifyParam fieldVerifyParam = field.getAnnotation(VerifyParam.class);
if (null == fieldVerifyParam) {
continue;
}
field.setAccessible(true);
Object resultValue = field.get(value);
checkValue(resultValue, fieldVerifyParam);
}
} catch (Exception e) {
logger.error(StatusCode.VALIDATE_FAILED.getMessage(), e.getMessage());
throw new BizException(StatusCode.VALIDATE_FAILED);
}
}
private void checkValue(Object value, VerifyParam verifyParam) {
boolean isEmpty = null == value || StringTools.isEmpty(value.toString());
int length = null == value ? 0 : value.toString().length();
if (isEmpty && verifyParam.required()) {
throw new BizException(StatusCode.VALIDATE_FAILED);
}
if (!isEmpty && (-1 != verifyParam.max() && verifyParam.max() < length
|| -1 != verifyParam.min() && verifyParam.min() > length)) {
throw new BizException(StatusCode.VALIDATE_FAILED);
}
if (!isEmpty && !StringTools.isEmpty(verifyParam.regex().getRegex())
&& !VerifyUtils.verify(verifyParam.regex(), String.valueOf(value))) {
throw new BizException(StatusCode.VALIDATE_FAILED);
}
}
} }

@ -98,7 +98,7 @@ public class AdminController {
@ApiImplicitParams({ @ApiImplicitParams({
@ApiImplicitParam(name = "ids", value = "多个id以','分隔", required = true) }) @ApiImplicitParam(name = "ids", value = "多个id以','分隔", required = true) })
@GetMapping("/ids/{id}") @GetMapping("/ids/{id}")
@GlobalInterceptor @GlobalInterceptor(checkAdminLogin=true)
public Result<List<Admin>> findAllById(@PathVariable @VerifyParam(required=true) String ids){ public Result<List<Admin>> findAllById(@PathVariable @VerifyParam(required=true) String ids){
List<String> idList=Arrays.stream(ids.split(",")).map(String::trim).collect(Collectors.toList()); List<String> idList=Arrays.stream(ids.split(",")).map(String::trim).collect(Collectors.toList());
return Result.success(adminService.findAllById(idList)); return Result.success(adminService.findAllById(idList));

Loading…
Cancel
Save