Skip to content
GitLab
Menu
Projects
Groups
Snippets
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
Menu
Open sidebar
jinli gu
Eladmin
Commits
cf1e17c7
Commit
cf1e17c7
authored
Jun 29, 2020
by
dbdu
Browse files
Merge branch 'master' of
https://gitee.com/elunez/eladmin
parents
425f910f
3379f4a9
Changes
32
Hide whitespace changes
Inline
Side-by-side
eladmin-common/src/main/java/me/zhengjie/annotation/Query.java
View file @
cf1e17c7
...
@@ -80,8 +80,8 @@ public @interface Query {
...
@@ -80,8 +80,8 @@ public @interface Query {
* 适用于简单连接查询,复杂的请自定义该注解,或者使用sql查询
* 适用于简单连接查询,复杂的请自定义该注解,或者使用sql查询
*/
*/
enum
Join
{
enum
Join
{
/** jie 2019-6-4 13:18:30
左右连接
*/
/** jie 2019-6-4 13:18:30 */
LEFT
,
RIGHT
LEFT
,
RIGHT
,
INNER
}
}
}
}
...
...
eladmin-common/src/main/java/me/zhengjie/utils/CacheKey.java
0 → 100644
View file @
cf1e17c7
/*
* Copyright 2019-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package
me.zhengjie.utils
;
/**
* @author: liaojinlong
* @date: 2020/6/11 15:49
* @apiNote: 关于缓存的Key集合
*/
public
interface
CacheKey
{
/**
* 内置 用户、岗位、应用、菜单、角色 相关key
*/
String
USER_MODIFY_TIME_KEY
=
"user:modify:time:key:"
;
String
APP_MODIFY_TIME_KEY
=
"app:modify:time:key:"
;
String
JOB_MODIFY_TIME_KEY
=
"job:modify:time:key:"
;
String
MENU_MODIFY_TIME_KEY
=
"menu:modify:time:key:"
;
String
ROLE_MODIFY_TIME_KEY
=
"role:modify:time:key:"
;
String
DEPT_MODIFY_TIME_KEY
=
"dept:modify:time:key:"
;
/**
* 用户
*/
String
USER_ID
=
"user::id:"
;
String
USER_NAME
=
"user::username:"
;
/**
* 数据
*/
String
DATE_USER
=
"data::user:"
;
/**
* 菜单
*/
String
MENU_USER
=
"menu::user:"
;
/**
* 角色授权
*/
String
ROLE_AUTH
=
"role::auth:"
;
/**
* 角色信息
*/
String
ROLE_ID
=
"role::id:"
;
}
eladmin-common/src/main/java/me/zhengjie/utils/DateUtil.java
0 → 100644
View file @
cf1e17c7
/*
* Copyright 2019-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package
me.zhengjie.utils
;
import
java.time.*
;
import
java.time.format.DateTimeFormatter
;
import
java.util.Date
;
/**
* @author: liaojinlong
* @date: 2020/6/11 16:28
* @apiNote: JDK 8 新日期类 格式化与字符串转换 工具类
*/
public
class
DateUtil
{
public
static
final
DateTimeFormatter
DFY_MD_HMS
=
DateTimeFormatter
.
ofPattern
(
"yyyy-MM-dd HH:mm:ss"
);
public
static
final
DateTimeFormatter
DFY_MD
=
DateTimeFormatter
.
ofPattern
(
"yyyy-MM-dd"
);
/**
* LocalDateTime 转时间戳
*
* @param localDateTime /
* @return /
*/
public
static
Long
getTimeStamp
(
LocalDateTime
localDateTime
)
{
return
localDateTime
.
atZone
(
ZoneId
.
systemDefault
()).
toEpochSecond
();
}
/**
* 时间戳转LocalDateTime
*
* @param timeStamp /
* @return /
*/
public
static
LocalDateTime
fromTimeStamp
(
Long
timeStamp
)
{
return
LocalDateTime
.
ofEpochSecond
(
timeStamp
,
0
,
OffsetDateTime
.
now
().
getOffset
());
}
/**
* LocalDateTime 转 Date
* Jdk8 后 不推荐使用 {@link Date} Date
*
* @param localDateTime /
* @return /
*/
public
static
Date
toDate
(
LocalDateTime
localDateTime
)
{
return
Date
.
from
(
localDateTime
.
atZone
(
ZoneId
.
systemDefault
()).
toInstant
());
}
/**
* LocalDate 转 Date
* Jdk8 后 不推荐使用 {@link Date} Date
*
* @param localDate /
* @return /
*/
public
static
Date
toDate
(
LocalDate
localDate
)
{
return
toDate
(
localDate
.
atTime
(
LocalTime
.
now
(
ZoneId
.
systemDefault
())));
}
/**
* Date转 LocalDateTime
* Jdk8 后 不推荐使用 {@link Date} Date
*
* @param date /
* @return /
*/
public
static
LocalDateTime
toLocalDateTime
(
Date
date
)
{
return
LocalDateTime
.
ofInstant
(
date
.
toInstant
(),
ZoneId
.
systemDefault
());
}
/**
* 日期 格式化
*
* @param localDateTime /
* @param patten /
* @return /
*/
public
static
String
localDateTimeFormat
(
LocalDateTime
localDateTime
,
String
patten
)
{
DateTimeFormatter
df
=
DateTimeFormatter
.
ofPattern
(
patten
);
return
df
.
format
(
localDateTime
);
}
/**
* 日期 格式化
*
* @param localDateTime /
* @param df /
* @return /
*/
public
static
String
localDateTimeFormat
(
LocalDateTime
localDateTime
,
DateTimeFormatter
df
)
{
return
df
.
format
(
localDateTime
);
}
/**
* 日期格式化 yyyy-MM-dd HH:mm:ss
*
* @param localDateTime /
* @return /
*/
public
static
String
localDateTimeFormatyMdHms
(
LocalDateTime
localDateTime
)
{
return
DFY_MD_HMS
.
format
(
localDateTime
);
}
/**
* 日期格式化 yyyy-MM-dd
*
* @param localDateTime /
* @return /
*/
public
String
localDateTimeFormatyMd
(
LocalDateTime
localDateTime
)
{
return
DFY_MD
.
format
(
localDateTime
);
}
/**
* 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd
*
* @param localDateTime /
* @return /
*/
public
static
LocalDateTime
parseLocalDateTimeFormat
(
String
localDateTime
,
String
pattern
)
{
DateTimeFormatter
dateTimeFormatter
=
DateTimeFormatter
.
ofPattern
(
pattern
);
return
LocalDateTime
.
from
(
dateTimeFormatter
.
parse
(
localDateTime
));
}
/**
* 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd
*
* @param localDateTime /
* @return /
*/
public
static
LocalDateTime
parseLocalDateTimeFormat
(
String
localDateTime
,
DateTimeFormatter
dateTimeFormatter
)
{
return
LocalDateTime
.
from
(
dateTimeFormatter
.
parse
(
localDateTime
));
}
/**
* 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd HH:mm:ss
*
* @param localDateTime /
* @return /
*/
public
static
LocalDateTime
parseLocalDateTimeFormatyMdHms
(
String
localDateTime
)
{
return
LocalDateTime
.
from
(
DFY_MD_HMS
.
parse
(
localDateTime
));
}
}
eladmin-common/src/main/java/me/zhengjie/utils/EncryptUtils.java
View file @
cf1e17c7
...
@@ -61,7 +61,7 @@ public class EncryptUtils {
...
@@ -61,7 +61,7 @@ public class EncryptUtils {
* 对称解密
* 对称解密
*/
*/
public
static
String
desDecrypt
(
String
source
)
throws
Exception
{
public
static
String
desDecrypt
(
String
source
)
throws
Exception
{
byte
[]
src
=
hex2byte
(
source
.
getBytes
());
byte
[]
src
=
hex2byte
(
source
.
getBytes
(
StandardCharsets
.
UTF_8
));
DESKeySpec
desKeySpec
=
getDesKeySpec
(
source
);
DESKeySpec
desKeySpec
=
getDesKeySpec
(
source
);
SecretKeyFactory
keyFactory
=
SecretKeyFactory
.
getInstance
(
"DES"
);
SecretKeyFactory
keyFactory
=
SecretKeyFactory
.
getInstance
(
"DES"
);
SecretKey
secretKey
=
keyFactory
.
generateSecret
(
desKeySpec
);
SecretKey
secretKey
=
keyFactory
.
generateSecret
(
desKeySpec
);
...
...
eladmin-common/src/main/java/me/zhengjie/utils/QueryHelp.java
View file @
cf1e17c7
...
@@ -100,6 +100,13 @@ public class QueryHelp {
...
@@ -100,6 +100,13 @@ public class QueryHelp {
join
=
root
.
join
(
name
,
JoinType
.
RIGHT
);
join
=
root
.
join
(
name
,
JoinType
.
RIGHT
);
}
}
break
;
break
;
case
INNER:
if
(
ObjectUtil
.
isNotNull
(
join
)
&&
ObjectUtil
.
isNotNull
(
val
)){
join
=
join
.
join
(
name
,
JoinType
.
INNER
);
}
else
{
join
=
root
.
join
(
name
,
JoinType
.
INNER
);
}
break
;
default
:
break
;
default
:
break
;
}
}
}
}
...
...
eladmin-common/src/main/java/me/zhengjie/utils/RedisUtils.java
View file @
cf1e17c7
...
@@ -174,19 +174,19 @@ public class RedisUtils {
...
@@ -174,19 +174,19 @@ public class RedisUtils {
if
(
keys
!=
null
&&
keys
.
length
>
0
)
{
if
(
keys
!=
null
&&
keys
.
length
>
0
)
{
if
(
keys
.
length
==
1
)
{
if
(
keys
.
length
==
1
)
{
boolean
result
=
redisTemplate
.
delete
(
keys
[
0
]);
boolean
result
=
redisTemplate
.
delete
(
keys
[
0
]);
System
.
out
.
println
(
"--------------------------------------------"
);
log
.
debug
(
"--------------------------------------------"
);
System
.
out
.
println
(
new
StringBuilder
(
"删除缓存:"
).
append
(
keys
[
0
]).
append
(
",结果:"
).
append
(
result
));
log
.
debug
(
new
StringBuilder
(
"删除缓存:"
).
append
(
keys
[
0
]).
append
(
",结果:"
).
append
(
result
)
.
toString
()
);
System
.
out
.
println
(
"--------------------------------------------"
);
log
.
debug
(
"--------------------------------------------"
);
}
else
{
}
else
{
Set
<
Object
>
keySet
=
new
HashSet
<>();
Set
<
Object
>
keySet
=
new
HashSet
<>();
for
(
String
key
:
keys
)
{
for
(
String
key
:
keys
)
{
keySet
.
addAll
(
redisTemplate
.
keys
(
key
));
keySet
.
addAll
(
redisTemplate
.
keys
(
key
));
}
}
long
count
=
redisTemplate
.
delete
(
keySet
);
long
count
=
redisTemplate
.
delete
(
keySet
);
System
.
out
.
println
(
"--------------------------------------------"
);
log
.
debug
(
"--------------------------------------------"
);
System
.
out
.
println
(
"成功删除缓存:"
+
keySet
.
toString
());
log
.
debug
(
"成功删除缓存:"
+
keySet
.
toString
());
System
.
out
.
println
(
"缓存删除数量:"
+
count
+
"个"
);
log
.
debug
(
"缓存删除数量:"
+
count
+
"个"
);
System
.
out
.
println
(
"--------------------------------------------"
);
log
.
debug
(
"--------------------------------------------"
);
}
}
}
}
}
}
...
@@ -697,9 +697,9 @@ public class RedisUtils {
...
@@ -697,9 +697,9 @@ public class RedisUtils {
}
}
long
count
=
redisTemplate
.
delete
(
keys
);
long
count
=
redisTemplate
.
delete
(
keys
);
// 此处提示可自行删除
// 此处提示可自行删除
System
.
out
.
println
(
"--------------------------------------------"
);
log
.
debug
(
"--------------------------------------------"
);
System
.
out
.
println
(
"成功删除缓存:"
+
keys
.
toString
());
log
.
debug
(
"成功删除缓存:"
+
keys
.
toString
());
System
.
out
.
println
(
"缓存删除数量:"
+
count
+
"个"
);
log
.
debug
(
"缓存删除数量:"
+
count
+
"个"
);
System
.
out
.
println
(
"--------------------------------------------"
);
log
.
debug
(
"--------------------------------------------"
);
}
}
}
}
eladmin-common/src/main/java/me/zhengjie/utils/StringUtils.java
View file @
cf1e17c7
...
@@ -26,6 +26,7 @@ import org.lionsoul.ip2region.DbSearcher;
...
@@ -26,6 +26,7 @@ import org.lionsoul.ip2region.DbSearcher;
import
org.slf4j.Logger
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.core.io.ClassPathResource
;
import
org.springframework.core.io.ClassPathResource
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletRequest
;
import
java.io.File
;
import
java.io.File
;
import
java.net.InetAddress
;
import
java.net.InetAddress
;
...
@@ -41,7 +42,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
...
@@ -41,7 +42,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
private
static
final
Logger
log
=
LoggerFactory
.
getLogger
(
StringUtils
.
class
);
private
static
final
Logger
log
=
LoggerFactory
.
getLogger
(
StringUtils
.
class
);
private
static
boolean
ipLocal
=
false
;
private
static
boolean
ipLocal
=
false
;
private
static
DbSearcher
searcher
=
null
;
private
static
File
file
=
null
;
private
static
DbConfig
config
;
private
static
final
char
SEPARATOR
=
'_'
;
private
static
final
char
SEPARATOR
=
'_'
;
private
static
final
String
UNKNOWN
=
"unknown"
;
private
static
final
String
UNKNOWN
=
"unknown"
;
...
@@ -54,11 +56,9 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
...
@@ -54,11 +56,9 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
*/
*/
String
path
=
"ip2region/ip2region.db"
;
String
path
=
"ip2region/ip2region.db"
;
String
name
=
"ip2region.db"
;
String
name
=
"ip2region.db"
;
DbConfig
config
;
try
{
try
{
config
=
new
DbConfig
();
config
=
new
DbConfig
();
File
file
=
FileUtil
.
inputStreamToFile
(
new
ClassPathResource
(
path
).
getInputStream
(),
name
);
file
=
FileUtil
.
inputStreamToFile
(
new
ClassPathResource
(
path
).
getInputStream
(),
name
);
searcher
=
new
DbSearcher
(
config
,
file
.
getPath
());
}
catch
(
Exception
e
)
{
}
catch
(
Exception
e
)
{
log
.
error
(
e
.
getMessage
(),
e
);
log
.
error
(
e
.
getMessage
(),
e
);
}
}
...
@@ -206,9 +206,10 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
...
@@ -206,9 +206,10 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
*/
*/
public
static
String
getLocalCityInfo
(
String
ip
)
{
public
static
String
getLocalCityInfo
(
String
ip
)
{
try
{
try
{
DataBlock
dataBlock
;
DataBlock
dataBlock
=
new
DbSearcher
(
config
,
file
.
getPath
())
dataBlock
=
searcher
.
binarySearch
(
ip
);
.
binarySearch
(
ip
);
String
address
=
dataBlock
.
getRegion
().
replace
(
"0|"
,
""
);
String
region
=
dataBlock
.
getRegion
();
String
address
=
region
.
replace
(
"0|"
,
""
);
char
symbol
=
'|'
;
char
symbol
=
'|'
;
if
(
address
.
charAt
(
address
.
length
()
-
1
)
==
symbol
)
{
if
(
address
.
charAt
(
address
.
length
()
-
1
)
==
symbol
)
{
address
=
address
.
substring
(
0
,
address
.
length
()
-
1
);
address
=
address
.
substring
(
0
,
address
.
length
()
-
1
);
...
...
eladmin-common/src/test/java/me/zhengjie/utils/DateUtilsTest.java
0 → 100644
View file @
cf1e17c7
package
me.zhengjie.utils
;
import
org.junit.Test
;
import
java.time.LocalDateTime
;
import
java.util.Date
;
public
class
DateUtilsTest
{
@Test
public
void
test1
()
{
long
l
=
System
.
currentTimeMillis
()
/
1000
;
LocalDateTime
localDateTime
=
DateUtil
.
fromTimeStamp
(
l
);
System
.
out
.
printf
(
DateUtil
.
localDateTimeFormatyMdHms
(
localDateTime
));
}
@Test
public
void
test2
()
{
LocalDateTime
now
=
LocalDateTime
.
now
();
System
.
out
.
println
(
DateUtil
.
localDateTimeFormatyMdHms
(
now
));
Date
date
=
DateUtil
.
toDate
(
now
);
LocalDateTime
localDateTime
=
DateUtil
.
toLocalDateTime
(
date
);
System
.
out
.
println
(
DateUtil
.
localDateTimeFormatyMdHms
(
localDateTime
));
LocalDateTime
localDateTime1
=
DateUtil
.
fromTimeStamp
(
date
.
getTime
()
/
1000
);
System
.
out
.
println
(
DateUtil
.
localDateTimeFormatyMdHms
(
localDateTime1
));
}
}
eladmin-logging/src/main/java/me/zhengjie/annotation/Log.java
View file @
cf1e17c7
...
@@ -15,6 +15,8 @@
...
@@ -15,6 +15,8 @@
*/
*/
package
me.zhengjie.annotation
;
package
me.zhengjie.annotation
;
import
me.zhengjie.annotation.type.LogActionType
;
import
java.lang.annotation.ElementType
;
import
java.lang.annotation.ElementType
;
import
java.lang.annotation.Retention
;
import
java.lang.annotation.Retention
;
import
java.lang.annotation.RetentionPolicy
;
import
java.lang.annotation.RetentionPolicy
;
...
@@ -27,5 +29,14 @@ import java.lang.annotation.Target;
...
@@ -27,5 +29,14 @@ import java.lang.annotation.Target;
@Target
(
ElementType
.
METHOD
)
@Target
(
ElementType
.
METHOD
)
@Retention
(
RetentionPolicy
.
RUNTIME
)
@Retention
(
RetentionPolicy
.
RUNTIME
)
public
@interface
Log
{
public
@interface
Log
{
String
value
()
default
""
;
String
value
()
default
""
;
/**
* 是否启用
*
* @return
*/
boolean
enable
()
default
true
;
LogActionType
type
()
default
LogActionType
.
SELECT
;
}
}
eladmin-logging/src/main/java/me/zhengjie/annotation/type/LogActionType.java
0 → 100644
View file @
cf1e17c7
/*
* Copyright 2019-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package
me.zhengjie.annotation.type
;
/**
* @author: liaojinlong
* @date: 2020/6/11 19:47
* @apiNote: 日志类型
*/
public
enum
LogActionType
{
/**
* 增删改查
*/
ADD
(
"新增"
),
SELECT
(
"查询"
),
UPDATE
(
"更新"
),
DELETE
(
"删除"
);
private
String
value
;
LogActionType
(
String
value
)
{
this
.
value
=
value
;
}
public
String
getValue
()
{
return
value
;
}
public
void
setValue
(
String
value
)
{
this
.
value
=
value
;
}
}
eladmin-system/src/main/java/me/zhengjie/modules/quartz/config/JobRunner.java
View file @
cf1e17c7
...
@@ -19,9 +19,12 @@ import lombok.RequiredArgsConstructor;
...
@@ -19,9 +19,12 @@ import lombok.RequiredArgsConstructor;
import
me.zhengjie.modules.quartz.domain.QuartzJob
;
import
me.zhengjie.modules.quartz.domain.QuartzJob
;
import
me.zhengjie.modules.quartz.repository.QuartzJobRepository
;
import
me.zhengjie.modules.quartz.repository.QuartzJobRepository
;
import
me.zhengjie.modules.quartz.utils.QuartzManage
;
import
me.zhengjie.modules.quartz.utils.QuartzManage
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.boot.ApplicationArguments
;
import
org.springframework.boot.ApplicationArguments
;
import
org.springframework.boot.ApplicationRunner
;
import
org.springframework.boot.ApplicationRunner
;
import
org.springframework.stereotype.Component
;
import
org.springframework.stereotype.Component
;
import
java.util.List
;
import
java.util.List
;
/**
/**
...
@@ -31,19 +34,20 @@ import java.util.List;
...
@@ -31,19 +34,20 @@ import java.util.List;
@Component
@Component
@RequiredArgsConstructor
@RequiredArgsConstructor
public
class
JobRunner
implements
ApplicationRunner
{
public
class
JobRunner
implements
ApplicationRunner
{
private
static
final
Logger
log
=
LoggerFactory
.
getLogger
(
JobRunner
.
class
);
private
final
QuartzJobRepository
quartzJobRepository
;
private
final
QuartzJobRepository
quartzJobRepository
;
private
final
QuartzManage
quartzManage
;
private
final
QuartzManage
quartzManage
;
/**
/**
* 项目启动时重新激活启用的定时任务
* 项目启动时重新激活启用的定时任务
*
* @param applicationArguments /
* @param applicationArguments /
*/
*/
@Override
@Override
public
void
run
(
ApplicationArguments
applicationArguments
){
public
void
run
(
ApplicationArguments
applicationArguments
)
{
System
.
out
.
println
(
"--------------------注入定时任务---------------------"
);
log
.
info
(
"--------------------注入定时任务---------------------"
);
List
<
QuartzJob
>
quartzJobs
=
quartzJobRepository
.
findByIsPauseIsFalse
();
List
<
QuartzJob
>
quartzJobs
=
quartzJobRepository
.
findByIsPauseIsFalse
();
quartzJobs
.
forEach
(
quartzManage:
:
addJob
);
quartzJobs
.
forEach
(
quartzManage:
:
addJob
);
System
.
out
.
println
(
"--------------------定时任务注入完成---------------------"
);
log
.
info
(
"--------------------定时任务注入完成---------------------"
);
}
}
}
}
eladmin-system/src/main/java/me/zhengjie/modules/quartz/utils/ExecutionJob.java
View file @
cf1e17c7
...
@@ -28,6 +28,7 @@ import me.zhengjie.modules.quartz.service.QuartzJobService;
...
@@ -28,6 +28,7 @@ import me.zhengjie.modules.quartz.service.QuartzJobService;
import
me.zhengjie.service.EmailService
;
import
me.zhengjie.service.EmailService
;
import
me.zhengjie.utils.RedisUtils
;
import
me.zhengjie.utils.RedisUtils
;
import
me.zhengjie.utils.SpringContextHolder
;
import
me.zhengjie.utils.SpringContextHolder
;
import
me.zhengjie.utils.StringUtils
;
import
me.zhengjie.utils.ThrowableUtil
;
import
me.zhengjie.utils.ThrowableUtil
;
import
org.quartz.JobExecutionContext
;
import
org.quartz.JobExecutionContext
;
import
org.springframework.scheduling.annotation.Async
;
import
org.springframework.scheduling.annotation.Async
;
...
@@ -54,6 +55,8 @@ public class ExecutionJob extends QuartzJobBean {
...
@@ -54,6 +55,8 @@ public class ExecutionJob extends QuartzJobBean {
QuartzLogRepository
quartzLogRepository
=
SpringContextHolder
.
getBean
(
QuartzLogRepository
.
class
);
QuartzLogRepository
quartzLogRepository
=
SpringContextHolder
.
getBean
(
QuartzLogRepository
.
class
);
QuartzJobService
quartzJobService
=
SpringContextHolder
.
getBean
(
QuartzJobService
.
class
);
QuartzJobService
quartzJobService
=
SpringContextHolder
.
getBean
(
QuartzJobService
.
class
);
RedisUtils
redisUtils
=
SpringContextHolder
.
getBean
(
RedisUtils
.
class
);
RedisUtils
redisUtils
=
SpringContextHolder
.
getBean
(
RedisUtils
.
class
);
String
uuid
=
quartzJob
.
getUuid
();
QuartzLog
log
=
new
QuartzLog
();
QuartzLog
log
=
new
QuartzLog
();
log
.
setJobName
(
quartzJob
.
getJobName
());
log
.
setJobName
(
quartzJob
.
getJobName
());
...
@@ -72,7 +75,9 @@ public class ExecutionJob extends QuartzJobBean {
...
@@ -72,7 +75,9 @@ public class ExecutionJob extends QuartzJobBean {
future
.
get
();
future
.
get
();
long
times
=
System
.
currentTimeMillis
()
-
startTime
;
long
times
=
System
.
currentTimeMillis
()
-
startTime
;
log
.
setTime
(
times
);
log
.
setTime
(
times
);
redisUtils
.
set
(
quartzJob
.
getUuid
(),
true
);
if
(
StringUtils
.
isNotBlank
(
uuid
))
{
redisUtils
.
set
(
uuid
,
true
);
}
// 任务状态
// 任务状态
log
.
setIsSuccess
(
true
);
log
.
setIsSuccess
(
true
);
System
.
out
.
println
(
"任务执行完毕,任务名称:"
+
quartzJob
.
getJobName
()
+
", 执行时间:"
+
times
+
"毫秒"
);
System
.
out
.
println
(
"任务执行完毕,任务名称:"
+
quartzJob
.
getJobName
()
+
", 执行时间:"
+
times
+
"毫秒"
);
...
@@ -84,7 +89,9 @@ public class ExecutionJob extends QuartzJobBean {
...
@@ -84,7 +89,9 @@ public class ExecutionJob extends QuartzJobBean {
quartzJobService
.
executionSubJob
(
tasks
);
quartzJobService
.
executionSubJob
(
tasks
);
}
}
}
catch
(
Exception
e
)
{
}
catch
(
Exception
e
)
{
redisUtils
.
set
(
quartzJob
.
getUuid
(),
false
);
if
(
StringUtils
.
isNotBlank
(
uuid
))
{
redisUtils
.
set
(
uuid
,
false
);
}
System
.
out
.
println
(
"任务执行失败,任务名称:"
+
quartzJob
.
getJobName
());
System
.
out
.
println
(
"任务执行失败,任务名称:"
+
quartzJob
.
getJobName
());
System
.
out
.
println
(
"--------------------------------------------------------------"
);
System
.
out
.
println
(
"--------------------------------------------------------------"
);
long
times
=
System
.
currentTimeMillis
()
-
startTime
;
long
times
=
System
.
currentTimeMillis
()
-
startTime
;
...
...
eladmin-system/src/main/java/me/zhengjie/modules/security/config/SecurityConfig.java
View file @
cf1e17c7
...
@@ -17,7 +17,10 @@ package me.zhengjie.modules.security.config;
...
@@ -17,7 +17,10 @@ package me.zhengjie.modules.security.config;
import
lombok.RequiredArgsConstructor
;
import
lombok.RequiredArgsConstructor
;
import
me.zhengjie.annotation.AnonymousAccess
;
import
me.zhengjie.annotation.AnonymousAccess
;
import
me.zhengjie.modules.security.config.bean.SecurityProperties
;
import
me.zhengjie.modules.security.security.*
;
import
me.zhengjie.modules.security.security.*
;
import
me.zhengjie.modules.security.service.OnlineUserService
;
import
me.zhengjie.modules.security.service.UserCacheClean
;
import
me.zhengjie.utils.enums.RequestMethodEnum
;
import
me.zhengjie.utils.enums.RequestMethodEnum
;
import
org.springframework.context.ApplicationContext
;
import
org.springframework.context.ApplicationContext
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Bean
;
...
@@ -37,6 +40,7 @@ import org.springframework.web.filter.CorsFilter;
...
@@ -37,6 +40,7 @@ import org.springframework.web.filter.CorsFilter;
import
org.springframework.web.method.HandlerMethod
;
import
org.springframework.web.method.HandlerMethod
;
import
org.springframework.web.servlet.mvc.method.RequestMappingInfo
;
import
org.springframework.web.servlet.mvc.method.RequestMappingInfo
;
import
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
;
import
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
;
import
java.util.*
;
import
java.util.*
;
/**
/**
...
@@ -53,6 +57,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
@@ -53,6 +57,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
private
final
JwtAuthenticationEntryPoint
authenticationErrorHandler
;
private
final
JwtAuthenticationEntryPoint
authenticationErrorHandler
;
private
final
JwtAccessDeniedHandler
jwtAccessDeniedHandler
;
private
final
JwtAccessDeniedHandler
jwtAccessDeniedHandler
;
private
final
ApplicationContext
applicationContext
;
private
final
ApplicationContext
applicationContext
;
private
final
SecurityProperties
properties
;
private
final
OnlineUserService
onlineUserService
;
private
final
UserCacheClean
userCacheClean
;
@Bean
@Bean
GrantedAuthorityDefaults
grantedAuthorityDefaults
()
{
GrantedAuthorityDefaults
grantedAuthorityDefaults
()
{
...
@@ -144,7 +151,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
@@ -144,7 +151,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
if
(
null
!=
anonymousAccess
)
{
if
(
null
!=
anonymousAccess
)
{
List
<
RequestMethod
>
requestMethods
=
new
ArrayList
<>(
infoEntry
.
getKey
().
getMethodsCondition
().
getMethods
());
List
<
RequestMethod
>
requestMethods
=
new
ArrayList
<>(
infoEntry
.
getKey
().
getMethodsCondition
().
getMethods
());
RequestMethodEnum
request
=
RequestMethodEnum
.
find
(
requestMethods
.
size
()
==
0
?
RequestMethodEnum
.
ALL
.
getType
()
:
requestMethods
.
get
(
0
).
name
());
RequestMethodEnum
request
=
RequestMethodEnum
.
find
(
requestMethods
.
size
()
==
0
?
RequestMethodEnum
.
ALL
.
getType
()
:
requestMethods
.
get
(
0
).
name
());
switch
(
Objects
.
requireNonNull
(
request
)){
switch
(
Objects
.
requireNonNull
(
request
))
{
case
GET:
case
GET:
get
.
addAll
(
infoEntry
.
getKey
().
getPatternsCondition
().
getPatterns
());
get
.
addAll
(
infoEntry
.
getKey
().
getPatternsCondition
().
getPatterns
());
break
;
break
;
...
@@ -176,6 +183,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
@@ -176,6 +183,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
}
private
TokenConfigurer
securityConfigurerAdapter
()
{
private
TokenConfigurer
securityConfigurerAdapter
()
{
return
new
TokenConfigurer
(
tokenProvider
);
return
new
TokenConfigurer
(
tokenProvider
,
properties
,
onlineUserService
,
userCacheClean
);
}
}
}
}
eladmin-system/src/main/java/me/zhengjie/modules/security/config/bean/LoginProperties.java
View file @
cf1e17c7
...
@@ -19,10 +19,12 @@ package me.zhengjie.modules.security.config.bean;
...
@@ -19,10 +19,12 @@ package me.zhengjie.modules.security.config.bean;
import
com.wf.captcha.*
;
import
com.wf.captcha.*
;
import
com.wf.captcha.base.Captcha
;
import
com.wf.captcha.base.Captcha
;
import
me.zhengjie.exception.BadConfigurationException
;
import
me.zhengjie.exception.BadConfigurationException
;
import
java.util.Objects
;
import
java.util.Objects
;
/**
/**
* 配置文件读取
* 配置文件读取
*
* @author liaojinlong
* @author liaojinlong
* @date loginCode.length0loginCode.length0/6/10 17:loginCode.length6
* @date loginCode.length0loginCode.length0/6/10 17:loginCode.length6
*/
*/
...
@@ -34,6 +36,10 @@ public class LoginProperties {
...
@@ -34,6 +36,10 @@ public class LoginProperties {
private
boolean
singleLogin
=
false
;
private
boolean
singleLogin
=
false
;
private
LoginCode
loginCode
;
private
LoginCode
loginCode
;
/**
* 用户登录信息缓存
*/
private
boolean
cacheEnable
;
public
boolean
isSingleLogin
()
{
public
boolean
isSingleLogin
()
{
return
singleLogin
;
return
singleLogin
;
...
@@ -51,6 +57,14 @@ public class LoginProperties {
...
@@ -51,6 +57,14 @@ public class LoginProperties {
this
.
loginCode
=
loginCode
;
this
.
loginCode
=
loginCode
;
}
}
public
boolean
isCacheEnable
()
{
return
cacheEnable
;
}
public
void
setCacheEnable
(
boolean
cacheEnable
)
{
this
.
cacheEnable
=
cacheEnable
;
}
/**
/**
* 获取验证码生产类
* 获取验证码生产类
*
*
...
...
eladmin-system/src/main/java/me/zhengjie/modules/security/rest/AuthorizationController.java
View file @
cf1e17c7
...
@@ -16,7 +16,6 @@
...
@@ -16,7 +16,6 @@
package
me.zhengjie.modules.security.rest
;
package
me.zhengjie.modules.security.rest
;
import
cn.hutool.core.util.IdUtil
;
import
cn.hutool.core.util.IdUtil
;
import
com.wf.captcha.ArithmeticCaptcha
;
import
com.wf.captcha.base.Captcha
;
import
com.wf.captcha.base.Captcha
;
import
io.swagger.annotations.Api
;
import
io.swagger.annotations.Api
;
import
io.swagger.annotations.ApiOperation
;
import
io.swagger.annotations.ApiOperation
;
...
@@ -38,7 +37,6 @@ import me.zhengjie.utils.RsaUtils;
...
@@ -38,7 +37,6 @@ import me.zhengjie.utils.RsaUtils;
import
me.zhengjie.utils.RedisUtils
;
import
me.zhengjie.utils.RedisUtils
;
import
me.zhengjie.utils.SecurityUtils
;
import
me.zhengjie.utils.SecurityUtils
;
import
me.zhengjie.utils.StringUtils
;
import
me.zhengjie.utils.StringUtils
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.http.ResponseEntity
;
import
org.springframework.http.ResponseEntity
;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken
;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken
;
...
@@ -47,7 +45,6 @@ import org.springframework.security.core.Authentication;
...
@@ -47,7 +45,6 @@ import org.springframework.security.core.Authentication;
import
org.springframework.security.core.context.SecurityContextHolder
;
import
org.springframework.security.core.context.SecurityContextHolder
;
import
org.springframework.validation.annotation.Validated
;
import
org.springframework.validation.annotation.Validated
;
import
org.springframework.web.bind.annotation.*
;
import
org.springframework.web.bind.annotation.*
;
import
javax.annotation.Resource
;
import
javax.annotation.Resource
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletRequest
;
import
java.util.HashMap
;
import
java.util.HashMap
;
...
@@ -91,7 +88,6 @@ public class AuthorizationController {
...
@@ -91,7 +88,6 @@ public class AuthorizationController {
}
}
UsernamePasswordAuthenticationToken
authenticationToken
=
UsernamePasswordAuthenticationToken
authenticationToken
=
new
UsernamePasswordAuthenticationToken
(
authUser
.
getUsername
(),
password
);
new
UsernamePasswordAuthenticationToken
(
authUser
.
getUsername
(),
password
);
Authentication
authentication
=
authenticationManagerBuilder
.
getObject
().
authenticate
(
authenticationToken
);
Authentication
authentication
=
authenticationManagerBuilder
.
getObject
().
authenticate
(
authenticationToken
);
SecurityContextHolder
.
getContext
().
setAuthentication
(
authentication
);
SecurityContextHolder
.
getContext
().
setAuthentication
(
authentication
);
// 生成令牌
// 生成令牌
...
...
eladmin-system/src/main/java/me/zhengjie/modules/security/security/TokenConfigurer.java
View file @
cf1e17c7
...
@@ -16,6 +16,9 @@
...
@@ -16,6 +16,9 @@
package
me.zhengjie.modules.security.security
;
package
me.zhengjie.modules.security.security
;
import
lombok.RequiredArgsConstructor
;
import
lombok.RequiredArgsConstructor
;
import
me.zhengjie.modules.security.config.bean.SecurityProperties
;
import
me.zhengjie.modules.security.service.OnlineUserService
;
import
me.zhengjie.modules.security.service.UserCacheClean
;
import
org.springframework.security.config.annotation.SecurityConfigurerAdapter
;
import
org.springframework.security.config.annotation.SecurityConfigurerAdapter
;
import
org.springframework.security.config.annotation.web.builders.HttpSecurity
;
import
org.springframework.security.config.annotation.web.builders.HttpSecurity
;
import
org.springframework.security.web.DefaultSecurityFilterChain
;
import
org.springframework.security.web.DefaultSecurityFilterChain
;
...
@@ -28,10 +31,13 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic
...
@@ -28,10 +31,13 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic
public
class
TokenConfigurer
extends
SecurityConfigurerAdapter
<
DefaultSecurityFilterChain
,
HttpSecurity
>
{
public
class
TokenConfigurer
extends
SecurityConfigurerAdapter
<
DefaultSecurityFilterChain
,
HttpSecurity
>
{
private
final
TokenProvider
tokenProvider
;
private
final
TokenProvider
tokenProvider
;
private
final
SecurityProperties
properties
;
private
final
OnlineUserService
onlineUserService
;
private
final
UserCacheClean
userCacheClean
;
@Override
@Override
public
void
configure
(
HttpSecurity
http
)
{
public
void
configure
(
HttpSecurity
http
)
{
TokenFilter
customFilter
=
new
TokenFilter
(
tokenProvider
);
TokenFilter
customFilter
=
new
TokenFilter
(
tokenProvider
,
properties
,
onlineUserService
,
userCacheClean
);
http
.
addFilterBefore
(
customFilter
,
UsernamePasswordAuthenticationFilter
.
class
);
http
.
addFilterBefore
(
customFilter
,
UsernamePasswordAuthenticationFilter
.
class
);
}
}
}
}
eladmin-system/src/main/java/me/zhengjie/modules/security/security/TokenFilter.java
View file @
cf1e17c7
...
@@ -17,64 +17,93 @@ package me.zhengjie.modules.security.security;
...
@@ -17,64 +17,93 @@ package me.zhengjie.modules.security.security;
import
cn.hutool.core.util.StrUtil
;
import
cn.hutool.core.util.StrUtil
;
import
io.jsonwebtoken.ExpiredJwtException
;
import
io.jsonwebtoken.ExpiredJwtException
;
import
lombok.RequiredArgsConstructor
;
import
lombok.extern.slf4j.Slf4j
;
import
me.zhengjie.modules.security.config.bean.SecurityProperties
;
import
me.zhengjie.modules.security.config.bean.SecurityProperties
;
import
me.zhengjie.modules.security.service.UserCacheClean
;
import
me.zhengjie.modules.security.service.dto.OnlineUserDto
;
import
me.zhengjie.modules.security.service.dto.OnlineUserDto
;
import
me.zhengjie.modules.security.service.OnlineUserService
;
import
me.zhengjie.modules.security.service.OnlineUserService
;
import
me.zhengjie.utils.SpringContextHolder
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.security.core.Authentication
;
import
org.springframework.security.core.Authentication
;
import
org.springframework.security.core.context.SecurityContextHolder
;
import
org.springframework.security.core.context.SecurityContextHolder
;
import
org.springframework.util.StringUtils
;
import
org.springframework.util.StringUtils
;
import
org.springframework.web.filter.GenericFilterBean
;
import
org.springframework.web.filter.GenericFilterBean
;
import
javax.servlet.FilterChain
;
import
javax.servlet.FilterChain
;
import
javax.servlet.ServletException
;
import
javax.servlet.ServletException
;
import
javax.servlet.ServletRequest
;
import
javax.servlet.ServletRequest
;
import
javax.servlet.ServletResponse
;
import
javax.servlet.ServletResponse
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletRequest
;
import
java.io.IOException
;
import
java.io.IOException
;
import
java.util.Objects
;
/**
/**
* @author /
* @author /
*/
*/
@Slf4j
@RequiredArgsConstructor
public
class
TokenFilter
extends
GenericFilterBean
{
public
class
TokenFilter
extends
GenericFilterBean
{
private
static
final
Logger
log
=
LoggerFactory
.
getLogger
(
TokenFilter
.
class
);
private
final
TokenProvider
tokenProvider
;
private
final
SecurityProperties
properties
;
private
final
OnlineUserService
onlineUserService
;
private
final
UserCacheClean
userCacheClean
;
private
final
TokenProvider
tokenProvider
;
/**
* @param tokenProvider Token
* @param properties JWT
* @param onlineUserService 用户在线
* @param userCacheClean 用户缓存清理工具
*/
public
TokenFilter
(
TokenProvider
tokenProvider
,
SecurityProperties
properties
,
OnlineUserService
onlineUserService
,
UserCacheClean
userCacheClean
)
{
this
.
properties
=
properties
;
this
.
onlineUserService
=
onlineUserService
;
this
.
tokenProvider
=
tokenProvider
;
this
.
userCacheClean
=
userCacheClean
;
}
@Override
@Override
public
void
doFilter
(
ServletRequest
servletRequest
,
ServletResponse
servletResponse
,
FilterChain
filterChain
)
public
void
doFilter
(
ServletRequest
servletRequest
,
ServletResponse
servletResponse
,
FilterChain
filterChain
)
throws
IOException
,
ServletException
{
throws
IOException
,
ServletException
{
HttpServletRequest
httpServletRequest
=
(
HttpServletRequest
)
servletRequest
;
HttpServletRequest
httpServletRequest
=
(
HttpServletRequest
)
servletRequest
;
String
token
=
resolveToken
(
httpServletRequest
);
String
token
=
resolveToken
(
httpServletRequest
);
// 对于 Token 为空的不需要去查 Redis
// 对于 Token 为空的不需要去查 Redis
if
(
StrUtil
.
isNotBlank
(
token
)){
if
(
StrUtil
.
isNotBlank
(
token
))
{
OnlineUserDto
onlineUserDto
=
null
;
OnlineUserDto
onlineUserDto
=
null
;
SecurityProperties
properties
=
SpringContextHolder
.
getBean
(
SecurityProperties
.
class
);
boolean
cleanUserCache
=
false
;
try
{
try
{
OnlineUserService
onlineUserService
=
SpringContextHolder
.
getBean
(
OnlineUserService
.
class
);
onlineUserDto
=
onlineUserService
.
getOne
(
properties
.
getOnlineKey
()
+
token
);
onlineUserDto
=
onlineUserService
.
getOne
(
properties
.
getOnlineKey
()
+
token
);
}
catch
(
ExpiredJwtException
e
)
{
}
catch
(
ExpiredJwtException
e
)
{
log
.
error
(
e
.
getMessage
());
log
.
error
(
e
.
getMessage
());
cleanUserCache
=
true
;
}
}
finally
{
if
(
onlineUserDto
!=
null
&&
StringUtils
.
hasText
(
token
))
{
if
(
cleanUserCache
||
Objects
.
isNull
(
onlineUserDto
))
{
Authentication
authentication
=
tokenProvider
.
getAuthentication
(
token
);
userCacheClean
.
cleanUserCache
(
String
.
valueOf
(
tokenProvider
.
getClaims
(
token
).
get
(
TokenProvider
.
AUTHORITIES_KEY
)));
SecurityContextHolder
.
getContext
().
setAuthentication
(
authentication
);
}
// Token 续期
}
tokenProvider
.
checkRenewal
(
token
);
if
(
onlineUserDto
!=
null
&&
StringUtils
.
hasText
(
token
))
{
}
Authentication
authentication
=
tokenProvider
.
getAuthentication
(
token
);
}
SecurityContextHolder
.
getContext
().
setAuthentication
(
authentication
);
filterChain
.
doFilter
(
servletRequest
,
servletResponse
);
// Token 续期
}
tokenProvider
.
checkRenewal
(
token
);
}
}
filterChain
.
doFilter
(
servletRequest
,
servletResponse
);
}
private
String
resolveToken
(
HttpServletRequest
request
)
{
/**
SecurityProperties
properties
=
SpringContextHolder
.
getBean
(
SecurityProperties
.
class
);
* 初步检测Token
String
bearerToken
=
request
.
getHeader
(
properties
.
getHeader
());
*
if
(
StringUtils
.
hasText
(
bearerToken
)
&&
bearerToken
.
startsWith
(
properties
.
getTokenStartWith
()))
{
* @param request /
// 去掉令牌前缀
* @return /
return
bearerToken
.
replace
(
properties
.
getTokenStartWith
(),
""
);
*/
}
private
String
resolveToken
(
HttpServletRequest
request
)
{
return
null
;
String
bearerToken
=
request
.
getHeader
(
properties
.
getHeader
());
}
if
(
StringUtils
.
hasText
(
bearerToken
)
&&
bearerToken
.
startsWith
(
properties
.
getTokenStartWith
()))
{
// 去掉令牌前缀
return
bearerToken
.
replace
(
properties
.
getTokenStartWith
(),
""
);
}
else
{
log
.
debug
(
"非法Token:{}"
,
bearerToken
);
}
return
null
;
}
}
}
eladmin-system/src/main/java/me/zhengjie/modules/security/security/TokenProvider.java
View file @
cf1e17c7
...
@@ -22,7 +22,6 @@ import cn.hutool.core.util.ObjectUtil;
...
@@ -22,7 +22,6 @@ import cn.hutool.core.util.ObjectUtil;
import
io.jsonwebtoken.*
;
import
io.jsonwebtoken.*
;
import
io.jsonwebtoken.io.Decoders
;
import
io.jsonwebtoken.io.Decoders
;
import
io.jsonwebtoken.security.Keys
;
import
io.jsonwebtoken.security.Keys
;
import
lombok.RequiredArgsConstructor
;
import
lombok.extern.slf4j.Slf4j
;
import
lombok.extern.slf4j.Slf4j
;
import
me.zhengjie.modules.security.config.bean.SecurityProperties
;
import
me.zhengjie.modules.security.config.bean.SecurityProperties
;
import
me.zhengjie.utils.RedisUtils
;
import
me.zhengjie.utils.RedisUtils
;
...
@@ -33,6 +32,7 @@ import org.springframework.security.core.GrantedAuthority;
...
@@ -33,6 +32,7 @@ import org.springframework.security.core.GrantedAuthority;
import
org.springframework.security.core.authority.SimpleGrantedAuthority
;
import
org.springframework.security.core.authority.SimpleGrantedAuthority
;
import
org.springframework.security.core.userdetails.User
;
import
org.springframework.security.core.userdetails.User
;
import
org.springframework.stereotype.Component
;
import
org.springframework.stereotype.Component
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletRequest
;
import
java.security.Key
;
import
java.security.Key
;
import
java.util.Arrays
;
import
java.util.Arrays
;
...
@@ -47,75 +47,100 @@ import java.util.stream.Collectors;
...
@@ -47,75 +47,100 @@ import java.util.stream.Collectors;
*/
*/
@Slf4j
@Slf4j
@Component
@Component
@RequiredArgsConstructor
public
class
TokenProvider
implements
InitializingBean
{
public
class
TokenProvider
implements
InitializingBean
{
private
final
SecurityProperties
properties
;
private
final
SecurityProperties
properties
;
private
final
RedisUtils
redisUtils
;
private
final
RedisUtils
redisUtils
;
private
static
final
String
AUTHORITIES_KEY
=
"auth"
;
public
static
final
String
AUTHORITIES_KEY
=
"auth"
;
private
Key
key
;
private
JwtParser
jwtParser
;
private
JwtBuilder
jwtBuilder
;
@Override
public
TokenProvider
(
SecurityProperties
properties
,
RedisUtils
redisUtils
)
{
public
void
afterPropertiesSet
()
{
this
.
properties
=
properties
;
byte
[]
keyBytes
=
Decoders
.
BASE64
.
decode
(
properties
.
getBase64Secret
());
this
.
redisUtils
=
redisUtils
;
this
.
key
=
Keys
.
hmacShaKeyFor
(
keyBytes
);
}
}
public
String
createToken
(
Authentication
authentication
)
{
@Override
String
authorities
=
authentication
.
getAuthorities
().
stream
()
public
void
afterPropertiesSet
()
{
.
map
(
GrantedAuthority:
:
getAuthority
)
byte
[]
keyBytes
=
Decoders
.
BASE64
.
decode
(
properties
.
getBase64Secret
());
.
collect
(
Collectors
.
joining
(
","
));
Key
key
=
Keys
.
hmacShaKeyFor
(
keyBytes
);
jwtParser
=
Jwts
.
parserBuilder
()
.
setSigningKey
(
key
)
.
build
();
jwtBuilder
=
Jwts
.
builder
()
.
signWith
(
key
,
SignatureAlgorithm
.
HS512
);
}
return
Jwts
.
builder
()
/**
.
setSubject
(
authentication
.
getName
())
* 创建Token 设置永不过期,
.
claim
(
AUTHORITIES_KEY
,
authorities
)
* Token 的时间有效性转到Redis 维护
.
signWith
(
key
,
SignatureAlgorithm
.
HS512
)
*
// 加入ID确保生成的 Token 都不一致
* @param authentication /
.
setId
(
IdUtil
.
simpleUUID
())
* @return /
.
compact
();
*/
}
public
String
createToken
(
Authentication
authentication
)
{
/*
* 获取权限列表
*/
String
authorities
=
authentication
.
getAuthorities
().
stream
()
.
map
(
GrantedAuthority:
:
getAuthority
)
.
collect
(
Collectors
.
joining
(
","
));
Authentication
getAuthentication
(
String
token
)
{
return
jwtBuilder
Claims
claims
=
Jwts
.
parserBuilder
()
// 加入ID确保生成的 Token 都不一致
.
setSigningKey
(
key
)
.
setId
(
IdUtil
.
simpleUUID
())
.
build
()
.
claim
(
AUTHORITIES_KEY
,
authorities
)
.
parseClaimsJws
(
token
)
.
setSubject
(
authentication
.
getName
())
.
getBody
();
.
compact
();
}
// fix bug: 当前用户如果没有任何权限时,在输入用户名后,刷新验证码会抛IllegalArgumentException
/**
Object
authoritiesStr
=
claims
.
get
(
AUTHORITIES_KEY
);
* 依据Token 获取鉴权信息
Collection
<?
extends
GrantedAuthority
>
authorities
=
*
ObjectUtil
.
isNotEmpty
(
authoritiesStr
)
?
* @param token /
Arrays
.
stream
(
authoritiesStr
.
toString
().
split
(
","
))
* @return /
.
map
(
SimpleGrantedAuthority:
:
new
)
*/
.
collect
(
Collectors
.
toList
())
:
Collections
.
emptyList
();
Authentication
getAuthentication
(
String
token
)
{
Claims
claims
=
getClaims
(
token
);
User
principal
=
new
User
(
claims
.
getSubject
(),
""
,
authorities
);
// fix bug: 当前用户如果没有任何权限时,在输入用户名后,刷新验证码会抛IllegalArgumentException
Object
authoritiesStr
=
claims
.
get
(
AUTHORITIES_KEY
);
Collection
<?
extends
GrantedAuthority
>
authorities
=
ObjectUtil
.
isNotEmpty
(
authoritiesStr
)
?
Arrays
.
stream
(
authoritiesStr
.
toString
().
split
(
","
))
.
map
(
SimpleGrantedAuthority:
:
new
)
.
collect
(
Collectors
.
toList
())
:
Collections
.
emptyList
();
User
principal
=
new
User
(
claims
.
getSubject
(),
"******"
,
authorities
);
return
new
UsernamePasswordAuthenticationToken
(
principal
,
token
,
authorities
);
}
return
new
UsernamePasswordAuthenticationToken
(
principal
,
token
,
authorities
);
public
Claims
getClaims
(
String
token
)
{
}
return
jwtParser
.
parseClaimsJws
(
token
)
.
getBody
();
}
/**
/**
* @param token 需要检查的token
* @param token 需要检查的token
*/
*/
public
void
checkRenewal
(
String
token
){
public
void
checkRenewal
(
String
token
)
{
// 判断是否续期token,计算token的过期时间
// 判断是否续期token,计算token的过期时间
long
time
=
redisUtils
.
getExpire
(
properties
.
getOnlineKey
()
+
token
)
*
1000
;
long
time
=
redisUtils
.
getExpire
(
properties
.
getOnlineKey
()
+
token
)
*
1000
;
Date
expireDate
=
DateUtil
.
offset
(
new
Date
(),
DateField
.
MILLISECOND
,
(
int
)
time
);
Date
expireDate
=
DateUtil
.
offset
(
new
Date
(),
DateField
.
MILLISECOND
,
(
int
)
time
);
// 判断当前时间与过期时间的时间差
// 判断当前时间与过期时间的时间差
long
differ
=
expireDate
.
getTime
()
-
System
.
currentTimeMillis
();
long
differ
=
expireDate
.
getTime
()
-
System
.
currentTimeMillis
();
// 如果在续期检查的范围内,则续期
// 如果在续期检查的范围内,则续期
if
(
differ
<=
properties
.
getDetect
()){
if
(
differ
<=
properties
.
getDetect
())
{
long
renew
=
time
+
properties
.
getRenew
();
long
renew
=
time
+
properties
.
getRenew
();
redisUtils
.
expire
(
properties
.
getOnlineKey
()
+
token
,
renew
,
TimeUnit
.
MILLISECONDS
);
redisUtils
.
expire
(
properties
.
getOnlineKey
()
+
token
,
renew
,
TimeUnit
.
MILLISECONDS
);
}
}
}
}
public
String
getToken
(
HttpServletRequest
request
){
public
String
getToken
(
HttpServletRequest
request
)
{
final
String
requestHeader
=
request
.
getHeader
(
properties
.
getHeader
());
final
String
requestHeader
=
request
.
getHeader
(
properties
.
getHeader
());
if
(
requestHeader
!=
null
&&
requestHeader
.
startsWith
(
properties
.
getTokenStartWith
()))
{
if
(
requestHeader
!=
null
&&
requestHeader
.
startsWith
(
properties
.
getTokenStartWith
()))
{
return
requestHeader
.
substring
(
7
);
return
requestHeader
.
substring
(
7
);
}
}
return
null
;
return
null
;
}
}
}
}
eladmin-system/src/main/java/me/zhengjie/modules/security/service/UserCacheClean.java
0 → 100644
View file @
cf1e17c7
/*
* Copyright 2019-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package
me.zhengjie.modules.security.service
;
import
me.zhengjie.utils.StringUtils
;
import
org.springframework.stereotype.Component
;
/**
* @author: liaojinlong
* @date: 2020/6/11 18:01
* @apiNote: 用于清理 用户登录信息缓存,为防止Spring循环依赖与安全考虑 ,单独构成工具类
*/
@Component
public
class
UserCacheClean
{
/**
* 清理特定用户缓存信息<br>
* 用户信息变更时
*
* @param userName /
*/
public
void
cleanUserCache
(
String
userName
)
{
if
(
StringUtils
.
isNotEmpty
(
userName
))
{
UserDetailsServiceImpl
.
userDtoCache
.
remove
(
userName
);
}
}
/**
* 清理所有用户的缓存信息<br>
* ,如发生角色授权信息变化,可以简便的全部失效缓存
*/
public
void
cleanAll
()
{
UserDetailsServiceImpl
.
userDtoCache
.
clear
();
}
}
eladmin-system/src/main/java/me/zhengjie/modules/security/service/UserDetailsServiceImpl.java
View file @
cf1e17c7
...
@@ -18,6 +18,7 @@ package me.zhengjie.modules.security.service;
...
@@ -18,6 +18,7 @@ package me.zhengjie.modules.security.service;
import
lombok.RequiredArgsConstructor
;
import
lombok.RequiredArgsConstructor
;
import
me.zhengjie.exception.BadRequestException
;
import
me.zhengjie.exception.BadRequestException
;
import
me.zhengjie.exception.EntityNotFoundException
;
import
me.zhengjie.exception.EntityNotFoundException
;
import
me.zhengjie.modules.security.config.bean.LoginProperties
;
import
me.zhengjie.modules.security.service.dto.JwtUserDto
;
import
me.zhengjie.modules.security.service.dto.JwtUserDto
;
import
me.zhengjie.modules.system.service.DataService
;
import
me.zhengjie.modules.system.service.DataService
;
import
me.zhengjie.modules.system.service.RoleService
;
import
me.zhengjie.modules.system.service.RoleService
;
...
@@ -26,6 +27,8 @@ import me.zhengjie.modules.system.service.dto.UserDto;
...
@@ -26,6 +27,8 @@ import me.zhengjie.modules.system.service.dto.UserDto;
import
org.springframework.security.core.userdetails.UserDetailsService
;
import
org.springframework.security.core.userdetails.UserDetailsService
;
import
org.springframework.security.core.userdetails.UsernameNotFoundException
;
import
org.springframework.security.core.userdetails.UsernameNotFoundException
;
import
org.springframework.stereotype.Service
;
import
org.springframework.stereotype.Service
;
import
java.util.Map
;
import
java.util.concurrent.ConcurrentHashMap
;
/**
/**
* @author Zheng Jie
* @author Zheng Jie
...
@@ -34,31 +37,51 @@ import org.springframework.stereotype.Service;
...
@@ -34,31 +37,51 @@ import org.springframework.stereotype.Service;
@RequiredArgsConstructor
@RequiredArgsConstructor
@Service
(
"userDetailsService"
)
@Service
(
"userDetailsService"
)
public
class
UserDetailsServiceImpl
implements
UserDetailsService
{
public
class
UserDetailsServiceImpl
implements
UserDetailsService
{
private
final
UserService
userService
;
private
final
UserService
userService
;
private
final
RoleService
roleService
;
private
final
RoleService
roleService
;
private
final
DataService
dataService
;
private
final
DataService
dataService
;
private
final
LoginProperties
loginProperties
;
public
void
setEnableCache
(
boolean
enableCache
)
{
this
.
loginProperties
.
setCacheEnable
(
enableCache
);
}
/**
* 用户信息缓存
*
* @see {@link UserCacheClean}
*/
static
Map
<
String
,
JwtUserDto
>
userDtoCache
=
new
ConcurrentHashMap
<>();
@Override
@Override
public
JwtUserDto
loadUserByUsername
(
String
username
)
{
public
JwtUserDto
loadUserByUsername
(
String
username
)
{
UserDto
user
;
boolean
searchDb
=
true
;
try
{
JwtUserDto
jwtUserDto
=
null
;
user
=
userService
.
findByName
(
username
);
if
(
loginProperties
.
isCacheEnable
()
&&
userDtoCache
.
containsKey
(
username
))
{
}
catch
(
EntityNotFoundException
e
)
{
jwtUserDto
=
userDtoCache
.
get
(
username
);
// SpringSecurity会自动转换UsernameNotFoundException为BadCredentialsException
searchDb
=
false
;
throw
new
UsernameNotFoundException
(
""
,
e
);
}
}
if
(
user
==
null
)
{
if
(
searchDb
)
{
throw
new
UsernameNotFoundException
(
""
);
UserDto
user
;
}
else
{
try
{
if
(!
user
.
getEnabled
())
{
user
=
userService
.
findByName
(
username
);
throw
new
BadRequestException
(
"账号未激活"
);
}
catch
(
EntityNotFoundException
e
)
{
// SpringSecurity会自动转换UsernameNotFoundException为BadCredentialsException
throw
new
UsernameNotFoundException
(
""
,
e
);
}
if
(
user
==
null
)
{
throw
new
UsernameNotFoundException
(
""
);
}
else
{
if
(!
user
.
getEnabled
())
{
throw
new
BadRequestException
(
"账号未激活"
);
}
jwtUserDto
=
new
JwtUserDto
(
user
,
dataService
.
getDeptIds
(
user
),
roleService
.
mapToGrantedAuthorities
(
user
)
);
userDtoCache
.
put
(
username
,
jwtUserDto
);
}
}
return
new
JwtUserDto
(
user
,
dataService
.
getDeptIds
(
user
),
roleService
.
mapToGrantedAuthorities
(
user
)
);
}
}
return
jwtUserDto
;
}
}
}
}
Prev
1
2
Next
Write
Preview
Supports
Markdown
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment