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
207e6fb1
Commit
207e6fb1
authored
Mar 10, 2020
by
Elune
Browse files
SecurityUtils 加入获取当前登录用户ID方法,Security 结构调整
parent
4054ac7b
Changes
25
Hide whitespace changes
Inline
Side-by-side
eladmin-common/src/main/java/me/zhengjie/config/ElPermissionConfig.java
View file @
207e6fb1
...
...
@@ -15,7 +15,7 @@ public class ElPermissionConfig {
public
Boolean
check
(
String
...
permissions
){
// 获取当前用户的所有权限
List
<
String
>
elPermissions
=
SecurityUtils
.
get
UserDetails
().
getAuthorities
().
stream
().
map
(
GrantedAuthority:
:
getAuthority
).
collect
(
Collectors
.
toList
());
List
<
String
>
elPermissions
=
SecurityUtils
.
get
CurrentUser
().
getAuthorities
().
stream
().
map
(
GrantedAuthority:
:
getAuthority
).
collect
(
Collectors
.
toList
());
// 判断当前用户的所有权限是否包含接口上定义的权限
return
elPermissions
.
contains
(
"admin"
)
||
Arrays
.
stream
(
permissions
).
anyMatch
(
elPermissions:
:
contains
);
}
...
...
eladmin-common/src/main/java/me/zhengjie/utils/SecurityUtils.java
View file @
207e6fb1
package
me.zhengjie.utils
;
import
cn.hutool.json.JSONObject
;
import
lombok.extern.slf4j.Slf4j
;
import
me.zhengjie.exception.BadRequestException
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.security.core.Authentication
;
import
org.springframework.security.core.context.SecurityContextHolder
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
org.springframework.security.core.userdetails.UserDetailsService
;
/**
* 获取当前登录的用户
* @author Zheng Jie
* @date 2019-01-17
*/
@Slf4j
public
class
SecurityUtils
{
public
static
UserDetails
getUserDetails
()
{
UserDetails
userDetails
;
try
{
userDetails
=
(
UserDetails
)
SecurityContextHolder
.
getContext
().
getAuthentication
().
getPrincipal
();
}
catch
(
Exception
e
)
{
throw
new
BadRequestException
(
HttpStatus
.
UNAUTHORIZED
,
"登录状态过期"
);
/**
* 获取当前登录的用户
* @return UserDetails
*/
public
static
UserDetails
getCurrentUser
()
{
final
Authentication
authentication
=
SecurityContextHolder
.
getContext
().
getAuthentication
();
if
(
authentication
==
null
)
{
throw
new
BadRequestException
(
HttpStatus
.
UNAUTHORIZED
,
"当前登录状态过期"
);
}
return
userDetails
;
if
(
authentication
.
getPrincipal
()
instanceof
UserDetails
)
{
UserDetails
userDetails
=
(
UserDetails
)
authentication
.
getPrincipal
();
UserDetailsService
userDetailsService
=
SpringContextHolder
.
getBean
(
UserDetailsService
.
class
);
return
userDetailsService
.
loadUserByUsername
(
userDetails
.
getUsername
());
}
throw
new
BadRequestException
(
HttpStatus
.
UNAUTHORIZED
,
"找不到当前登录的信息"
);
}
/**
* 获取系统用户名称
*
* @return 系统用户名称
*/
public
static
String
getUsername
(){
Object
obj
=
getUserDetails
();
return
new
JSONObject
(
obj
).
get
(
"username"
,
String
.
class
);
public
static
String
getCurrentUsername
()
{
final
Authentication
authentication
=
SecurityContextHolder
.
getContext
().
getAuthentication
();
if
(
authentication
==
null
)
{
throw
new
BadRequestException
(
HttpStatus
.
UNAUTHORIZED
,
"当前登录状态过期"
);
}
UserDetails
userDetails
=
(
UserDetails
)
authentication
.
getPrincipal
();
return
userDetails
.
getUsername
();
}
/**
* 获取系统用户ID
*
* @return 系统用户ID
*/
public
static
Long
getCurrentUserId
()
{
UserDetails
userDetails
=
getCurrentUser
();
return
new
JSONObject
(
new
JSONObject
(
userDetails
).
get
(
"user"
)).
get
(
"id"
,
Long
.
class
);
}
}
eladmin-logging/src/main/java/me/zhengjie/aspect/LogAspect.java
View file @
207e6fb1
...
...
@@ -76,7 +76,7 @@ public class LogAspect {
public
String
getUsername
()
{
try
{
return
SecurityUtils
.
getUsername
();
return
SecurityUtils
.
get
Current
Username
();
}
catch
(
Exception
e
){
return
""
;
}
...
...
eladmin-logging/src/main/java/me/zhengjie/rest/LogController.java
View file @
207e6fb1
...
...
@@ -58,7 +58,7 @@ public class LogController {
@ApiOperation
(
"用户日志查询"
)
public
ResponseEntity
<
Object
>
getUserLogs
(
LogQueryCriteria
criteria
,
Pageable
pageable
){
criteria
.
setLogType
(
"INFO"
);
criteria
.
setBlurry
(
SecurityUtils
.
getUsername
());
criteria
.
setBlurry
(
SecurityUtils
.
get
Current
Username
());
return
new
ResponseEntity
<>(
logService
.
queryAllByUser
(
criteria
,
pageable
),
HttpStatus
.
OK
);
}
...
...
eladmin-system/src/main/java/me/zhengjie/AppRun.java
View file @
207e6fb1
...
...
@@ -14,12 +14,12 @@ import org.springframework.web.bind.annotation.GetMapping;
import
org.springframework.web.bind.annotation.RestController
;
/**
* 开启审计功能 -> @EnableJpaAuditing
* @author Zheng Jie
* @date 2018/11/15 9:20:19
*/
@EnableAsync
@RestController
/** 开启审计功能 */
@EnableJpaAuditing
(
auditorAwareRef
=
"auditorAware"
)
@SpringBootApplication
@EnableTransactionManagement
...
...
eladmin-system/src/main/java/me/zhengjie/config/AuditorConfig.java
View file @
207e6fb1
...
...
@@ -8,7 +8,7 @@ import java.util.Optional;
/**
* @描述 : 设置审计
* @
作者
: Dong ZhaoYang
* @
author
: Dong ZhaoYang
* @日期 : 2019/10/28
* @时间 : 10:29
*/
...
...
@@ -18,11 +18,11 @@ public class AuditorConfig implements AuditorAware<String> {
/**
* 返回操作员标志信息
*
* @return
* @return
/
*/
@Override
public
Optional
<
String
>
getCurrentAuditor
()
{
// 这里应根据实际业务情况获取具体信息
return
Optional
.
of
(
SecurityUtils
.
getUsername
());
return
Optional
.
of
(
SecurityUtils
.
get
Current
Username
());
}
}
eladmin-system/src/main/java/me/zhengjie/config/DataScope.java
View file @
207e6fb1
...
...
@@ -37,7 +37,7 @@ public class DataScope {
public
Set
<
Long
>
getDeptIds
()
{
UserDto
user
=
userService
.
findByName
(
SecurityUtils
.
getUsername
());
UserDto
user
=
userService
.
findByName
(
SecurityUtils
.
get
Current
Username
());
// 用于存储部门id
Set
<
Long
>
deptIds
=
new
HashSet
<>();
...
...
eladmin-system/src/main/java/me/zhengjie/modules/mnt/service/impl/DeployServiceImpl.java
View file @
207e6fb1
...
...
@@ -202,7 +202,7 @@ public class DeployServiceImpl implements DeployService {
//还原信息入库
DeployHistory
deployHistory
=
new
DeployHistory
();
deployHistory
.
setAppName
(
appName
);
deployHistory
.
setDeployUser
(
SecurityUtils
.
getUsername
());
deployHistory
.
setDeployUser
(
SecurityUtils
.
get
Current
Username
());
deployHistory
.
setIp
(
ip
);
deployHistory
.
setDeployId
(
id
);
deployHistoryService
.
create
(
deployHistory
);
...
...
eladmin-system/src/main/java/me/zhengjie/modules/security/config/SecurityConfig.java
View file @
207e6fb1
...
...
@@ -37,6 +37,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
private
final
JwtAccessDeniedHandler
jwtAccessDeniedHandler
;
private
final
ApplicationContext
applicationContext
;
public
SecurityConfig
(
TokenProvider
tokenProvider
,
CorsFilter
corsFilter
,
JwtAuthenticationEntryPoint
authenticationErrorHandler
,
JwtAccessDeniedHandler
jwtAccessDeniedHandler
,
ApplicationContext
applicationContext
)
{
this
.
tokenProvider
=
tokenProvider
;
this
.
corsFilter
=
corsFilter
;
...
...
eladmin-system/src/main/java/me/zhengjie/modules/security/rest/AuthController.java
→
eladmin-system/src/main/java/me/zhengjie/modules/security/rest/Auth
orization
Controller.java
View file @
207e6fb1
...
...
@@ -12,8 +12,8 @@ import me.zhengjie.aop.log.Log;
import
me.zhengjie.exception.BadRequestException
;
import
me.zhengjie.modules.security.config.SecurityProperties
;
import
me.zhengjie.modules.security.security.TokenProvider
;
import
me.zhengjie.modules.security.se
curity.v
o.AuthUser
;
import
me.zhengjie.modules.security.se
curity.v
o.JwtUser
;
import
me.zhengjie.modules.security.se
rvice.dt
o.AuthUser
Dto
;
import
me.zhengjie.modules.security.se
rvice.dt
o.JwtUser
Dto
;
import
me.zhengjie.modules.security.service.OnlineUserService
;
import
me.zhengjie.utils.RedisUtils
;
import
me.zhengjie.utils.SecurityUtils
;
...
...
@@ -42,7 +42,7 @@ import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping
(
"/auth"
)
@Api
(
tags
=
"系统:系统授权接口"
)
public
class
AuthController
{
public
class
Auth
orization
Controller
{
@Value
(
"${loginCode.expiration}"
)
private
Long
expiration
;
...
...
@@ -57,7 +57,7 @@ public class AuthController {
private
final
TokenProvider
tokenProvider
;
private
final
AuthenticationManagerBuilder
authenticationManagerBuilder
;
public
AuthController
(
SecurityProperties
properties
,
RedisUtils
redisUtils
,
UserDetailsService
userDetailsService
,
OnlineUserService
onlineUserService
,
TokenProvider
tokenProvider
,
AuthenticationManagerBuilder
authenticationManagerBuilder
)
{
public
Auth
orization
Controller
(
SecurityProperties
properties
,
RedisUtils
redisUtils
,
UserDetailsService
userDetailsService
,
OnlineUserService
onlineUserService
,
TokenProvider
tokenProvider
,
AuthenticationManagerBuilder
authenticationManagerBuilder
)
{
this
.
properties
=
properties
;
this
.
redisUtils
=
redisUtils
;
this
.
userDetailsService
=
userDetailsService
;
...
...
@@ -70,7 +70,7 @@ public class AuthController {
@ApiOperation
(
"登录授权"
)
@AnonymousAccess
@PostMapping
(
value
=
"/login"
)
public
ResponseEntity
<
Object
>
login
(
@Validated
@RequestBody
AuthUser
authUser
,
HttpServletRequest
request
){
public
ResponseEntity
<
Object
>
login
(
@Validated
@RequestBody
AuthUser
Dto
authUser
,
HttpServletRequest
request
){
// 密码解密
RSA
rsa
=
new
RSA
(
privateKey
,
null
);
String
password
=
new
String
(
rsa
.
decrypt
(
authUser
.
getPassword
(),
KeyType
.
PrivateKey
));
...
...
@@ -91,13 +91,13 @@ public class AuthController {
SecurityContextHolder
.
getContext
().
setAuthentication
(
authentication
);
// 生成令牌
String
token
=
tokenProvider
.
createToken
(
authentication
);
final
JwtUser
jwtUser
=
(
JwtUser
)
authentication
.
getPrincipal
();
final
JwtUser
Dto
jwtUser
Dto
=
(
JwtUser
Dto
)
authentication
.
getPrincipal
();
// 保存在线信息
onlineUserService
.
save
(
jwtUser
,
token
,
request
);
onlineUserService
.
save
(
jwtUser
Dto
,
token
,
request
);
// 返回 token 与 用户信息
Map
<
String
,
Object
>
authInfo
=
new
HashMap
<
String
,
Object
>(
2
){{
put
(
"token"
,
properties
.
getTokenStartWith
()
+
token
);
put
(
"user"
,
jwtUser
);
put
(
"user"
,
jwtUser
Dto
);
}};
if
(
singleLogin
){
//踢掉之前已经登录的token
...
...
@@ -109,8 +109,8 @@ public class AuthController {
@ApiOperation
(
"获取用户信息"
)
@GetMapping
(
value
=
"/info"
)
public
ResponseEntity
<
Object
>
getUserInfo
(){
JwtUser
jwtUser
=
(
JwtUser
)
userDetailsService
.
loadUserByUsername
(
SecurityUtils
.
getUsername
());
return
ResponseEntity
.
ok
(
jwtUser
);
JwtUser
Dto
jwtUser
Dto
=
(
JwtUser
Dto
)
userDetailsService
.
loadUserByUsername
(
SecurityUtils
.
get
Current
Username
());
return
ResponseEntity
.
ok
(
jwtUser
Dto
);
}
@AnonymousAccess
...
...
eladmin-system/src/main/java/me/zhengjie/modules/security/security/TokenFilter.java
View file @
207e6fb1
...
...
@@ -3,7 +3,7 @@ package me.zhengjie.modules.security.security;
import
io.jsonwebtoken.ExpiredJwtException
;
import
lombok.extern.slf4j.Slf4j
;
import
me.zhengjie.modules.security.config.SecurityProperties
;
import
me.zhengjie.modules.security.se
curity.v
o.OnlineUser
;
import
me.zhengjie.modules.security.se
rvice.dt
o.OnlineUser
Dto
;
import
me.zhengjie.modules.security.service.OnlineUserService
;
import
me.zhengjie.utils.SpringContextHolder
;
import
org.springframework.security.core.Authentication
;
...
...
@@ -36,15 +36,15 @@ public class TokenFilter extends GenericFilterBean {
String
token
=
resolveToken
(
httpServletRequest
);
String
requestRri
=
httpServletRequest
.
getRequestURI
();
// 验证 token 是否存在
OnlineUser
onlineUser
=
null
;
OnlineUser
Dto
onlineUser
Dto
=
null
;
try
{
SecurityProperties
properties
=
SpringContextHolder
.
getBean
(
SecurityProperties
.
class
);
OnlineUserService
onlineUserService
=
SpringContextHolder
.
getBean
(
OnlineUserService
.
class
);
onlineUser
=
onlineUserService
.
getOne
(
properties
.
getOnlineKey
()
+
token
);
onlineUser
Dto
=
onlineUserService
.
getOne
(
properties
.
getOnlineKey
()
+
token
);
}
catch
(
ExpiredJwtException
e
)
{
log
.
error
(
e
.
getMessage
());
}
if
(
onlineUser
!=
null
&&
StringUtils
.
hasText
(
token
)
&&
tokenProvider
.
validateToken
(
token
))
{
if
(
onlineUser
Dto
!=
null
&&
StringUtils
.
hasText
(
token
)
&&
tokenProvider
.
validateToken
(
token
))
{
Authentication
authentication
=
tokenProvider
.
getAuthentication
(
token
);
SecurityContextHolder
.
getContext
().
setAuthentication
(
authentication
);
log
.
debug
(
"set Authentication to security context for '{}', uri: {}"
,
authentication
.
getName
(),
requestRri
);
...
...
eladmin-system/src/main/java/me/zhengjie/modules/security/service/OnlineUserService.java
View file @
207e6fb1
...
...
@@ -2,8 +2,8 @@ package me.zhengjie.modules.security.service;
import
lombok.extern.slf4j.Slf4j
;
import
me.zhengjie.modules.security.config.SecurityProperties
;
import
me.zhengjie.modules.security.se
curity.v
o.JwtUser
;
import
me.zhengjie.modules.security.se
curity.v
o.OnlineUser
;
import
me.zhengjie.modules.security.se
rvice.dt
o.JwtUser
Dto
;
import
me.zhengjie.modules.security.se
rvice.dt
o.OnlineUser
Dto
;
import
me.zhengjie.utils.*
;
import
org.springframework.data.domain.Pageable
;
import
org.springframework.stereotype.Service
;
...
...
@@ -30,22 +30,22 @@ public class OnlineUserService {
/**
* 保存在线用户信息
* @param jwtUser /
* @param jwtUser
Dto
/
* @param token /
* @param request /
*/
public
void
save
(
JwtUser
jwtUser
,
String
token
,
HttpServletRequest
request
){
String
job
=
jwtUser
.
getDept
()
+
"/"
+
jwtUser
.
getJob
();
public
void
save
(
JwtUser
Dto
jwtUser
Dto
,
String
token
,
HttpServletRequest
request
){
String
job
=
jwtUser
Dto
.
getUser
().
getDept
().
getName
()
+
"/"
+
jwtUserDto
.
getUser
().
getJob
().
getName
();
String
ip
=
StringUtils
.
getIp
(
request
);
String
browser
=
StringUtils
.
getBrowser
(
request
);
String
address
=
StringUtils
.
getCityInfo
(
ip
);
OnlineUser
onlineUser
=
null
;
OnlineUser
Dto
onlineUser
Dto
=
null
;
try
{
onlineUser
=
new
OnlineUser
(
jwtUser
.
getUsername
(),
jwtUser
.
getNickName
(),
job
,
browser
,
ip
,
address
,
EncryptUtils
.
desEncrypt
(
token
),
new
Date
());
onlineUser
Dto
=
new
OnlineUser
Dto
(
jwtUser
Dto
.
getUsername
(),
jwtUser
Dto
.
getUser
()
.
getNickName
(),
job
,
browser
,
ip
,
address
,
EncryptUtils
.
desEncrypt
(
token
),
new
Date
());
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
redisUtils
.
set
(
properties
.
getOnlineKey
()
+
token
,
onlineUser
,
properties
.
getTokenValidityInSeconds
()/
1000
);
redisUtils
.
set
(
properties
.
getOnlineKey
()
+
token
,
onlineUser
Dto
,
properties
.
getTokenValidityInSeconds
()/
1000
);
}
/**
...
...
@@ -55,10 +55,10 @@ public class OnlineUserService {
* @return /
*/
public
Map
<
String
,
Object
>
getAll
(
String
filter
,
Pageable
pageable
){
List
<
OnlineUser
>
onlineUsers
=
getAll
(
filter
);
List
<
OnlineUser
Dto
>
onlineUser
Dto
s
=
getAll
(
filter
);
return
PageUtil
.
toPage
(
PageUtil
.
toPage
(
pageable
.
getPageNumber
(),
pageable
.
getPageSize
(),
onlineUsers
),
onlineUsers
.
size
()
PageUtil
.
toPage
(
pageable
.
getPageNumber
(),
pageable
.
getPageSize
(),
onlineUser
Dto
s
),
onlineUser
Dto
s
.
size
()
);
}
...
...
@@ -67,28 +67,27 @@ public class OnlineUserService {
* @param filter /
* @return /
*/
public
List
<
OnlineUser
>
getAll
(
String
filter
){
public
List
<
OnlineUser
Dto
>
getAll
(
String
filter
){
List
<
String
>
keys
=
redisUtils
.
scan
(
properties
.
getOnlineKey
()
+
"*"
);
Collections
.
reverse
(
keys
);
List
<
OnlineUser
>
onlineUsers
=
new
ArrayList
<>();
List
<
OnlineUser
Dto
>
onlineUser
Dto
s
=
new
ArrayList
<>();
for
(
String
key
:
keys
)
{
OnlineUser
onlineUser
=
(
OnlineUser
)
redisUtils
.
get
(
key
);
OnlineUser
Dto
onlineUser
Dto
=
(
OnlineUser
Dto
)
redisUtils
.
get
(
key
);
if
(
StringUtils
.
isNotBlank
(
filter
)){
if
(
onlineUser
.
toString
().
contains
(
filter
)){
onlineUsers
.
add
(
onlineUser
);
if
(
onlineUser
Dto
.
toString
().
contains
(
filter
)){
onlineUser
Dto
s
.
add
(
onlineUser
Dto
);
}
}
else
{
onlineUsers
.
add
(
onlineUser
);
onlineUser
Dto
s
.
add
(
onlineUser
Dto
);
}
}
onlineUsers
.
sort
((
o1
,
o2
)
->
o2
.
getLoginTime
().
compareTo
(
o1
.
getLoginTime
()));
return
onlineUsers
;
onlineUser
Dto
s
.
sort
((
o1
,
o2
)
->
o2
.
getLoginTime
().
compareTo
(
o1
.
getLoginTime
()));
return
onlineUser
Dto
s
;
}
/**
* 踢出用户
* @param key /
* @throws Exception /
*/
public
void
kickOut
(
String
key
){
key
=
properties
.
getOnlineKey
()
+
key
;
...
...
@@ -110,9 +109,9 @@ public class OnlineUserService {
* @param response /
* @throws IOException /
*/
public
void
download
(
List
<
OnlineUser
>
all
,
HttpServletResponse
response
)
throws
IOException
{
public
void
download
(
List
<
OnlineUser
Dto
>
all
,
HttpServletResponse
response
)
throws
IOException
{
List
<
Map
<
String
,
Object
>>
list
=
new
ArrayList
<>();
for
(
OnlineUser
user
:
all
)
{
for
(
OnlineUser
Dto
user
:
all
)
{
Map
<
String
,
Object
>
map
=
new
LinkedHashMap
<>();
map
.
put
(
"用户名"
,
user
.
getUserName
());
map
.
put
(
"岗位"
,
user
.
getJob
());
...
...
@@ -130,8 +129,8 @@ public class OnlineUserService {
* @param key /
* @return /
*/
public
OnlineUser
getOne
(
String
key
)
{
return
(
OnlineUser
)
redisUtils
.
get
(
key
);
public
OnlineUser
Dto
getOne
(
String
key
)
{
return
(
OnlineUser
Dto
)
redisUtils
.
get
(
key
);
}
/**
...
...
@@ -139,14 +138,14 @@ public class OnlineUserService {
* @param userName 用户名
*/
public
void
checkLoginOnUser
(
String
userName
,
String
igoreToken
){
List
<
OnlineUser
>
onlineUsers
=
getAll
(
userName
);
if
(
onlineUsers
==
null
||
onlineUsers
.
isEmpty
()){
List
<
OnlineUser
Dto
>
onlineUser
Dto
s
=
getAll
(
userName
);
if
(
onlineUser
Dto
s
==
null
||
onlineUser
Dto
s
.
isEmpty
()){
return
;
}
for
(
OnlineUser
onlineUser
:
onlineUsers
){
if
(
onlineUser
.
getUserName
().
equals
(
userName
)){
for
(
OnlineUser
Dto
onlineUser
Dto
:
onlineUser
Dto
s
){
if
(
onlineUser
Dto
.
getUserName
().
equals
(
userName
)){
try
{
String
token
=
EncryptUtils
.
desDecrypt
(
onlineUser
.
getKey
());
String
token
=
EncryptUtils
.
desDecrypt
(
onlineUser
Dto
.
getKey
());
if
(
StringUtils
.
isNotBlank
(
igoreToken
)&&!
igoreToken
.
equals
(
token
)){
this
.
kickOut
(
token
);
}
else
if
(
StringUtils
.
isBlank
(
igoreToken
)){
...
...
eladmin-system/src/main/java/me/zhengjie/modules/security/service/UserDetailsServiceImpl.java
View file @
207e6fb1
package
me.zhengjie.modules.security.service
;
import
me.zhengjie.exception.BadRequestException
;
import
me.zhengjie.modules.security.se
curity.v
o.JwtUser
;
import
me.zhengjie.modules.security.se
rvice.dt
o.JwtUser
Dto
;
import
me.zhengjie.modules.system.service.RoleService
;
import
me.zhengjie.modules.system.service.UserService
;
import
me.zhengjie.modules.system.service.dto.*
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
org.springframework.security.core.userdetails.UserDetailsService
;
import
org.springframework.stereotype.Service
;
import
org.springframework.transaction.annotation.Propagation
;
import
org.springframework.transaction.annotation.Transactional
;
import
java.util.Optional
;
/**
* @author Zheng Jie
...
...
@@ -30,7 +28,7 @@ public class UserDetailsServiceImpl implements UserDetailsService {
}
@Override
public
UserD
etails
loadUserByUsername
(
String
username
){
public
Jwt
UserD
to
loadUserByUsername
(
String
username
){
UserDto
user
=
userService
.
findByName
(
username
);
if
(
user
==
null
)
{
throw
new
BadRequestException
(
"账号不存在"
);
...
...
@@ -38,26 +36,10 @@ public class UserDetailsServiceImpl implements UserDetailsService {
if
(!
user
.
getEnabled
())
{
throw
new
BadRequestException
(
"账号未激活"
);
}
return
createJwtUser
(
user
);
return
new
JwtUserDto
(
user
,
roleService
.
mapToGrantedAuthorities
(
user
)
);
}
}
private
UserDetails
createJwtUser
(
UserDto
user
)
{
return
new
JwtUser
(
user
.
getId
(),
user
.
getUsername
(),
user
.
getNickName
(),
user
.
getSex
(),
user
.
getPassword
(),
user
.
getAvatar
(),
user
.
getEmail
(),
user
.
getPhone
(),
Optional
.
ofNullable
(
user
.
getDept
()).
map
(
DeptSmallDto:
:
getName
).
orElse
(
null
),
Optional
.
ofNullable
(
user
.
getJob
()).
map
(
JobSmallDto:
:
getName
).
orElse
(
null
),
roleService
.
mapToGrantedAuthorities
(
user
),
user
.
getEnabled
(),
user
.
getCreateTime
(),
user
.
getLastPasswordResetTime
()
);
}
}
eladmin-system/src/main/java/me/zhengjie/modules/security/se
curity/v
o/AuthUser.java
→
eladmin-system/src/main/java/me/zhengjie/modules/security/se
rvice/dt
o/AuthUser
Dto
.java
View file @
207e6fb1
package
me.zhengjie.modules.security.se
curity.v
o
;
package
me.zhengjie.modules.security.se
rvice.dt
o
;
import
lombok.Getter
;
import
lombok.Setter
;
...
...
@@ -11,7 +11,7 @@ import javax.validation.constraints.NotBlank;
*/
@Getter
@Setter
public
class
AuthUser
{
public
class
AuthUser
Dto
{
@NotBlank
private
String
username
;
...
...
eladmin-system/src/main/java/me/zhengjie/modules/security/se
curity/v
o/JwtUser.java
→
eladmin-system/src/main/java/me/zhengjie/modules/security/se
rvice/dt
o/JwtUser
Dto
.java
View file @
207e6fb1
package
me.zhengjie.modules.security.se
curity.v
o
;
package
me.zhengjie.modules.security.se
rvice.dt
o
;
import
com.fasterxml.jackson.annotation.JsonIgnore
;
import
lombok.AllArgsConstructor
;
import
lombok.Getter
;
import
me.zhengjie.modules.system.service.dto.UserDto
;
import
org.springframework.security.core.GrantedAuthority
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
java.sql.Timestamp
;
import
java.util.Collection
;
import
java.util.Date
;
import
java.util.List
;
import
java.util.Set
;
import
java.util.stream.Collectors
;
/**
...
...
@@ -16,38 +16,28 @@ import java.util.stream.Collectors;
*/
@Getter
@AllArgsConstructor
public
class
JwtUser
implements
UserDetails
{
public
class
JwtUser
Dto
implements
UserDetails
{
private
final
Long
id
;
private
final
String
username
;
private
final
String
nickName
;
private
final
String
sex
;
private
UserDto
user
;
@JsonIgnore
private
final
String
password
;
private
final
String
avatar
;
private
final
String
email
;
private
final
String
phone
;
private
final
String
dept
;
private
List
<
GrantedAuthority
>
authorities
;
private
final
String
job
;
public
Set
<
String
>
getRoles
()
{
return
authorities
.
stream
().
map
(
GrantedAuthority:
:
getAuthority
).
collect
(
Collectors
.
toSet
());
}
@Override
@JsonIgnore
private
final
Collection
<
GrantedAuthority
>
authorities
;
private
final
boolean
enabled
;
private
Timestamp
createTime
;
public
String
getPassword
()
{
return
user
.
getPassword
();
}
@Override
@JsonIgnore
private
final
Date
lastPasswordResetDate
;
public
String
getUsername
()
{
return
user
.
getUsername
();
}
@JsonIgnore
@Override
...
...
@@ -67,18 +57,9 @@ public class JwtUser implements UserDetails {
return
true
;
}
@JsonIgnore
@Override
public
String
getPassword
()
{
return
password
;
}
@Override
@JsonIgnore
public
boolean
isEnabled
()
{
return
enabled
;
}
public
Collection
getRoles
()
{
return
authorities
.
stream
().
map
(
GrantedAuthority:
:
getAuthority
).
collect
(
Collectors
.
toSet
());
return
user
.
getEnabled
();
}
}
eladmin-system/src/main/java/me/zhengjie/modules/security/se
curity/v
o/OnlineUser.java
→
eladmin-system/src/main/java/me/zhengjie/modules/security/se
rvice/dt
o/OnlineUser
Dto
.java
View file @
207e6fb1
package
me.zhengjie.modules.security.se
curity.v
o
;
package
me.zhengjie.modules.security.se
rvice.dt
o
;
import
lombok.AllArgsConstructor
;
import
lombok.Data
;
import
lombok.NoArgsConstructor
;
import
java.util.Date
;
/**
* 在线用户
* @author Zheng Jie
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public
class
OnlineUser
{
public
class
OnlineUser
Dto
{
/**
* 用户名
*/
private
String
userName
;
/**
* 昵称
*/
private
String
nickName
;
/**
* 岗位
*/
private
String
job
;
/**
* 浏览器
*/
private
String
browser
;
/**
* IP
*/
private
String
ip
;
/**
* 地址
*/
private
String
address
;
/**
* token
*/
private
String
key
;
/**
* 登录时间
*/
private
Date
loginTime
;
...
...
eladmin-system/src/main/java/me/zhengjie/modules/system/rest/MenuController.java
View file @
207e6fb1
...
...
@@ -59,7 +59,7 @@ public class MenuController {
@ApiOperation
(
"获取前端所需菜单"
)
@GetMapping
(
value
=
"/build"
)
public
ResponseEntity
<
Object
>
buildMenus
(){
UserDto
user
=
userService
.
findByName
(
SecurityUtils
.
getUsername
());
UserDto
user
=
userService
.
findByName
(
SecurityUtils
.
get
Current
Username
());
List
<
MenuDto
>
menuDtoList
=
menuService
.
findByRoles
(
roleService
.
findByUsersId
(
user
.
getId
()));
List
<
MenuDto
>
menuDtos
=
(
List
<
MenuDto
>)
menuService
.
buildTree
(
menuDtoList
).
get
(
"content"
);
return
new
ResponseEntity
<>(
menuService
.
buildMenus
(
menuDtos
),
HttpStatus
.
OK
);
...
...
eladmin-system/src/main/java/me/zhengjie/modules/system/rest/RoleController.java
View file @
207e6fb1
...
...
@@ -139,7 +139,7 @@ public class RoleController {
* @return /
*/
private
int
getLevels
(
Integer
level
){
UserDto
user
=
userService
.
findByName
(
SecurityUtils
.
getUsername
());
UserDto
user
=
userService
.
findByName
(
SecurityUtils
.
get
Current
Username
());
List
<
Integer
>
levels
=
roleService
.
findByUsersId
(
user
.
getId
()).
stream
().
map
(
RoleSmallDto:
:
getLevel
).
collect
(
Collectors
.
toList
());
int
min
=
Collections
.
min
(
levels
);
if
(
level
!=
null
){
...
...
eladmin-system/src/main/java/me/zhengjie/modules/system/rest/UserController.java
View file @
207e6fb1
...
...
@@ -128,7 +128,7 @@ public class UserController {
@ApiOperation
(
"修改用户:个人中心"
)
@PutMapping
(
value
=
"center"
)
public
ResponseEntity
<
Object
>
center
(
@Validated
(
User
.
Update
.
class
)
@RequestBody
User
resources
){
UserDto
userDto
=
userService
.
findByName
(
SecurityUtils
.
getUsername
());
UserDto
userDto
=
userService
.
findByName
(
SecurityUtils
.
get
Current
Username
());
if
(!
resources
.
getId
().
equals
(
userDto
.
getId
())){
throw
new
BadRequestException
(
"不能修改他人资料"
);
}
...
...
@@ -141,12 +141,12 @@ public class UserController {
@DeleteMapping
@PreAuthorize
(
"@el.check('user:del')"
)
public
ResponseEntity
<
Object
>
delete
(
@RequestBody
Set
<
Long
>
ids
){
UserDto
user
=
userService
.
findByName
(
SecurityUtils
.
getUsername
());
UserDto
user
=
userService
.
findByName
(
SecurityUtils
.
get
Current
Username
());
for
(
Long
id
:
ids
)
{
Integer
currentLevel
=
Collections
.
min
(
roleService
.
findByUsersId
(
user
.
getId
()).
stream
().
map
(
RoleSmallDto:
:
getLevel
).
collect
(
Collectors
.
toList
()));
Integer
optLevel
=
Collections
.
min
(
roleService
.
findByUsersId
(
id
).
stream
().
map
(
RoleSmallDto:
:
getLevel
).
collect
(
Collectors
.
toList
()));
if
(
currentLevel
>
optLevel
)
{
throw
new
BadRequestException
(
"角色权限不足,不能删除:"
+
userService
.
findByName
(
SecurityUtils
.
getUsername
()).
getUsername
());
throw
new
BadRequestException
(
"角色权限不足,不能删除:"
+
userService
.
findByName
(
SecurityUtils
.
get
Current
Username
()).
getUsername
());
}
}
userService
.
delete
(
ids
);
...
...
@@ -160,7 +160,7 @@ public class UserController {
RSA
rsa
=
new
RSA
(
privateKey
,
null
);
String
oldPass
=
new
String
(
rsa
.
decrypt
(
passVo
.
getOldPass
(),
KeyType
.
PrivateKey
));
String
newPass
=
new
String
(
rsa
.
decrypt
(
passVo
.
getNewPass
(),
KeyType
.
PrivateKey
));
UserDto
user
=
userService
.
findByName
(
SecurityUtils
.
getUsername
());
UserDto
user
=
userService
.
findByName
(
SecurityUtils
.
get
Current
Username
());
if
(!
passwordEncoder
.
matches
(
oldPass
,
user
.
getPassword
())){
throw
new
BadRequestException
(
"修改失败,旧密码错误"
);
}
...
...
@@ -185,7 +185,7 @@ public class UserController {
// 密码解密
RSA
rsa
=
new
RSA
(
privateKey
,
null
);
String
password
=
new
String
(
rsa
.
decrypt
(
user
.
getPassword
(),
KeyType
.
PrivateKey
));
UserDto
userDto
=
userService
.
findByName
(
SecurityUtils
.
getUsername
());
UserDto
userDto
=
userService
.
findByName
(
SecurityUtils
.
get
Current
Username
());
if
(!
passwordEncoder
.
matches
(
password
,
userDto
.
getPassword
())){
throw
new
BadRequestException
(
"密码错误"
);
}
...
...
@@ -200,7 +200,7 @@ public class UserController {
* @param resources /
*/
private
void
checkLevel
(
User
resources
)
{
UserDto
user
=
userService
.
findByName
(
SecurityUtils
.
getUsername
());
UserDto
user
=
userService
.
findByName
(
SecurityUtils
.
get
Current
Username
());
Integer
currentLevel
=
Collections
.
min
(
roleService
.
findByUsersId
(
user
.
getId
()).
stream
().
map
(
RoleSmallDto:
:
getLevel
).
collect
(
Collectors
.
toList
()));
Integer
optLevel
=
roleService
.
findByRoles
(
resources
.
getRoles
());
if
(
currentLevel
>
optLevel
)
{
...
...
eladmin-system/src/main/java/me/zhengjie/modules/system/service/RoleService.java
View file @
207e6fb1
...
...
@@ -7,10 +7,8 @@ import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import
me.zhengjie.modules.system.service.dto.UserDto
;
import
org.springframework.data.domain.Pageable
;
import
org.springframework.security.core.GrantedAuthority
;
import
javax.servlet.http.HttpServletResponse
;
import
java.io.IOException
;
import
java.util.Collection
;
import
java.util.List
;
import
java.util.Set
;
...
...
@@ -108,5 +106,5 @@ public interface RoleService {
* @param user 用户信息
* @return 权限信息
*/
Collection
<
GrantedAuthority
>
mapToGrantedAuthorities
(
UserDto
user
);
List
<
GrantedAuthority
>
mapToGrantedAuthorities
(
UserDto
user
);
}
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