| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- package nju.seec.helper.aspect.auth;
- import nju.seec.helper.util.Consts;
- import nju.seec.helper.dto.LoginUser;
- import nju.seec.helper.util.exception.HelperException;
- import org.aspectj.lang.JoinPoint;
- import org.aspectj.lang.annotation.Aspect;
- import org.aspectj.lang.annotation.Before;
- import org.springframework.beans.BeanUtils;
- import org.springframework.stereotype.Component;
- import org.springframework.web.context.request.RequestContextHolder;
- import org.springframework.web.context.request.ServletRequestAttributes;
- import javax.servlet.http.HttpSession;
- import java.util.Arrays;
- import java.util.Objects;
- import java.util.stream.Collectors;
- /**
- * @author cst
- */
- @Aspect
- @Component
- public class AuthAspect {
- @Before("execution(public * nju.seec.helper.controller.*.*(..)) && @annotation(auth)")
- public void authCheck(JoinPoint joinPoint, Auth auth) {
- HttpSession session =
- ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))
- .getRequest()
- .getSession();
- LoginUser user = (LoginUser) session.getAttribute(Consts.SESSION_USER_NAME);
- if (user == null) {
- throw HelperException.of(HelperException.ExceptionType.NOT_LOGIN, "您未登录");
- } else if (!Arrays
- .stream(auth.roles())
- .collect(Collectors.toSet())
- .contains(user.getType())) {
- throw HelperException.of(HelperException.ExceptionType.FORBIDDEN, String.format("您暂时无法%s,请重新登录", auth.message()));
- }
- Object[] objects = joinPoint.getArgs();
- for (Object o : objects) {
- if (o.getClass() == LoginUser.class) {
- BeanUtils.copyProperties(user, o);
- break;
- }
- }
- }
- }
|