1. 验证码调整

2. token 解析调增
3. 代码优化
This commit is contained in:
wangiegie@gmail.com 2017-12-21 22:48:23 +08:00
parent 1da228e8ae
commit 178f85be9a
20 changed files with 265 additions and 231 deletions

View File

@ -65,9 +65,9 @@
<version>[7.2.0, 7.2.99]</version>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-pay</artifactId>
<version>2.9.0</version>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
</dependencies>

View File

@ -0,0 +1,41 @@
package com.github.pig.admin.common.config;
import com.github.pig.common.constant.SecurityConstants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
/**
* @author lengleng
* @date 2017-12-21 21:12:18
*/
@Configuration
public class KaptchaConfig {
private static final String KAPTCHA_BORDER = "kaptcha.border";
private static final String KAPTCHA_TEXTPRODUCER_FONT_COLOR = "kaptcha.textproducer.font.color";
private static final String KAPTCHA_TEXTPRODUCER_CHAR_SPACE = "kaptcha.textproducer.char.space";
private static final String KAPTCHA_IMAGE_WIDTH = "kaptcha.image.width";
private static final String KAPTCHA_IMAGE_HEIGHT = "kaptcha.image.height";
private static final String KAPTCHA_TEXTPRODUCER_CHAR_LENGTH = "kaptcha.textproducer.char.length";
private static final Object KAPTCHA_IMAGE_FONT_SIZE = "kaptcha.textproducer.font.size";
@Bean
public DefaultKaptcha producer() {
Properties properties = new Properties();
properties.put(KAPTCHA_BORDER, SecurityConstants.DEFAULT_IMAGE_BORDER);
properties.put(KAPTCHA_TEXTPRODUCER_FONT_COLOR, SecurityConstants.DEFAULT_COLOR_FONT);
properties.put(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, SecurityConstants.DEFAULT_CHAR_SPACE);
properties.put(KAPTCHA_IMAGE_WIDTH, SecurityConstants.DEFAULT_IMAGE_WIDTH);
properties.put(KAPTCHA_IMAGE_HEIGHT, SecurityConstants.DEFAULT_IMAGE_HEIGHT);
properties.put(KAPTCHA_IMAGE_FONT_SIZE, SecurityConstants.DEFAULT_IMAGE_FONT_SIZE);
properties.put(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, SecurityConstants.DEFAULT_IMAGE_LENGTH);
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}

View File

@ -1,70 +0,0 @@
package com.github.pig.admin.common.util;
import com.github.pig.common.vo.ImageCode;
import org.springframework.stereotype.Component;
import com.github.pig.common.constant.SecurityConstants;
import org.springframework.web.context.request.ServletWebRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
* @author lengleng
* @date 2017-12-18
*/
public class ImageCodeGenerator {
public ImageCode generate(ServletWebRequest request) {
BufferedImage image = new BufferedImage(SecurityConstants.DEFAULT_IMAGE_WIDTH, SecurityConstants.DEFAULT_IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, SecurityConstants.DEFAULT_IMAGE_WIDTH, SecurityConstants.DEFAULT_IMAGE_HEIGHT);
g.setFont(new Font("Times New Roman", Font.ITALIC, 20));
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(SecurityConstants.DEFAULT_IMAGE_WIDTH);
int y = random.nextInt(SecurityConstants.DEFAULT_IMAGE_HEIGHT);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
String sRand = "";
for (int i = 0; i < SecurityConstants.DEFAULT_IMAGE_LENGTH; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 16);
}
g.dispose();
return new ImageCode(image, sRand, SecurityConstants.DEFAULT_IMAGE_EXPIRE);
}
/**
* 生成随机背景条纹
*
* @param fc
* @param bc
* @return
*/
private Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
}

View File

@ -1,18 +1,19 @@
package com.github.pig.admin.controller;
import com.github.pig.admin.common.util.ImageCodeGenerator;
import com.github.pig.admin.service.UserService;
import com.github.pig.common.constant.SecurityConstants;
import com.github.pig.common.vo.ImageCode;
import com.google.code.kaptcha.Producer;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.context.request.ServletWebRequest;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
/**
* @author lengleng
@ -20,6 +21,8 @@ import javax.servlet.http.HttpServletResponse;
*/
@Controller
public class ImageCodeController {
@Autowired
private Producer producer;
@Autowired
private UserService userService;
@ -34,8 +37,13 @@ public class ImageCodeController {
throws Exception {
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
ImageCode imageCode = new ImageCodeGenerator().generate(new ServletWebRequest(request));
userService.save(randomStr, imageCode);
ImageIO.write(imageCode.getImage(), "JPEG",response.getOutputStream());
//生成文字验证码
String text = producer.createText();
//生成图片验证码
BufferedImage image = producer.createImage(text);
userService.save(randomStr, text);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "JPEG", out);
IOUtils.closeQuietly(out);
}
}

View File

@ -44,19 +44,18 @@ public class UserController extends BaseController {
@Autowired
private UserService userService;
@Autowired
private SysUserRoleService sysUserRoleService;
@Autowired
private QiniuPropertiesConfig qiniuPropertiesConfig;
/**
* 获取当前用户信息角色权限
*
* @param userVo 当前用户信息
* @return 用户名
*/
@GetMapping("/info")
public R<UserInfo> user() {
return new R<>(userService.findUserInfo(getRole()));
public R<UserInfo> user(UserVo userVo) {
return new R<>(userService.findUserInfo(userVo));
}
/**
@ -74,22 +73,12 @@ public class UserController extends BaseController {
* 删除用户信息
*
* @param id ID
* @return boolean
* @return R
*/
@DeleteMapping("/{id}")
public Boolean userDel(@PathVariable Integer id) {
boolean delUserRole = sysUserRoleService.deleteByUserId(id);
if (delUserRole) {
boolean delUserInfo = userService.deleteById(id);
if (delUserInfo) {
userService.clearCache(UserUtils.getUserName());
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
} else {
return Boolean.FALSE;
}
public R<Boolean> userDel(@PathVariable Integer id) {
SysUser sysUser = userService.selectById(id);
return new R<>(userService.deleteUserById(sysUser));
}
/**
@ -99,7 +88,7 @@ public class UserController extends BaseController {
* @return success/false
*/
@PostMapping
public Boolean user(@RequestBody UserDto userDto) {
public R<Boolean> user(@RequestBody UserDto userDto) {
SysUser sysUser = new SysUser();
BeanUtils.copyProperties(userDto, sysUser);
sysUser.setDelFlag(CommonConstant.STATUS_NORMAL);
@ -108,28 +97,19 @@ public class UserController extends BaseController {
SysUserRole userRole = new SysUserRole();
userRole.setUserId(sysUser.getUserId());
userRole.setRoleId(userDto.getRole());
return userRole.insert();
return new R<>(userRole.insert());
}
/**
* 更新用户信息
*
* @param userDto 用户信息
* @return boolean
* @return R
*/
@PutMapping
public Boolean userUpdate(@RequestBody UserDto userDto) {
SysUser sysUser = new SysUser();
BeanUtils.copyProperties(userDto, sysUser);
sysUser.setUpdateTime(new Date());
userService.updateById(sysUser);
SysUserRole condition = new SysUserRole();
condition.setUserId(userDto.getUserId());
SysUserRole sysUserRole = sysUserRoleService.selectOne(new EntityWrapper<>(condition));
sysUserRole.setRoleId(userDto.getRole());
userService.clearCache(UserUtils.getUserName());
return sysUserRoleService.update(sysUserRole, new EntityWrapper<>(condition));
public R<Boolean> userUpdate(@RequestBody UserDto userDto) {
SysUser user = userService.selectById(userDto.getUserId());
return new R<>(userService.updateUser(userDto, user.getUsername()));
}
/**
@ -158,12 +138,11 @@ public class UserController extends BaseController {
* 上传用户头像
* (多机部署有问题建议使用独立的文件服务器)
*
* @param file 资源
* @param request request
* @param file 资源
* @return filename map
*/
@PostMapping("/upload")
public Map<String, String> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
public Map<String, String> upload(@RequestParam("file") MultipartFile file) {
String fileExt = FileUtil.extName(file.getOriginalFilename());
Configuration cfg = new Configuration(Zone.zone0());
UploadManager uploadManager = new UploadManager(cfg);
@ -185,23 +164,12 @@ public class UserController extends BaseController {
* 修改个人信息
*
* @param userDto userDto
* @param userVo 登录用户信息
* @return success/false
*/
@PutMapping("/editInfo")
public Boolean editInfo(@RequestBody UserDto userDto) {
String username = UserUtils.getUserName();
UserVo userVo = userService.findUserByUsername(username);
if (!ENCODER.matches(userDto.getPassword(), userVo.getPassword())) {
return Boolean.FALSE;
}
SysUser sysUser = new SysUser();
sysUser.setUserId(userVo.getUserId());
sysUser.setPassword(ENCODER.encode(userDto.getNewpassword1()));
sysUser.setAvatar(userDto.getAvatar());
userService.clearCache(UserUtils.getUserName());
return userService.updateById(sysUser);
public R<Boolean> editInfo(@RequestBody UserDto userDto, UserVo userVo) {
return new R<>(userService.updateUserInfo(userDto, userVo.getUsername()));
}
}

View File

@ -28,8 +28,9 @@ public interface SysUserMapper extends BaseMapper<SysUser> {
/**
* 分页查询用户信息含角色
*
* @param query 查询条件
* @return
* @param query 查询条件
* @param params 参数
* @return list
*/
List selectUserVoPage(Query query, Map<String,Object> params);
List selectUserVoPage(Query query, Map<String, Object> params);
}

View File

@ -2,14 +2,11 @@ package com.github.pig.admin.service;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;
import com.github.pig.admin.dto.UserDto;
import com.github.pig.admin.dto.UserInfo;
import com.github.pig.admin.entity.SysUser;
import com.github.pig.common.util.Query;
import com.github.pig.common.vo.ImageCode;
import com.github.pig.common.vo.UserVo;
import org.springframework.web.context.request.ServletWebRequest;
import java.util.List;
/**
* @author lengleng
@ -32,26 +29,40 @@ public interface UserService extends IService<SysUser> {
*/
Page selectWithRolePage(Query query);
/**
* 清除用户缓存
*
* @param userName 用户名
*/
void clearCache(String userName);
/**
* 查询用户信息
*
* @param roleNames 角色名
* @param userVo 角色名
* @return userInfo
*/
UserInfo findUserInfo(List<String> roleNames);
UserInfo findUserInfo(UserVo userVo);
/**
* 保存验证码
*
* @param randomStr 随机串
* @param imageCode 验证码
* @param randomStr 随机串
* @param imageCode 验证码*/
void save(String randomStr, String imageCode);
/**
* 删除用户
* @param sysUser 用户
* @return boolean
*/
void save(String randomStr, ImageCode imageCode);
Boolean deleteUserById(SysUser sysUser);
/**
* 更新当前用户基本信息
* @param userDto 用户信息
* @param username 用户名
* @return Boolean
*/
Boolean updateUserInfo(UserDto userDto, String username);
/**
* 更新指定用户信息
* @param userDto 用户信息
* @param username 用户信息
* @return
*/
Boolean updateUser(UserDto userDto, String username);
}

View File

@ -1,19 +0,0 @@
package com.github.pig.admin.service.impl;
import com.github.pig.common.constant.SecurityConstants;
import com.github.pig.common.vo.ImageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;
import javax.imageio.ImageIO;
/**
* @author lengleng
* @date 2017/12/18
*/
@Component("imageCodeService")
public class ImageCodeServiceImpl {
}

View File

@ -3,24 +3,29 @@ package com.github.pig.admin.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pig.admin.dto.UserDto;
import com.github.pig.admin.dto.UserInfo;
import com.github.pig.admin.entity.SysUser;
import com.github.pig.admin.entity.SysUserRole;
import com.github.pig.admin.mapper.SysUserMapper;
import com.github.pig.admin.service.SysMenuService;
import com.github.pig.admin.service.SysUserRoleService;
import com.github.pig.admin.service.UserService;
import com.github.pig.common.constant.SecurityConstants;
import com.github.pig.common.util.Query;
import com.github.pig.common.util.UserUtils;
import com.github.pig.common.vo.ImageCode;
import com.github.pig.common.vo.SysRole;
import com.github.pig.common.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.ServletWebRequest;
import javax.imageio.ImageIO;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
@ -30,22 +35,30 @@ import java.util.concurrent.TimeUnit;
*/
@Service
public class UserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements UserService {
private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();
@Autowired
private SysMenuService sysMenuService;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private SysUserMapper sysUserMapper;
@Autowired
private SysUserRoleService sysUserRoleService;
@Override
public UserInfo findUserInfo(List<String> roleNames) {
public UserInfo findUserInfo(UserVo userVo) {
SysUser condition = new SysUser();
condition.setUsername(UserUtils.getUserName());
condition.setUsername(userVo.getUsername());
SysUser sysUser = this.selectOne(new EntityWrapper<>(condition));
UserInfo userInfo = new UserInfo();
userInfo.setSysUser(sysUser);
//设置角色列表
List<SysRole> roleList = userVo.getRoleList();
List<String> roleNames = new ArrayList<>();
for (SysRole sysRole:roleList){
roleNames.add(sysRole.getRoleName());
}
String[] roles = roleNames.toArray(new String[roleNames.size()]);
userInfo.setRoles(roles);
//设置权限列表menu.permission
@ -62,16 +75,10 @@ public class UserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impleme
@Override
public Page selectWithRolePage(Query query) {
query.setRecords(sysUserMapper.selectUserVoPage(query,query.getCondition()));
query.setRecords(sysUserMapper.selectUserVoPage(query, query.getCondition()));
return query;
}
@Override
@CacheEvict(value = "user_details", key = "#username")
public void clearCache(String username) {
}
/**
* 保存用户验证码和randomStr绑定
*
@ -79,7 +86,51 @@ public class UserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impleme
* @param imageCode 验证码信息
*/
@Override
public void save(String randomStr, ImageCode imageCode) {
redisTemplate.opsForValue().set(SecurityConstants.DEFAULT_CODE_KEY + randomStr,imageCode.getCode(),SecurityConstants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS);
public void save(String randomStr, String imageCode) {
redisTemplate.opsForValue().set(SecurityConstants.DEFAULT_CODE_KEY + randomStr, imageCode, SecurityConstants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS);
}
/**
* 删除用户
*
* @param sysUser 用户
* @return Boolean
*/
@Override
@CacheEvict(value = "user_details", key = "#sysUser.username")
public Boolean deleteUserById(SysUser sysUser) {
sysUserRoleService.deleteByUserId(sysUser.getUserId());
this.deleteById(sysUser.getUserId());
return Boolean.TRUE;
}
@Override
@CacheEvict(value = "user_details", key = "#username")
public Boolean updateUserInfo(UserDto userDto, String username) {
UserVo userVo = this.findUserByUsername(username);
if (!ENCODER.matches(userDto.getPassword(), userVo.getPassword())) {
return Boolean.FALSE;
}
SysUser sysUser = new SysUser();
sysUser.setUserId(userVo.getUserId());
sysUser.setPassword(ENCODER.encode(userDto.getNewpassword1()));
sysUser.setAvatar(userDto.getAvatar());
return this.updateById(sysUser);
}
@Override
@CacheEvict(value = "user_details", key = "#username")
public Boolean updateUser(UserDto userDto, String username) {
SysUser sysUser = new SysUser();
BeanUtils.copyProperties(userDto, sysUser);
sysUser.setUpdateTime(new Date());
this.updateById(sysUser);
SysUserRole condition = new SysUserRole();
condition.setUserId(userDto.getUserId());
SysUserRole sysUserRole = sysUserRoleService.selectOne(new EntityWrapper<>(condition));
sysUserRole.setRoleId(userDto.getRole());
return sysUserRoleService.update(sysUserRole, new EntityWrapper<>(condition));
}
}

View File

@ -1,6 +1,7 @@
package com.github.pig.auth.config;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.constant.SecurityConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -42,12 +43,12 @@ public class PigAuthorizationConfig extends AuthorizationServerConfigurerAdapter
clients.inMemory()
.withClient(authServerConfig.getClientId())
.secret(authServerConfig.getClientSecret())
.authorizedGrantTypes("refresh_token", "password")
.authorizedGrantTypes(SecurityConstants.REFRESH_TOKEN, SecurityConstants.PASSWORD)
.scopes(authServerConfig.getScope());
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints
.tokenStore(new RedisTokenStore(redisConnectionFactory))
.accessTokenConverter(jwtAccessTokenConverter())

View File

@ -1,7 +1,7 @@
package com.github.pig.auth.serivce;
import com.github.pig.auth.feign.UserService;
import com.github.pig.auth.util.UserInfo;
import com.github.pig.auth.util.UserDetailsImpl;
import com.github.pig.common.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
@ -21,8 +21,8 @@ public class UserDetailServiceImpl implements UserDetailsService, Serializable {
private UserService userService;
@Override
public UserInfo loadUserByUsername(String username) throws UsernameNotFoundException {
public UserDetailsImpl loadUserByUsername(String username) throws UsernameNotFoundException {
UserVo userVo = userService.findUserByUsername(username);
return new UserInfo(userVo);
return new UserDetailsImpl(userVo);
}
}

View File

@ -1,6 +1,7 @@
package com.github.pig.common.bean.config;
import com.github.pig.common.bean.resolver.TokenArgumentResolver;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@ -11,10 +12,10 @@ import java.util.List;
* @date 2017/12/21
* mvc配置
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
super.addArgumentResolvers(argumentResolvers);
argumentResolvers.add(new TokenArgumentResolver());
}
}

View File

@ -5,6 +5,19 @@ package com.github.pig.common.constant;
* @date 2017-12-18
*/
public interface SecurityConstants {
/**
* 密码模式
*/
String PASSWORD = "password";
/**
* 刷新token
*/
String REFRESH_TOKEN = "refresh_token";
/**
* oauth token
*/
String OAUTH_TOKEN_URL = "/oauth/token";
/**
* 默认的处理验证码的url前缀
@ -14,26 +27,42 @@ public interface SecurityConstants {
/**
* 默认生成图形验证码宽度
*/
int DEFAULT_IMAGE_WIDTH = 67;
String DEFAULT_IMAGE_WIDTH = "150";
/**
* 默认生成图像验证码高度
*/
int DEFAULT_IMAGE_HEIGHT = 23;
String DEFAULT_IMAGE_HEIGHT = "32";
/**
* 默认生成图形验证码长度
*/
int DEFAULT_IMAGE_LENGTH = 4;
String DEFAULT_IMAGE_LENGTH = "4";
/**
* 默认生成图形验证码过期时间
*/
int DEFAULT_IMAGE_EXPIRE = 60;
/**
* 边框颜色合法值 r,g,b (and optional alpha) 或者 white,black,blue.
*/
String DEFAULT_COLOR_FONT = "black";
/**
* 图片边框
*/
String DEFAULT_IMAGE_BORDER = "no";
/**
* 默认图片间隔
*/
String DEFAULT_CHAR_SPACE = "5";
/**
* 默认保存code的前缀
*/
String DEFAULT_CODE_KEY = "DEFAULT_CODE_KEY";
/**
* 验证码文字大小
*/
String DEFAULT_IMAGE_FONT_SIZE = "30";
}

View File

@ -14,7 +14,7 @@ import java.util.Set;
* @email sunlightcs@gmail.com
* @date 2017-03-23 15:50
*/
public abstract class Assert {
public class Assert {
private static Validator validator;
static {

View File

@ -6,6 +6,7 @@ import java.io.Serializable;
* 响应信息主体
*
* @param <T>
* @author lengleng
*/
public class R<T> implements Serializable {

View File

@ -19,7 +19,7 @@ import java.util.List;
*/
public class UserUtils {
private static Logger logger = LoggerFactory.getLogger(UserUtils.class);
private static final ThreadLocal<String> TL_User = new ThreadLocal<>();
private static final ThreadLocal<String> THREAD_LOCAL_USER = new ThreadLocal<>();
private static final String KEY_USER = "user";
@ -92,7 +92,7 @@ public class UserUtils {
* @param username
*/
public static void setUser(String username) {
TL_User.set(username);
THREAD_LOCAL_USER.set(username);
MDC.put(KEY_USER, username);
}
@ -103,11 +103,11 @@ public class UserUtils {
* @return
*/
public static String getUserName() {
return TL_User.get();
return THREAD_LOCAL_USER.get();
}
public static void clearAllUserInfo() {
TL_User.remove();
THREAD_LOCAL_USER.remove();
MDC.remove(KEY_USER);
}
}

View File

@ -1,26 +1,30 @@
package com.github.pig.common.util.exception;
/**
* @author lengleng
* @date 😴2017年12月21日20:44:38
*/
public class CheckException extends RuntimeException {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public CheckException() {
}
public CheckException() {
}
public CheckException(String message) {
super(message);
}
public CheckException(String message) {
super(message);
}
public CheckException(Throwable cause) {
super(cause);
}
public CheckException(Throwable cause) {
super(cause);
}
public CheckException(String message, Throwable cause) {
super(message, cause);
}
public CheckException(String message, Throwable cause) {
super(message, cause);
}
public CheckException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public CheckException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@ -1,26 +1,30 @@
package com.github.pig.common.util.exception;
/**
* @author lengleng
* @date 2017年12月21日20:45:10
*/
public class UnloginException extends RuntimeException {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public UnloginException() {
}
public UnloginException() {
}
public UnloginException(String message) {
super(message);
}
public UnloginException(String message) {
super(message);
}
public UnloginException(Throwable cause) {
super(cause);
}
public UnloginException(Throwable cause) {
super(cause);
}
public UnloginException(String message, Throwable cause) {
super(message, cause);
}
public UnloginException(String message, Throwable cause) {
super(message, cause);
}
public UnloginException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public UnloginException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@ -1,5 +1,9 @@
package com.github.pig.common.util.exception;
/**
* @author lengleng
* @date 2017年12月21日20:45:38
*/
public class ValidateCodeException extends RuntimeException {
/**

View File

@ -30,18 +30,17 @@ import java.io.PrintWriter;
@Component("validateCodeFilter")
public class ValidateCodeFilter extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(ValidateCodeFilter.class);
@Value("${security.login.url}")
private String loginUrl;
@Autowired
private RedisTemplate redisTemplate;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (StringUtils.contains(request.getRequestURI(), loginUrl)) {
if (StringUtils.contains(request.getRequestURI(), SecurityConstants.OAUTH_TOKEN_URL) || StringUtils.contains(request.getRequestURI(), SecurityConstants.REFRESH_TOKEN)) {
PrintWriter printWriter = null;
try {
checkCode(request, response, filterChain);
} catch (ValidateCodeException e) {
logger.info("登录失败:{}", e.getMessage());
response.setCharacterEncoding(CommonConstant.UTF8);
response.setContentType(CommonConstant.CONTENT_TYPE);
R<String> result = new R<>(e.getMessage());