use of com.moxi.mogublog.commons.entity.OnlineAdmin in project mogu_blog_v2 by moxi624.
the class TokenInterceptor method preHandle.
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
StringBuffer requestURL = request.getRequestURL();
// 得到请求头信息authorization信息
String authHeader = "";
if (request.getHeader("Authorization") != null) {
authHeader = request.getHeader("Authorization");
} else if (request.getParameter(SysConf.TOKEN) != null) {
authHeader = request.getParameter(SysConf.TOKEN);
}
if (StringUtils.isNotEmpty(authHeader) && authHeader.startsWith("bearer_")) {
// 获取在线的管理员信息
RedisUtil redisUtil = SpringUtils.getBean(RedisUtil.class);
String onlineAdmin = redisUtil.get(RedisConf.LOGIN_TOKEN_KEY + RedisConf.SEGMENTATION + authHeader);
if (StringUtils.isNotEmpty(onlineAdmin)) {
// 得到管理员UID和 Name
OnlineAdmin admin = JsonUtils.jsonToPojo(onlineAdmin, OnlineAdmin.class);
request.setAttribute(SysConf.ADMIN_UID, admin.getAdminUid());
request.setAttribute(SysConf.NAME, admin.getUserName());
request.setAttribute(SysConf.TOKEN, authHeader);
}
}
return true;
}
use of com.moxi.mogublog.commons.entity.OnlineAdmin in project mogu_blog_v2 by moxi624.
the class AdminServiceImpl method addOnlineAdmin.
@Override
public void addOnlineAdmin(Admin admin, Long expirationSecond) {
HttpServletRequest request = RequestHolder.getRequest();
Map<String, String> map = IpUtils.getOsAndBrowserInfo(request);
String os = map.get(SysConf.OS);
String browser = map.get(SysConf.BROWSER);
String ip = IpUtils.getIpAddr(request);
OnlineAdmin onlineAdmin = new OnlineAdmin();
onlineAdmin.setAdminUid(admin.getUid());
onlineAdmin.setTokenId(admin.getTokenUid());
onlineAdmin.setToken(admin.getValidCode());
onlineAdmin.setOs(os);
onlineAdmin.setBrowser(browser);
onlineAdmin.setIpaddr(ip);
onlineAdmin.setLoginTime(DateUtils.getNowTime());
onlineAdmin.setRoleName(admin.getRole().getRoleName());
onlineAdmin.setUserName(admin.getUserName());
onlineAdmin.setExpireTime(DateUtils.getDateStr(new Date(), expirationSecond));
// 从Redis中获取IP来源
String jsonResult = redisUtil.get(RedisConf.IP_SOURCE + Constants.SYMBOL_COLON + ip);
if (StringUtils.isEmpty(jsonResult)) {
String addresses = IpUtils.getAddresses(SysConf.IP + SysConf.EQUAL_TO + ip, SysConf.UTF_8);
if (StringUtils.isNotEmpty(addresses)) {
onlineAdmin.setLoginLocation(addresses);
redisUtil.setEx(RedisConf.IP_SOURCE + Constants.SYMBOL_COLON + ip, addresses, 24, TimeUnit.HOURS);
}
} else {
onlineAdmin.setLoginLocation(jsonResult);
}
// 将登录的管理员存储到在线用户表
redisUtil.setEx(RedisConf.LOGIN_TOKEN_KEY + RedisConf.SEGMENTATION + admin.getValidCode(), JsonUtils.objectToJson(onlineAdmin), expirationSecond, TimeUnit.SECONDS);
// 在维护一张表,用于 uuid - token 互相转换
redisUtil.setEx(RedisConf.LOGIN_UUID_KEY + RedisConf.SEGMENTATION + admin.getTokenUid(), admin.getValidCode(), expirationSecond, TimeUnit.SECONDS);
}
use of com.moxi.mogublog.commons.entity.OnlineAdmin in project mogu_blog_v2 by moxi624.
the class AdminServiceImpl method getOnlineAdminList.
@Override
public String getOnlineAdminList(AdminVO adminVO) {
// 获取Redis中匹配的所有key
Set<String> keys = redisUtil.keys(RedisConf.LOGIN_TOKEN_KEY + "*");
List<String> onlineAdminJsonList = redisUtil.multiGet(keys);
// 拼装分页信息
int pageSize = adminVO.getPageSize().intValue();
int currentPage = adminVO.getCurrentPage().intValue();
int total = onlineAdminJsonList.size();
int startIndex = Math.max((currentPage - 1) * pageSize, 0);
int endIndex = Math.min(currentPage * pageSize, total);
// TODO 截取出当前分页下的内容,后面考虑用Redis List做分页
List<String> onlineAdminSubList = onlineAdminJsonList.subList(startIndex, endIndex);
List<OnlineAdmin> onlineAdminList = new ArrayList<>();
for (String item : onlineAdminSubList) {
OnlineAdmin onlineAdmin = JsonUtils.jsonToPojo(item, OnlineAdmin.class);
// 数据脱敏【移除用户的token令牌】
onlineAdmin.setToken("");
onlineAdminList.add(onlineAdmin);
}
Page<OnlineAdmin> page = new Page<>();
page.setCurrent(currentPage);
page.setTotal(total);
page.setSize(pageSize);
page.setRecords(onlineAdminList);
return ResultUtil.successWithData(page);
}
use of com.moxi.mogublog.commons.entity.OnlineAdmin in project mogu_blog_v2 by moxi624.
the class JwtAuthenticationTokenFilter method doFilterInternal.
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
// 得到请求头信息authorization信息
String authHeader = request.getHeader(tokenHeader);
// TODO 判断是否触发 mogu-picture发送的请求【图片上传鉴权,需要用户登录,携带token请求admin,后期考虑加入OAuth服务统一鉴权】
final String pictureToken = request.getHeader("pictureToken");
if (StringUtils.isNotEmpty(pictureToken)) {
authHeader = pictureToken;
}
// 请求头 'Authorization': tokenHead + token
if (authHeader != null && authHeader.startsWith(tokenHead)) {
log.error("传递过来的token为: {}", authHeader);
final String token = authHeader.substring(tokenHead.length());
// 私钥
String base64Secret = audience.getBase64Secret();
// 获取在线的管理员信息
String onlineAdmin = redisUtil.get(RedisConf.LOGIN_TOKEN_KEY + RedisConf.SEGMENTATION + authHeader);
if (StringUtils.isNotEmpty(onlineAdmin) && !jwtTokenUtil.isExpiration(token, base64Secret)) {
/**
* 得到过期时间
*/
Date expirationDate = jwtTokenUtil.getExpiration(token, base64Secret);
long nowMillis = System.currentTimeMillis();
Date nowDate = new Date(nowMillis);
// 得到两个日期相差的间隔,秒
Integer survivalSecond = DateUtils.getSecondByTwoDay(expirationDate, nowDate);
// 而旧的Token将会在不久之后从Redis中过期
if (survivalSecond < refreshSecond) {
// 生成一个新的Token
String newToken = tokenHead + jwtTokenUtil.refreshToken(token, base64Secret, expiresSecond * 1000);
// 生成新的token,发送到客户端
CookieUtils.setCookie("Admin-Token", newToken, expiresSecond.intValue());
OnlineAdmin newOnlineAdmin = JsonUtils.jsonToPojo(onlineAdmin, OnlineAdmin.class);
// 获取旧的TokenUid
String oldTokenUid = newOnlineAdmin.getTokenId();
// 随机生成一个TokenUid,用于换取Token令牌
String tokenUid = StringUtils.getUUID();
newOnlineAdmin.setTokenId(tokenUid);
newOnlineAdmin.setToken(newToken);
newOnlineAdmin.setExpireTime(DateUtils.getDateStr(new Date(), expiresSecond));
newOnlineAdmin.setLoginTime(DateUtils.getNowTime());
// 移除原来的旧Token和TokenUid
redisUtil.delete(RedisConf.LOGIN_TOKEN_KEY + Constants.SYMBOL_COLON + authHeader);
redisUtil.delete(RedisConf.LOGIN_UUID_KEY + Constants.SYMBOL_COLON + oldTokenUid);
// 将新token赋值,用于后续使用
authHeader = newToken;
// 将新的Token存入Redis中
redisUtil.setEx(RedisConf.LOGIN_TOKEN_KEY + Constants.SYMBOL_COLON + newToken, JsonUtils.objectToJson(newOnlineAdmin), expiresSecond, TimeUnit.SECONDS);
// 维护 uuid - token 互相转换的Redis集合【主要用于在线用户管理】
redisUtil.setEx(RedisConf.LOGIN_UUID_KEY + Constants.SYMBOL_COLON + tokenUid, newToken, expiresSecond, TimeUnit.SECONDS);
}
} else {
chain.doFilter(request, response);
return;
}
String username = jwtTokenUtil.getUsername(token, base64Secret);
String adminUid = jwtTokenUtil.getUserUid(token, base64Secret);
// 把adminUid存储到request中
request.setAttribute(SysConf.ADMIN_UID, adminUid);
request.setAttribute(SysConf.USER_NAME, username);
request.setAttribute(SysConf.TOKEN, authHeader);
log.info("解析出来用户: {}", username);
log.info("解析出来的用户Uid: {}", adminUid);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
// 通过用户名加载SpringSecurity用户
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
// 校验Token的有效性
if (jwtTokenUtil.validateToken(token, userDetails, base64Secret)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// 以后可以security中取得SecurityUser信息
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
}
chain.doFilter(request, response);
}
use of com.moxi.mogublog.commons.entity.OnlineAdmin in project mogu_blog_v2 by moxi624.
the class LoginRestApi method logout.
@ApiOperation(value = "退出登录", notes = "退出登录", response = String.class)
@PostMapping(value = "/logout")
public String logout() {
ServletRequestAttributes attribute = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attribute.getRequest();
String token = request.getAttribute(SysConf.TOKEN).toString();
if (StringUtils.isEmpty(token)) {
return ResultUtil.result(SysConf.ERROR, MessageConf.OPERATION_FAIL);
} else {
// 获取在线用户信息
String adminJson = redisUtil.get(RedisConf.LOGIN_TOKEN_KEY + RedisConf.SEGMENTATION + token);
if (StringUtils.isNotEmpty(adminJson)) {
OnlineAdmin onlineAdmin = JsonUtils.jsonToPojo(adminJson, OnlineAdmin.class);
String tokenUid = onlineAdmin.getTokenId();
// 移除Redis中的TokenUid
redisUtil.delete(RedisConf.LOGIN_UUID_KEY + RedisConf.SEGMENTATION + tokenUid);
}
// 移除Redis中的用户
redisUtil.delete(RedisConf.LOGIN_TOKEN_KEY + RedisConf.SEGMENTATION + token);
SecurityContextHolder.clearContext();
return ResultUtil.result(SysConf.SUCCESS, MessageConf.OPERATION_SUCCESS);
}
}
Aggregations