SecurityUtils 加入获取当前登录用户ID方法,Security 结构调整

pull/308/head
Elune 2020-03-10 13:49:44 +08:00
parent 4054ac7bc8
commit 207e6fb1df
25 changed files with 159 additions and 145 deletions

View File

@ -15,7 +15,7 @@ public class ElPermissionConfig {
public Boolean check(String ...permissions){ public Boolean check(String ...permissions){
// 获取当前用户的所有权限 // 获取当前用户的所有权限
List<String> elPermissions = SecurityUtils.getUserDetails().getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()); List<String> elPermissions = SecurityUtils.getCurrentUser().getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
// 判断当前用户的所有权限是否包含接口上定义的权限 // 判断当前用户的所有权限是否包含接口上定义的权限
return elPermissions.contains("admin") || Arrays.stream(permissions).anyMatch(elPermissions::contains); return elPermissions.contains("admin") || Arrays.stream(permissions).anyMatch(elPermissions::contains);
} }

View File

@ -1,34 +1,60 @@
package me.zhengjie.utils; package me.zhengjie.utils;
import cn.hutool.json.JSONObject; import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.exception.BadRequestException; import me.zhengjie.exception.BadRequestException;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
/** /**
* *
* @author Zheng Jie * @author Zheng Jie
* @date 2019-01-17 * @date 2019-01-17
*/ */
@Slf4j
public class SecurityUtils { public class SecurityUtils {
public static UserDetails getUserDetails() { /**
UserDetails userDetails; *
try { * @return UserDetails
userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); */
} catch (Exception e) { public static UserDetails getCurrentUser() {
throw new BadRequestException(HttpStatus.UNAUTHORIZED, "登录状态过期"); 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 * @return
*/ */
public static String getUsername(){ public static String getCurrentUsername() {
Object obj = getUserDetails(); final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return new JSONObject(obj).get("username", String.class); 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);
} }
} }

View File

@ -76,7 +76,7 @@ public class LogAspect {
public String getUsername() { public String getUsername() {
try { try {
return SecurityUtils.getUsername(); return SecurityUtils.getCurrentUsername();
}catch (Exception e){ }catch (Exception e){
return ""; return "";
} }

View File

@ -58,7 +58,7 @@ public class LogController {
@ApiOperation("用户日志查询") @ApiOperation("用户日志查询")
public ResponseEntity<Object> getUserLogs(LogQueryCriteria criteria, Pageable pageable){ public ResponseEntity<Object> getUserLogs(LogQueryCriteria criteria, Pageable pageable){
criteria.setLogType("INFO"); criteria.setLogType("INFO");
criteria.setBlurry(SecurityUtils.getUsername()); criteria.setBlurry(SecurityUtils.getCurrentUsername());
return new ResponseEntity<>(logService.queryAllByUser(criteria,pageable), HttpStatus.OK); return new ResponseEntity<>(logService.queryAllByUser(criteria,pageable), HttpStatus.OK);
} }

View File

@ -14,12 +14,12 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
/** /**
* -> @EnableJpaAuditing
* @author Zheng Jie * @author Zheng Jie
* @date 2018/11/15 9:20:19 * @date 2018/11/15 9:20:19
*/ */
@EnableAsync @EnableAsync
@RestController @RestController
/** 开启审计功能 */
@EnableJpaAuditing(auditorAwareRef = "auditorAware") @EnableJpaAuditing(auditorAwareRef = "auditorAware")
@SpringBootApplication @SpringBootApplication
@EnableTransactionManagement @EnableTransactionManagement

View File

@ -8,7 +8,7 @@ import java.util.Optional;
/** /**
* @ : * @ :
* @ : Dong ZhaoYang * @author : Dong ZhaoYang
* @ : 2019/10/28 * @ : 2019/10/28
* @ : 10:29 * @ : 10:29
*/ */
@ -18,11 +18,11 @@ public class AuditorConfig implements AuditorAware<String> {
/** /**
* *
* *
* @return * @return /
*/ */
@Override @Override
public Optional<String> getCurrentAuditor() { public Optional<String> getCurrentAuditor() {
// 这里应根据实际业务情况获取具体信息 // 这里应根据实际业务情况获取具体信息
return Optional.of(SecurityUtils.getUsername()); return Optional.of(SecurityUtils.getCurrentUsername());
} }
} }

View File

@ -37,7 +37,7 @@ public class DataScope {
public Set<Long> getDeptIds() { public Set<Long> getDeptIds() {
UserDto user = userService.findByName(SecurityUtils.getUsername()); UserDto user = userService.findByName(SecurityUtils.getCurrentUsername());
// 用于存储部门id // 用于存储部门id
Set<Long> deptIds = new HashSet<>(); Set<Long> deptIds = new HashSet<>();

View File

@ -202,7 +202,7 @@ public class DeployServiceImpl implements DeployService {
//还原信息入库 //还原信息入库
DeployHistory deployHistory = new DeployHistory(); DeployHistory deployHistory = new DeployHistory();
deployHistory.setAppName(appName); deployHistory.setAppName(appName);
deployHistory.setDeployUser(SecurityUtils.getUsername()); deployHistory.setDeployUser(SecurityUtils.getCurrentUsername());
deployHistory.setIp(ip); deployHistory.setIp(ip);
deployHistory.setDeployId(id); deployHistory.setDeployId(id);
deployHistoryService.create(deployHistory); deployHistoryService.create(deployHistory);

View File

@ -37,6 +37,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final JwtAccessDeniedHandler jwtAccessDeniedHandler; private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
private final ApplicationContext applicationContext; private final ApplicationContext applicationContext;
public SecurityConfig(TokenProvider tokenProvider, CorsFilter corsFilter, JwtAuthenticationEntryPoint authenticationErrorHandler, JwtAccessDeniedHandler jwtAccessDeniedHandler, ApplicationContext applicationContext) { public SecurityConfig(TokenProvider tokenProvider, CorsFilter corsFilter, JwtAuthenticationEntryPoint authenticationErrorHandler, JwtAccessDeniedHandler jwtAccessDeniedHandler, ApplicationContext applicationContext) {
this.tokenProvider = tokenProvider; this.tokenProvider = tokenProvider;
this.corsFilter = corsFilter; this.corsFilter = corsFilter;

View File

@ -12,8 +12,8 @@ import me.zhengjie.aop.log.Log;
import me.zhengjie.exception.BadRequestException; import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.security.config.SecurityProperties; import me.zhengjie.modules.security.config.SecurityProperties;
import me.zhengjie.modules.security.security.TokenProvider; import me.zhengjie.modules.security.security.TokenProvider;
import me.zhengjie.modules.security.security.vo.AuthUser; import me.zhengjie.modules.security.service.dto.AuthUserDto;
import me.zhengjie.modules.security.security.vo.JwtUser; import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.security.service.OnlineUserService; import me.zhengjie.modules.security.service.OnlineUserService;
import me.zhengjie.utils.RedisUtils; import me.zhengjie.utils.RedisUtils;
import me.zhengjie.utils.SecurityUtils; import me.zhengjie.utils.SecurityUtils;
@ -42,7 +42,7 @@ import java.util.concurrent.TimeUnit;
@RestController @RestController
@RequestMapping("/auth") @RequestMapping("/auth")
@Api(tags = "系统:系统授权接口") @Api(tags = "系统:系统授权接口")
public class AuthController { public class AuthorizationController {
@Value("${loginCode.expiration}") @Value("${loginCode.expiration}")
private Long expiration; private Long expiration;
@ -57,7 +57,7 @@ public class AuthController {
private final TokenProvider tokenProvider; private final TokenProvider tokenProvider;
private final AuthenticationManagerBuilder authenticationManagerBuilder; private final AuthenticationManagerBuilder authenticationManagerBuilder;
public AuthController(SecurityProperties properties, RedisUtils redisUtils, UserDetailsService userDetailsService, OnlineUserService onlineUserService, TokenProvider tokenProvider, AuthenticationManagerBuilder authenticationManagerBuilder) { public AuthorizationController(SecurityProperties properties, RedisUtils redisUtils, UserDetailsService userDetailsService, OnlineUserService onlineUserService, TokenProvider tokenProvider, AuthenticationManagerBuilder authenticationManagerBuilder) {
this.properties = properties; this.properties = properties;
this.redisUtils = redisUtils; this.redisUtils = redisUtils;
this.userDetailsService = userDetailsService; this.userDetailsService = userDetailsService;
@ -70,7 +70,7 @@ public class AuthController {
@ApiOperation("登录授权") @ApiOperation("登录授权")
@AnonymousAccess @AnonymousAccess
@PostMapping(value = "/login") @PostMapping(value = "/login")
public ResponseEntity<Object> login(@Validated @RequestBody AuthUser authUser, HttpServletRequest request){ public ResponseEntity<Object> login(@Validated @RequestBody AuthUserDto authUser, HttpServletRequest request){
// 密码解密 // 密码解密
RSA rsa = new RSA(privateKey, null); RSA rsa = new RSA(privateKey, null);
String password = new String(rsa.decrypt(authUser.getPassword(), KeyType.PrivateKey)); String password = new String(rsa.decrypt(authUser.getPassword(), KeyType.PrivateKey));
@ -91,13 +91,13 @@ public class AuthController {
SecurityContextHolder.getContext().setAuthentication(authentication); SecurityContextHolder.getContext().setAuthentication(authentication);
// 生成令牌 // 生成令牌
String token = tokenProvider.createToken(authentication); String token = tokenProvider.createToken(authentication);
final JwtUser jwtUser = (JwtUser) authentication.getPrincipal(); final JwtUserDto jwtUserDto = (JwtUserDto) authentication.getPrincipal();
// 保存在线信息 // 保存在线信息
onlineUserService.save(jwtUser, token, request); onlineUserService.save(jwtUserDto, token, request);
// 返回 token 与 用户信息 // 返回 token 与 用户信息
Map<String,Object> authInfo = new HashMap<String,Object>(2){{ Map<String,Object> authInfo = new HashMap<String,Object>(2){{
put("token", properties.getTokenStartWith() + token); put("token", properties.getTokenStartWith() + token);
put("user", jwtUser); put("user", jwtUserDto);
}}; }};
if(singleLogin){ if(singleLogin){
//踢掉之前已经登录的token //踢掉之前已经登录的token
@ -109,8 +109,8 @@ public class AuthController {
@ApiOperation("获取用户信息") @ApiOperation("获取用户信息")
@GetMapping(value = "/info") @GetMapping(value = "/info")
public ResponseEntity<Object> getUserInfo(){ public ResponseEntity<Object> getUserInfo(){
JwtUser jwtUser = (JwtUser)userDetailsService.loadUserByUsername(SecurityUtils.getUsername()); JwtUserDto jwtUserDto = (JwtUserDto)userDetailsService.loadUserByUsername(SecurityUtils.getCurrentUsername());
return ResponseEntity.ok(jwtUser); return ResponseEntity.ok(jwtUserDto);
} }
@AnonymousAccess @AnonymousAccess

View File

@ -3,7 +3,7 @@ package me.zhengjie.modules.security.security;
import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.security.config.SecurityProperties; import me.zhengjie.modules.security.config.SecurityProperties;
import me.zhengjie.modules.security.security.vo.OnlineUser; 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 me.zhengjie.utils.SpringContextHolder;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
@ -36,15 +36,15 @@ public class TokenFilter extends GenericFilterBean {
String token = resolveToken(httpServletRequest); String token = resolveToken(httpServletRequest);
String requestRri = httpServletRequest.getRequestURI(); String requestRri = httpServletRequest.getRequestURI();
// 验证 token 是否存在 // 验证 token 是否存在
OnlineUser onlineUser = null; OnlineUserDto onlineUserDto = null;
try { try {
SecurityProperties properties = SpringContextHolder.getBean(SecurityProperties.class); SecurityProperties properties = SpringContextHolder.getBean(SecurityProperties.class);
OnlineUserService onlineUserService = SpringContextHolder.getBean(OnlineUserService.class); OnlineUserService onlineUserService = SpringContextHolder.getBean(OnlineUserService.class);
onlineUser = 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());
} }
if (onlineUser != null && StringUtils.hasText(token) && tokenProvider.validateToken(token)) { if (onlineUserDto != null && StringUtils.hasText(token) && tokenProvider.validateToken(token)) {
Authentication authentication = tokenProvider.getAuthentication(token); Authentication authentication = tokenProvider.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(authentication); SecurityContextHolder.getContext().setAuthentication(authentication);
log.debug("set Authentication to security context for '{}', uri: {}", authentication.getName(), requestRri); log.debug("set Authentication to security context for '{}', uri: {}", authentication.getName(), requestRri);

View File

@ -2,8 +2,8 @@ package me.zhengjie.modules.security.service;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.security.config.SecurityProperties; import me.zhengjie.modules.security.config.SecurityProperties;
import me.zhengjie.modules.security.security.vo.JwtUser; import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.security.security.vo.OnlineUser; import me.zhengjie.modules.security.service.dto.OnlineUserDto;
import me.zhengjie.utils.*; import me.zhengjie.utils.*;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -30,22 +30,22 @@ public class OnlineUserService {
/** /**
* 线 * 线
* @param jwtUser / * @param jwtUserDto /
* @param token / * @param token /
* @param request / * @param request /
*/ */
public void save(JwtUser jwtUser, String token, HttpServletRequest request){ public void save(JwtUserDto jwtUserDto, String token, HttpServletRequest request){
String job = jwtUser.getDept() + "/" + jwtUser.getJob(); String job = jwtUserDto.getUser().getDept().getName() + "/" + jwtUserDto.getUser().getJob().getName();
String ip = StringUtils.getIp(request); String ip = StringUtils.getIp(request);
String browser = StringUtils.getBrowser(request); String browser = StringUtils.getBrowser(request);
String address = StringUtils.getCityInfo(ip); String address = StringUtils.getCityInfo(ip);
OnlineUser onlineUser = null; OnlineUserDto onlineUserDto = null;
try { try {
onlineUser = new OnlineUser(jwtUser.getUsername(), jwtUser.getNickName(), job, browser , ip, address, EncryptUtils.desEncrypt(token), new Date()); onlineUserDto = new OnlineUserDto(jwtUserDto.getUsername(), jwtUserDto.getUser().getNickName(), job, browser , ip, address, EncryptUtils.desEncrypt(token), new Date());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
redisUtils.set(properties.getOnlineKey() + token, onlineUser, properties.getTokenValidityInSeconds()/1000); redisUtils.set(properties.getOnlineKey() + token, onlineUserDto, properties.getTokenValidityInSeconds()/1000);
} }
/** /**
@ -55,10 +55,10 @@ public class OnlineUserService {
* @return / * @return /
*/ */
public Map<String,Object> getAll(String filter, Pageable pageable){ public Map<String,Object> getAll(String filter, Pageable pageable){
List<OnlineUser> onlineUsers = getAll(filter); List<OnlineUserDto> onlineUserDtos = getAll(filter);
return PageUtil.toPage( return PageUtil.toPage(
PageUtil.toPage(pageable.getPageNumber(),pageable.getPageSize(),onlineUsers), PageUtil.toPage(pageable.getPageNumber(),pageable.getPageSize(), onlineUserDtos),
onlineUsers.size() onlineUserDtos.size()
); );
} }
@ -67,28 +67,27 @@ public class OnlineUserService {
* @param filter / * @param filter /
* @return / * @return /
*/ */
public List<OnlineUser> getAll(String filter){ public List<OnlineUserDto> getAll(String filter){
List<String> keys = redisUtils.scan(properties.getOnlineKey() + "*"); List<String> keys = redisUtils.scan(properties.getOnlineKey() + "*");
Collections.reverse(keys); Collections.reverse(keys);
List<OnlineUser> onlineUsers = new ArrayList<>(); List<OnlineUserDto> onlineUserDtos = new ArrayList<>();
for (String key : keys) { for (String key : keys) {
OnlineUser onlineUser = (OnlineUser) redisUtils.get(key); OnlineUserDto onlineUserDto = (OnlineUserDto) redisUtils.get(key);
if(StringUtils.isNotBlank(filter)){ if(StringUtils.isNotBlank(filter)){
if(onlineUser.toString().contains(filter)){ if(onlineUserDto.toString().contains(filter)){
onlineUsers.add(onlineUser); onlineUserDtos.add(onlineUserDto);
} }
} else { } else {
onlineUsers.add(onlineUser); onlineUserDtos.add(onlineUserDto);
} }
} }
onlineUsers.sort((o1, o2) -> o2.getLoginTime().compareTo(o1.getLoginTime())); onlineUserDtos.sort((o1, o2) -> o2.getLoginTime().compareTo(o1.getLoginTime()));
return onlineUsers; return onlineUserDtos;
} }
/** /**
* *
* @param key / * @param key /
* @throws Exception /
*/ */
public void kickOut(String key){ public void kickOut(String key){
key = properties.getOnlineKey() + key; key = properties.getOnlineKey() + key;
@ -110,9 +109,9 @@ public class OnlineUserService {
* @param response / * @param response /
* @throws IOException / * @throws IOException /
*/ */
public void download(List<OnlineUser> all, HttpServletResponse response) throws IOException { public void download(List<OnlineUserDto> all, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>(); List<Map<String, Object>> list = new ArrayList<>();
for (OnlineUser user : all) { for (OnlineUserDto user : all) {
Map<String,Object> map = new LinkedHashMap<>(); Map<String,Object> map = new LinkedHashMap<>();
map.put("用户名", user.getUserName()); map.put("用户名", user.getUserName());
map.put("岗位", user.getJob()); map.put("岗位", user.getJob());
@ -130,8 +129,8 @@ public class OnlineUserService {
* @param key / * @param key /
* @return / * @return /
*/ */
public OnlineUser getOne(String key) { public OnlineUserDto getOne(String key) {
return (OnlineUser)redisUtils.get(key); return (OnlineUserDto)redisUtils.get(key);
} }
/** /**
@ -139,14 +138,14 @@ public class OnlineUserService {
* @param userName * @param userName
*/ */
public void checkLoginOnUser(String userName, String igoreToken){ public void checkLoginOnUser(String userName, String igoreToken){
List<OnlineUser> onlineUsers = getAll(userName); List<OnlineUserDto> onlineUserDtos = getAll(userName);
if(onlineUsers ==null || onlineUsers.isEmpty()){ if(onlineUserDtos ==null || onlineUserDtos.isEmpty()){
return; return;
} }
for(OnlineUser onlineUser:onlineUsers){ for(OnlineUserDto onlineUserDto : onlineUserDtos){
if(onlineUser.getUserName().equals(userName)){ if(onlineUserDto.getUserName().equals(userName)){
try { try {
String token =EncryptUtils.desDecrypt(onlineUser.getKey()); String token =EncryptUtils.desDecrypt(onlineUserDto.getKey());
if(StringUtils.isNotBlank(igoreToken)&&!igoreToken.equals(token)){ if(StringUtils.isNotBlank(igoreToken)&&!igoreToken.equals(token)){
this.kickOut(token); this.kickOut(token);
}else if(StringUtils.isBlank(igoreToken)){ }else if(StringUtils.isBlank(igoreToken)){

View File

@ -1,16 +1,14 @@
package me.zhengjie.modules.security.service; package me.zhengjie.modules.security.service;
import me.zhengjie.exception.BadRequestException; import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.security.security.vo.JwtUser; import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.system.service.RoleService; import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.UserService; import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.*; import me.zhengjie.modules.system.service.dto.*;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/** /**
* @author Zheng Jie * @author Zheng Jie
@ -30,7 +28,7 @@ public class UserDetailsServiceImpl implements UserDetailsService {
} }
@Override @Override
public UserDetails loadUserByUsername(String username){ public JwtUserDto loadUserByUsername(String username){
UserDto user = userService.findByName(username); UserDto user = userService.findByName(username);
if (user == null) { if (user == null) {
throw new BadRequestException("账号不存在"); throw new BadRequestException("账号不存在");
@ -38,26 +36,10 @@ public class UserDetailsServiceImpl implements UserDetailsService {
if (!user.getEnabled()) { if (!user.getEnabled()) {
throw new BadRequestException("账号未激活"); 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()
);
}
} }

View File

@ -1,4 +1,4 @@
package me.zhengjie.modules.security.security.vo; package me.zhengjie.modules.security.service.dto;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
@ -11,7 +11,7 @@ import javax.validation.constraints.NotBlank;
*/ */
@Getter @Getter
@Setter @Setter
public class AuthUser { public class AuthUserDto {
@NotBlank @NotBlank
private String username; private String username;

View File

@ -1,13 +1,13 @@
package me.zhengjie.modules.security.security.vo; package me.zhengjie.modules.security.service.dto;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
import me.zhengjie.modules.system.service.dto.UserDto;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import java.sql.Timestamp; import java.util.List;
import java.util.Collection; import java.util.Set;
import java.util.Date;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
@ -16,38 +16,28 @@ import java.util.stream.Collectors;
*/ */
@Getter @Getter
@AllArgsConstructor @AllArgsConstructor
public class JwtUser implements UserDetails { public class JwtUserDto implements UserDetails {
private final Long id; private UserDto user;
private final String username;
private final String nickName;
private final String sex;
@JsonIgnore @JsonIgnore
private final String password; private List<GrantedAuthority> authorities;
private final String avatar; public Set<String> getRoles() {
return authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
private final String email; }
private final String phone;
private final String dept;
private final String job;
@Override
@JsonIgnore @JsonIgnore
private final Collection<GrantedAuthority> authorities; public String getPassword() {
return user.getPassword();
private final boolean enabled; }
private Timestamp createTime;
@Override
@JsonIgnore @JsonIgnore
private final Date lastPasswordResetDate; public String getUsername() {
return user.getUsername();
}
@JsonIgnore @JsonIgnore
@Override @Override
@ -67,18 +57,9 @@ public class JwtUser implements UserDetails {
return true; return true;
} }
@Override
@JsonIgnore @JsonIgnore
@Override
public String getPassword() {
return password;
}
@Override
public boolean isEnabled() { public boolean isEnabled() {
return enabled; return user.getEnabled();
}
public Collection getRoles() {
return authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
} }
} }

View File

@ -1,33 +1,57 @@
package me.zhengjie.modules.security.security.vo; package me.zhengjie.modules.security.service.dto;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import java.util.Date; import java.util.Date;
/** /**
* 线
* @author Zheng Jie * @author Zheng Jie
*/ */
@Data @Data
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
public class OnlineUser { public class OnlineUserDto {
/**
*
*/
private String userName; private String userName;
/**
*
*/
private String nickName; private String nickName;
/**
*
*/
private String job; private String job;
/**
*
*/
private String browser; private String browser;
/**
* IP
*/
private String ip; private String ip;
/**
*
*/
private String address; private String address;
/**
* token
*/
private String key; private String key;
/**
*
*/
private Date loginTime; private Date loginTime;

View File

@ -59,7 +59,7 @@ public class MenuController {
@ApiOperation("获取前端所需菜单") @ApiOperation("获取前端所需菜单")
@GetMapping(value = "/build") @GetMapping(value = "/build")
public ResponseEntity<Object> buildMenus(){ public ResponseEntity<Object> buildMenus(){
UserDto user = userService.findByName(SecurityUtils.getUsername()); UserDto user = userService.findByName(SecurityUtils.getCurrentUsername());
List<MenuDto> menuDtoList = menuService.findByRoles(roleService.findByUsersId(user.getId())); List<MenuDto> menuDtoList = menuService.findByRoles(roleService.findByUsersId(user.getId()));
List<MenuDto> menuDtos = (List<MenuDto>) menuService.buildTree(menuDtoList).get("content"); List<MenuDto> menuDtos = (List<MenuDto>) menuService.buildTree(menuDtoList).get("content");
return new ResponseEntity<>(menuService.buildMenus(menuDtos),HttpStatus.OK); return new ResponseEntity<>(menuService.buildMenus(menuDtos),HttpStatus.OK);

View File

@ -139,7 +139,7 @@ public class RoleController {
* @return / * @return /
*/ */
private int getLevels(Integer level){ private int getLevels(Integer level){
UserDto user = userService.findByName(SecurityUtils.getUsername()); UserDto user = userService.findByName(SecurityUtils.getCurrentUsername());
List<Integer> levels = roleService.findByUsersId(user.getId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()); List<Integer> levels = roleService.findByUsersId(user.getId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
int min = Collections.min(levels); int min = Collections.min(levels);
if(level != null){ if(level != null){

View File

@ -128,7 +128,7 @@ public class UserController {
@ApiOperation("修改用户:个人中心") @ApiOperation("修改用户:个人中心")
@PutMapping(value = "center") @PutMapping(value = "center")
public ResponseEntity<Object> center(@Validated(User.Update.class) @RequestBody User resources){ public ResponseEntity<Object> center(@Validated(User.Update.class) @RequestBody User resources){
UserDto userDto = userService.findByName(SecurityUtils.getUsername()); UserDto userDto = userService.findByName(SecurityUtils.getCurrentUsername());
if(!resources.getId().equals(userDto.getId())){ if(!resources.getId().equals(userDto.getId())){
throw new BadRequestException("不能修改他人资料"); throw new BadRequestException("不能修改他人资料");
} }
@ -141,12 +141,12 @@ public class UserController {
@DeleteMapping @DeleteMapping
@PreAuthorize("@el.check('user:del')") @PreAuthorize("@el.check('user:del')")
public ResponseEntity<Object> delete(@RequestBody Set<Long> ids){ public ResponseEntity<Object> delete(@RequestBody Set<Long> ids){
UserDto user = userService.findByName(SecurityUtils.getUsername()); UserDto user = userService.findByName(SecurityUtils.getCurrentUsername());
for (Long id : ids) { for (Long id : ids) {
Integer currentLevel = Collections.min(roleService.findByUsersId(user.getId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList())); 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())); Integer optLevel = Collections.min(roleService.findByUsersId(id).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
if (currentLevel > optLevel) { if (currentLevel > optLevel) {
throw new BadRequestException("角色权限不足,不能删除:" + userService.findByName(SecurityUtils.getUsername()).getUsername()); throw new BadRequestException("角色权限不足,不能删除:" + userService.findByName(SecurityUtils.getCurrentUsername()).getUsername());
} }
} }
userService.delete(ids); userService.delete(ids);
@ -160,7 +160,7 @@ public class UserController {
RSA rsa = new RSA(privateKey, null); RSA rsa = new RSA(privateKey, null);
String oldPass = new String(rsa.decrypt(passVo.getOldPass(), KeyType.PrivateKey)); String oldPass = new String(rsa.decrypt(passVo.getOldPass(), KeyType.PrivateKey));
String newPass = new String(rsa.decrypt(passVo.getNewPass(), KeyType.PrivateKey)); String newPass = new String(rsa.decrypt(passVo.getNewPass(), KeyType.PrivateKey));
UserDto user = userService.findByName(SecurityUtils.getUsername()); UserDto user = userService.findByName(SecurityUtils.getCurrentUsername());
if(!passwordEncoder.matches(oldPass, user.getPassword())){ if(!passwordEncoder.matches(oldPass, user.getPassword())){
throw new BadRequestException("修改失败,旧密码错误"); throw new BadRequestException("修改失败,旧密码错误");
} }
@ -185,7 +185,7 @@ public class UserController {
// 密码解密 // 密码解密
RSA rsa = new RSA(privateKey, null); RSA rsa = new RSA(privateKey, null);
String password = new String(rsa.decrypt(user.getPassword(), KeyType.PrivateKey)); String password = new String(rsa.decrypt(user.getPassword(), KeyType.PrivateKey));
UserDto userDto = userService.findByName(SecurityUtils.getUsername()); UserDto userDto = userService.findByName(SecurityUtils.getCurrentUsername());
if(!passwordEncoder.matches(password, userDto.getPassword())){ if(!passwordEncoder.matches(password, userDto.getPassword())){
throw new BadRequestException("密码错误"); throw new BadRequestException("密码错误");
} }
@ -200,7 +200,7 @@ public class UserController {
* @param resources / * @param resources /
*/ */
private void checkLevel(User resources) { private void checkLevel(User resources) {
UserDto user = userService.findByName(SecurityUtils.getUsername()); UserDto user = userService.findByName(SecurityUtils.getCurrentUsername());
Integer currentLevel = Collections.min(roleService.findByUsersId(user.getId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList())); Integer currentLevel = Collections.min(roleService.findByUsersId(user.getId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
Integer optLevel = roleService.findByRoles(resources.getRoles()); Integer optLevel = roleService.findByRoles(resources.getRoles());
if (currentLevel > optLevel) { if (currentLevel > optLevel) {

View File

@ -7,10 +7,8 @@ import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.system.service.dto.UserDto; import me.zhengjie.modules.system.service.dto.UserDto;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -108,5 +106,5 @@ public interface RoleService {
* @param user * @param user
* @return * @return
*/ */
Collection<GrantedAuthority> mapToGrantedAuthorities(UserDto user); List<GrantedAuthority> mapToGrantedAuthorities(UserDto user);
} }

View File

@ -3,9 +3,12 @@ package me.zhengjie.modules.system.service.dto;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import lombok.Data; import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import java.io.Serializable; import java.io.Serializable;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.Set; import java.util.Set;
/** /**

View File

@ -153,7 +153,7 @@ public class RoleServiceImpl implements RoleService {
@Override @Override
@Cacheable(key = "'loadPermissionByUser:' + #p0.username") @Cacheable(key = "'loadPermissionByUser:' + #p0.username")
public Collection<GrantedAuthority> mapToGrantedAuthorities(UserDto user) { public List<GrantedAuthority> mapToGrantedAuthorities(UserDto user) {
Set<Role> roles = roleRepository.findByUsers_Id(user.getId()); Set<Role> roles = roleRepository.findByUsers_Id(user.getId());
Set<String> permissions = roles.stream().filter(role -> StringUtils.isNotBlank(role.getPermission())).map(Role::getPermission).collect(Collectors.toSet()); Set<String> permissions = roles.stream().filter(role -> StringUtils.isNotBlank(role.getPermission())).map(Role::getPermission).collect(Collectors.toSet());
permissions.addAll( permissions.addAll(

View File

@ -171,7 +171,7 @@ public class UserServiceImpl implements UserService {
@CacheEvict(allEntries = true) @CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void updateAvatar(MultipartFile multipartFile) { public void updateAvatar(MultipartFile multipartFile) {
User user = userRepository.findByUsername(SecurityUtils.getUsername()); User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername());
UserAvatar userAvatar = user.getUserAvatar(); UserAvatar userAvatar = user.getUserAvatar();
String oldPath = ""; String oldPath = "";
if(userAvatar != null){ if(userAvatar != null){

View File

@ -52,7 +52,7 @@ public class PictureController {
@PostMapping @PostMapping
@ApiOperation("上传图片") @ApiOperation("上传图片")
public ResponseEntity<Object> upload(@RequestParam MultipartFile file){ public ResponseEntity<Object> upload(@RequestParam MultipartFile file){
String userName = SecurityUtils.getUsername(); String userName = SecurityUtils.getCurrentUsername();
Picture picture = pictureService.upload(file,userName); Picture picture = pictureService.upload(file,userName);
return new ResponseEntity<>(picture,HttpStatus.OK); return new ResponseEntity<>(picture,HttpStatus.OK);
} }

View File

@ -94,7 +94,7 @@ public class LocalStorageServiceImpl implements LocalStorageService {
file.getPath(), file.getPath(),
type, type,
FileUtil.getSize(multipartFile.getSize()), FileUtil.getSize(multipartFile.getSize()),
SecurityUtils.getUsername() SecurityUtils.getCurrentUsername()
); );
return localStorageMapper.toDto(localStorageRepository.save(localStorage)); return localStorageMapper.toDto(localStorageRepository.save(localStorage));
}catch (Exception e){ }catch (Exception e){