@Override
public CurrentAdminInfo login(LoginParam param) {
Admin admin = adminMapper.selectOne(new QueryWrapper<Admin>().lambda().eq(Admin::getUsername, param.getUsername()));
if (admin == null) {
throw new BusinessException(ApiResult.ACCOUNT_NOT_EXIST);
}
if (!DigestUtils.md5Hex(param.getPassword()).equals(admin.getPassword())) {
// 计算次数
throw new BusinessException(ApiResult.PASSWORD_ERROR);
}
if (admin.getLocked() || !admin.getEnabled()) {
throw new BusinessException(ApiResult.ACCOUNT_RESTRICTED_LOGIN);
}
admin.setLoginDate(new Date());
admin.setLoginIp(RequestUtils.getIp());
adminMapper.updateById(admin);
String accessToken = IdUtil.fastSimpleUUID();
CurrentAdminInfo adminLoginVO = new CurrentAdminInfo();
adminLoginVO.setId(admin.getId());
adminLoginVO.setAccessToken(accessToken);
adminLoginVO.setName(admin.getName());
//注意:1,这里保存到redis里的value是一个Json字符串,并且设置过期是时间
//2,StrUtil.format(RedisKeyEnum.ADMIN_LOGIN_TOKEN.getKey(), accessToken)是拼接字符串功能
stringRedisTemplate.opsForValue().
set(StrUtil.format(RedisKeyEnum.ADMIN_LOGIN_TOKEN.getKey(), accessToken), JSON.toJSONString(adminLoginVO), RedisKeyEnum.ADMIN_LOGIN_TOKEN.getTtl(), TimeUnit.SECONDS);
return adminLoginVO;
}
上面这个登陆过程:注意这里保存accessTocken的方式
拦截器:
前端把accessToken传过来
/**
* @author lcx
*/
@Slf4j
@Component
public class AdminInterceptor extends HandlerInterceptorAdapter {
private final StringRedisTemplate stringRedisTemplate;
public AdminInterceptor(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String accessToken = request.getHeader(SystemConstants.ACCESS_TOKEN);
CurrentAdminInfo currentAdminInfo;
if (StringUtils.isNotBlank(accessToken)) {
//这里redis里的值应该是第一次登陆的时候保存进去的
String value = stringRedisTemplate.opsForValue().get(StrUtil.format(RedisKeyEnum.ADMIN_LOGIN_TOKEN.getKey(), accessToken));
currentAdminInfo = JSONObject.parseObject(value, CurrentAdminInfo.class);
if (currentAdminInfo != null) {//不等于null就说明已经登陆成功了
//这一步很重要 为了后面做铺垫 后面的各种XxxBaseController会用到这个值
request.setAttribute(CurrentShopInfo.PRINCIPAL_ATTRIBUTE_NAME, currentAdminInfo);
return true;
}
}
throw new BusinessException(ApiResult.NOT_LOGIN);
}
}
上面之所以有getCurrentAdmin()这个方法 就是因为拦截器里设置了这一步request.setAttribute(CurrentShopInfo.PRINCIPAL_ATTRIBUTE_NAME, currentAdminInfo);
public class BaseAdminController {
protected CurrentAdminInfo getCurrentAdmin() {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (servletRequestAttributes != null) {
HttpServletRequest request = servletRequestAttributes.getRequest();
return (CurrentAdminInfo) request.getAttribute(CurrentAdminInfo.PRINCIPAL_ATTRIBUTE_NAME);
}
return null;
}
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
}