1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| package io.coderyeah.basic.interceptor;
import com.alibaba.fastjson.JSON; import io.coderyeah.basic.annotation.PreAuthorize; import io.coderyeah.basic.constant.Constants; import io.coderyeah.org.mapper.EmployeeMapper; import io.coderyeah.user.domain.LoginInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.util.List; import java.util.concurrent.TimeUnit;
@Component public class LoginInterceptor implements HandlerInterceptor { @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private EmployeeMapper employeeMapper;
@Override public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception { if (!(handler instanceof HandlerMethod)) { return true; }
String token = req.getHeader("token"); if (token != null) { String loginInfo = stringRedisTemplate.opsForValue().get(Constants.LOGIN_TOKEN + token); if (loginInfo != null) { stringRedisTemplate.opsForValue().set(Constants.LOGIN_TOKEN + token, loginInfo, 30, TimeUnit.MINUTES); final LoginInfo info = JSON.parseObject(loginInfo, LoginInfo.class); if (info.getType() == 1) { return true; } final HandlerMethod handlerMethod = (HandlerMethod) handler; final PreAuthorize p = handlerMethod.getMethodAnnotation(PreAuthorize.class); if (null == p) { return true; } final String sn = p.sn(); List<String> ownPermissions = employeeMapper.getPermissionSnByLoginInfoId(info.getId()); if (ownPermissions.contains(sn)) { return true; } resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=utf-8"); final PrintWriter writer = resp.getWriter(); writer.print("{\"success\":false,\"message\":\"noPermission\"}"); writer.close(); return false; } } resp.setContentType("application/json;charset=UTF-8"); resp.getWriter().println("{\"success\":false,\"message\":\"noLogin\"}"); return false; } }
|