Skip to content

Commit

Permalink
修改代码规范,if for try空格添加,代码更美观
Browse files Browse the repository at this point in the history
  • Loading branch information
dolyw committed Dec 25, 2018
1 parent 00ce41a commit 3543c26
Show file tree
Hide file tree
Showing 13 changed files with 89 additions and 89 deletions.
4 changes: 2 additions & 2 deletions src/main/java/com/wang/config/ExceptionAdvice.java
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,11 @@ private HttpStatus getStatus(HttpServletRequest request) {
* @param fieldErrors
* @return
*/
private Map<String, Object> getValidError(List<FieldError> fieldErrors){
private Map<String, Object> getValidError(List<FieldError> fieldErrors) {
Map<String, Object> result = new HashMap<String, Object>(16);
List<String> errorList = new ArrayList<String>();
StringBuffer errorMsg = new StringBuffer("校验异常(ValidException):");
for (FieldError error : fieldErrors){
for (FieldError error : fieldErrors) {
errorList.add(error.getField() + "-" + error.getDefaultMessage());
errorMsg.append(error.getField() + "-" + error.getDefaultMessage() + ".");
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/wang/config/redis/JedisConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public class JedisConfig {
private int minIdle;

@Bean
public JedisPool redisPoolFactory(){
public JedisPool redisPoolFactory() {
try {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/wang/config/shiro/UserRealm.java
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,11 @@ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) t
throw new AuthenticationException("该帐号不存在(The account does not exist.)");
}
// 开始认证,要AccessToken认证通过,且Redis中存在RefreshToken,且两个Token时间戳一致
if(JwtUtil.verify(token) && JedisUtil.exists(Constant.PREFIX_SHIRO_REFRESH_TOKEN + account)){
if (JwtUtil.verify(token) && JedisUtil.exists(Constant.PREFIX_SHIRO_REFRESH_TOKEN + account)) {
// 获取RefreshToken的时间戳
String currentTimeMillisRedis = JedisUtil.getObject(Constant.PREFIX_SHIRO_REFRESH_TOKEN + account).toString();
// 获取AccessToken时间戳,与RefreshToken的时间戳对比
if(JwtUtil.getClaim(token, Constant.CURRENT_TIME_MILLIS).equals(currentTimeMillisRedis)){
if (JwtUtil.getClaim(token, Constant.CURRENT_TIME_MILLIS).equals(currentTimeMillisRedis)) {
return new SimpleAuthenticationInfo(token, token, "userRealm");
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/wang/config/shiro/cache/CustomCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class CustomCache<K,V> implements Cache<K,V> {
* @author Wang926454
* @date 2018/9/4 18:33
*/
private String getKey(Object key){
private String getKey(Object key) {
return Constant.PREFIX_SHIRO_CACHE + JwtUtil.getClaim(key.toString(), Constant.ACCOUNT);
}

Expand Down
16 changes: 8 additions & 8 deletions src/main/java/com/wang/config/shiro/jwt/JwtFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,19 +54,19 @@ protected boolean isAccessAllowed(ServletRequest request, ServletResponse respon
String msg = e.getMessage();
// 获取应用异常(该Cause是导致抛出此throwable(异常)的throwable(异常))
Throwable throwable = e.getCause();
if(throwable != null && throwable instanceof SignatureVerificationException ){
if (throwable != null && throwable instanceof SignatureVerificationException) {
// 该异常为JWT的AccessToken认证失败(Token或者密钥不正确)
msg = "Token或者密钥不正确(" + throwable.getMessage() + ")";
} else if(throwable != null && throwable instanceof TokenExpiredException){
} else if (throwable != null && throwable instanceof TokenExpiredException) {
// 该异常为JWT的AccessToken已过期,判断RefreshToken未过期就进行AccessToken刷新
if(this.refreshToken(request, response)){
if (this.refreshToken(request, response)) {
return true;
}else{
} else {
msg = "Token已过期(" + throwable.getMessage() + ")";
}
} else{
} else {
// 应用异常不为空
if(throwable != null) {
if (throwable != null) {
// 获取应用异常msg
msg = throwable.getMessage();
}
Expand Down Expand Up @@ -128,11 +128,11 @@ private boolean refreshToken(ServletRequest request, ServletResponse response) {
// 获取当前Token的帐号信息
String account = JwtUtil.getClaim(token, Constant.ACCOUNT);
// 判断Redis中RefreshToken是否存在
if(JedisUtil.exists(Constant.PREFIX_SHIRO_REFRESH_TOKEN + account)){
if (JedisUtil.exists(Constant.PREFIX_SHIRO_REFRESH_TOKEN + account)) {
// Redis中RefreshToken还存在,获取RefreshToken的时间戳
String currentTimeMillisRedis = JedisUtil.getObject(Constant.PREFIX_SHIRO_REFRESH_TOKEN + account).toString();
// 获取当前AccessToken中的时间戳,与RefreshToken的时间戳对比,如果当前时间戳一致,进行AccessToken刷新
if(JwtUtil.getClaim(token, Constant.CURRENT_TIME_MILLIS).equals(currentTimeMillisRedis)){
if (JwtUtil.getClaim(token, Constant.CURRENT_TIME_MILLIS).equals(currentTimeMillisRedis)) {
// 获取当前最新时间戳
String currentTimeMillis = String.valueOf(System.currentTimeMillis());
// 读取配置文件,获取refreshTokenExpireTime属性
Expand Down
46 changes: 23 additions & 23 deletions src/main/java/com/wang/controller/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,15 @@ public UserController(IUserService userService) {
*/
@GetMapping
@RequiresPermissions(logical = Logical.AND, value = {"user:view"})
public ResponseBean user(@Validated BaseDto baseDto){
if(baseDto.getPage() == null || baseDto.getRows() == null){
public ResponseBean user(@Validated BaseDto baseDto) {
if (baseDto.getPage() == null || baseDto.getRows() == null) {
baseDto.setPage(1);
baseDto.setRows(10);
}
PageHelper.startPage(baseDto.getPage(), baseDto.getRows());
List<UserDto> userDtos = userService.selectAll();
PageInfo<UserDto> selectPage = new PageInfo<UserDto>(userDtos);
if(userDtos == null || userDtos.size() <= 0){
if (userDtos == null || userDtos.size() <= 0) {
throw new CustomException("查询失败(Query Failure)");
}
Map<String, Object> result = new HashMap<String, Object>(16);
Expand All @@ -88,12 +88,12 @@ public ResponseBean user(@Validated BaseDto baseDto){
*/
@GetMapping("/online")
@RequiresPermissions(logical = Logical.AND, value = {"user:view"})
public ResponseBean online(){
public ResponseBean online() {
List<Object> userDtos = new ArrayList<Object>();
// 查询所有Redis键
Set<String> keys = JedisUtil.keysS(Constant.PREFIX_SHIRO_REFRESH_TOKEN + "*");
for (String key : keys) {
if(JedisUtil.exists(key)){
if (JedisUtil.exists(key)) {
// 根据:分割key,获取最后一个字符(帐号)
String[] strArray = key.split(":");
UserDto userDto = new UserDto();
Expand All @@ -104,7 +104,7 @@ public ResponseBean online(){
userDtos.add(userDto);
}
}
if(userDtos == null || userDtos.size() <= 0){
if (userDtos == null || userDtos.size() <= 0) {
throw new CustomException("查询失败(Query Failure)");
}
return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", userDtos);
Expand All @@ -123,15 +123,15 @@ public ResponseBean login(@Validated(UserLoginValidGroup.class) @RequestBody Use
UserDto userDtoTemp = new UserDto();
userDtoTemp.setAccount(userDto.getAccount());
userDtoTemp = userService.selectOne(userDtoTemp);
if(userDtoTemp == null){
if (userDtoTemp == null) {
throw new CustomUnauthorizedException("该帐号不存在(The account does not exist.)");
}
// 密码进行AES解密
String key = AesCipherUtil.deCrypto(userDtoTemp.getPassword());
// 因为密码加密是以帐号+密码的形式进行加密的,所以解密后的对比是帐号+密码
if (key.equals(userDto.getAccount() + userDto.getPassword())) {
// 清除可能存在的Shiro权限信息缓存
if(JedisUtil.exists(Constant.PREFIX_SHIRO_CACHE + userDto.getAccount())){
if (JedisUtil.exists(Constant.PREFIX_SHIRO_CACHE + userDto.getAccount())) {
JedisUtil.delKey(Constant.PREFIX_SHIRO_CACHE + userDto.getAccount());
}
// 设置RefreshToken,时间戳为当前时间戳,直接设置即可(不用先删后设,会覆盖已有的RefreshToken)
Expand Down Expand Up @@ -187,9 +187,9 @@ public ResponseBean requireAuth() {
*/
@GetMapping("/{id}")
@RequiresPermissions(logical = Logical.AND, value = {"user:view"})
public ResponseBean findById(@PathVariable("id") Integer id){
public ResponseBean findById(@PathVariable("id") Integer id) {
UserDto userDto = userService.selectByPrimaryKey(id);
if(userDto == null){
if (userDto == null) {
throw new CustomException("查询失败(Query Failure)");
}
return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", userDto);
Expand All @@ -209,18 +209,18 @@ public ResponseBean add(@Validated(UserEditValidGroup.class) @RequestBody UserDt
UserDto userDtoTemp = new UserDto();
userDtoTemp.setAccount(userDto.getAccount());
userDtoTemp = userService.selectOne(userDtoTemp);
if(userDtoTemp != null && StringUtil.isNotBlank(userDtoTemp.getPassword())){
if (userDtoTemp != null && StringUtil.isNotBlank(userDtoTemp.getPassword())) {
throw new CustomUnauthorizedException("该帐号已存在(Account exist.)");
}
userDto.setRegTime(new Date());
// 密码以帐号+密码的形式进行AES加密
if(userDto.getPassword().length() > Constant.PASSWORD_MAX_LEN){
if (userDto.getPassword().length() > Constant.PASSWORD_MAX_LEN) {
throw new CustomException("密码最多8位(Password up to 8 bits.)");
}
String key = AesCipherUtil.enCrypto(userDto.getAccount() + userDto.getPassword());
userDto.setPassword(key);
int count = userService.insert(userDto);
if(count <= 0){
if (count <= 0) {
throw new CustomException("新增失败(Insert Failure)");
}
return new ResponseBean(HttpStatus.OK.value(), "新增成功(Insert Success)", userDto);
Expand All @@ -240,22 +240,22 @@ public ResponseBean update(@Validated(UserEditValidGroup.class) @RequestBody Use
UserDto userDtoTemp = new UserDto();
userDtoTemp.setAccount(userDto.getAccount());
userDtoTemp = userService.selectOne(userDtoTemp);
if(userDtoTemp == null){
if (userDtoTemp == null) {
throw new CustomUnauthorizedException("该帐号不存在(Account not exist.)");
}else{
} else {
userDto.setId(userDtoTemp.getId());
}
// FIXME: 如果不一样就说明用户修改了密码,重新加密密码(这个处理不太好,但是没有想到好的处理方式)
if(!userDtoTemp.getPassword().equals(userDto.getPassword())){
if (!userDtoTemp.getPassword().equals(userDto.getPassword())) {
// 密码以帐号+密码的形式进行AES加密
if(userDto.getPassword().length() > Constant.PASSWORD_MAX_LEN){
if (userDto.getPassword().length() > Constant.PASSWORD_MAX_LEN) {
throw new CustomException("密码最多8位(Password up to 8 bits.)");
}
String key = AesCipherUtil.enCrypto(userDto.getAccount() + userDto.getPassword());
userDto.setPassword(key);
}
int count = userService.updateByPrimaryKeySelective(userDto);
if(count <= 0){
if (count <= 0) {
throw new CustomException("更新失败(Update Failure)");
}
return new ResponseBean(HttpStatus.OK.value(), "更新成功(Update Success)", userDto);
Expand All @@ -270,9 +270,9 @@ public ResponseBean update(@Validated(UserEditValidGroup.class) @RequestBody Use
*/
@DeleteMapping("/{id}")
@RequiresPermissions(logical = Logical.AND, value = {"user:edit"})
public ResponseBean delete(@PathVariable("id") Integer id){
public ResponseBean delete(@PathVariable("id") Integer id) {
int count = userService.deleteByPrimaryKey(id);
if(count <= 0){
if (count <= 0) {
throw new CustomException("删除失败,ID不存在(Deletion Failed. ID does not exist.)");
}
return new ResponseBean(HttpStatus.OK.value(), "删除成功(Delete Success)", null);
Expand All @@ -287,10 +287,10 @@ public ResponseBean delete(@PathVariable("id") Integer id){
*/
@DeleteMapping("/online/{id}")
@RequiresPermissions(logical = Logical.AND, value = {"user:edit"})
public ResponseBean deleteOnline(@PathVariable("id") Integer id){
public ResponseBean deleteOnline(@PathVariable("id") Integer id) {
UserDto userDto = userService.selectByPrimaryKey(id);
if(JedisUtil.exists(Constant.PREFIX_SHIRO_REFRESH_TOKEN + userDto.getAccount())){
if(JedisUtil.delKey(Constant.PREFIX_SHIRO_REFRESH_TOKEN + userDto.getAccount()) > 0){
if (JedisUtil.exists(Constant.PREFIX_SHIRO_REFRESH_TOKEN + userDto.getAccount())) {
if (JedisUtil.delKey(Constant.PREFIX_SHIRO_REFRESH_TOKEN + userDto.getAccount()) > 0) {
return new ResponseBean(HttpStatus.OK.value(), "剔除成功(Delete Success)", null);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/wang/service/IUserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
* @author Wang926454
* @date 2018/8/9 15:44
*/
public interface IUserService extends IBaseService<UserDto>{
public interface IUserService extends IBaseService<UserDto> {
}
28 changes: 14 additions & 14 deletions src/main/java/com/wang/util/AesCipherUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public void setEncryptAESKey(String encryptAESKey) {
* @date 2018/8/31 16:56
*/
public static String enCrypto(String str) {
try{
try {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
// 实例化支持AES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)
// KeyGenerator 提供对称密钥生成器的功能,支持各种算法
Expand All @@ -67,22 +67,22 @@ public static String enCrypto(String str) {
byte[] cipherByte = c.doFinal(src);
// 先将二进制转换成16进制,再返回Bsae64加密后的String
return Base64ConvertUtil.encode(HexConvertUtil.parseByte2HexStr(cipherByte));
} catch (NoSuchAlgorithmException e){
} catch (NoSuchAlgorithmException e) {
LOGGER.error("getInstance()方法异常:" + e.getMessage());
throw new CustomUnauthorizedException("getInstance()方法异常:" + e.getMessage());
} catch (UnsupportedEncodingException e){
} catch (UnsupportedEncodingException e) {
LOGGER.error("Bsae64加密异常:" + e.getMessage());
throw new CustomUnauthorizedException("Bsae64加密异常:" + e.getMessage());
} catch (NoSuchPaddingException e){
} catch (NoSuchPaddingException e) {
LOGGER.error("getInstance()方法异常:" + e.getMessage());
throw new CustomUnauthorizedException("getInstance()方法异常:" + e.getMessage());
} catch (InvalidKeyException e){
} catch (InvalidKeyException e) {
LOGGER.error("初始化Cipher对象异常:" + e.getMessage());
throw new CustomUnauthorizedException("初始化Cipher对象异常:" + e.getMessage());
} catch (IllegalBlockSizeException e){
} catch (IllegalBlockSizeException e) {
LOGGER.error("加密异常,密钥有误:" + e.getMessage());
throw new CustomUnauthorizedException("加密异常,密钥有误:" + e.getMessage());
} catch (BadPaddingException e){
} catch (BadPaddingException e) {
LOGGER.error("加密异常,密钥有误:" + e.getMessage());
throw new CustomUnauthorizedException("加密异常,密钥有误:" + e.getMessage());
}
Expand All @@ -96,7 +96,7 @@ public static String enCrypto(String str) {
* @date 2018/8/31 16:56
*/
public static String deCrypto(String str) {
try{
try {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
// 实例化支持AES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)
// KeyGenerator 提供对称密钥生成器的功能,支持各种算法
Expand All @@ -114,22 +114,22 @@ public static String deCrypto(String str) {
// 该字节数组负责保存加密的结果,先对str进行Bsae64解密,将16进制转换为二进制
byte[] cipherByte = c.doFinal(HexConvertUtil.parseHexStr2Byte(Base64ConvertUtil.decode(str)));
return new String(cipherByte);
} catch (NoSuchAlgorithmException e){
} catch (NoSuchAlgorithmException e) {
LOGGER.error("getInstance()方法异常:" + e.getMessage());
throw new CustomUnauthorizedException("getInstance()方法异常:" + e.getMessage());
} catch (UnsupportedEncodingException e){
} catch (UnsupportedEncodingException e) {
LOGGER.error("Bsae64加密异常:" + e.getMessage());
throw new CustomUnauthorizedException("Bsae64加密异常:" + e.getMessage());
} catch (NoSuchPaddingException e){
} catch (NoSuchPaddingException e) {
LOGGER.error("getInstance()方法异常:" + e.getMessage());
throw new CustomUnauthorizedException("getInstance()方法异常:" + e.getMessage());
} catch (InvalidKeyException e){
} catch (InvalidKeyException e) {
LOGGER.error("初始化Cipher对象异常:" + e.getMessage());
throw new CustomUnauthorizedException("初始化Cipher对象异常:" + e.getMessage());
} catch (IllegalBlockSizeException e){
} catch (IllegalBlockSizeException e) {
LOGGER.error("解密异常,密钥有误:" + e.getMessage());
throw new CustomUnauthorizedException("解密异常,密钥有误:" + e.getMessage());
} catch (BadPaddingException e){
} catch (BadPaddingException e) {
LOGGER.error("解密异常,密钥有误:" + e.getMessage());
throw new CustomUnauthorizedException("解密异常,密钥有误:" + e.getMessage());
}
Expand Down
Loading

0 comments on commit 3543c26

Please sign in to comment.