MagicApiRequestInterceptor.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package com.xjrsoft.common.interceptor;
  2. import cn.dev33.satoken.session.SaSession;
  3. import cn.dev33.satoken.stp.StpUtil;
  4. import cn.dev33.satoken.strategy.SaStrategy;
  5. import com.xjrsoft.common.constant.GlobalConstant;
  6. import com.xjrsoft.common.enums.ResponseCode;
  7. import com.xjrsoft.common.model.result.R;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.springframework.stereotype.Component;
  10. import org.ssssssss.magicapi.core.context.RequestEntity;
  11. import org.ssssssss.magicapi.core.interceptor.RequestInterceptor;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. /**
  15. * magic-api 接口鉴权
  16. *
  17. * @author tzx
  18. */
  19. @Component
  20. @Slf4j
  21. public class MagicApiRequestInterceptor implements RequestInterceptor {
  22. /***
  23. * 接口请求之前
  24. * @param requestEntity
  25. * @return
  26. */
  27. @Override
  28. public Object preHandle(RequestEntity requestEntity) {
  29. if (!StpUtil.isLogin()) {
  30. return R.error(ResponseCode.UN_AUTHORIZED.getCode(), ResponseCode.UN_AUTHORIZED.getMessage());
  31. }
  32. SaSession tokenSession = StpUtil.getTokenSession();
  33. List<Long> roleIds = tokenSession.get(GlobalConstant.LOGIN_USER_ROLE_ID_KEY, new ArrayList<>());
  34. if (roleIds.size() == 0) {
  35. tokenSession = StpUtil.getSessionByLoginId(StpUtil.getLoginId());
  36. roleIds = tokenSession.get(GlobalConstant.LOGIN_USER_ROLE_ID_KEY, new ArrayList<>());
  37. }
  38. //非管理员需要进行权限验证
  39. if (!roleIds.contains(GlobalConstant.SUPER_ADMIN_ROLE_ID)) {
  40. if (!SaStrategy.me.hasElement.apply(tokenSession.get(GlobalConstant.LOGIN_USER_INTERFACE_AUTH_CODE_KEY, new ArrayList<>()), requestEntity.getApiInfo().getId())) {
  41. return R.error(ResponseCode.MAGIC_API_UN_AUTHORIZED.getCode(), ResponseCode.MAGIC_API_UN_AUTHORIZED.getMessage());
  42. }
  43. }
  44. return null;
  45. }
  46. /**
  47. * 接口执行之后
  48. *
  49. * @param requestEntity
  50. * @param returnValue
  51. * @return
  52. */
  53. @Override
  54. public Object postHandle(RequestEntity requestEntity, Object returnValue) {
  55. log.info("{} 执行完毕,返回结果:{}", requestEntity.getApiInfo().getName(), returnValue);
  56. return null;
  57. }
  58. }