mirror of https://github.com/elunez/eladmin
SecurityUtils 加入获取当前登录用户ID方法,Security 结构调整
parent
4054ac7bc8
commit
207e6fb1df
|
@ -15,7 +15,7 @@ public class ElPermissionConfig {
|
|||
|
||||
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);
|
||||
}
|
||||
|
|
|
@ -1,34 +1,60 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -76,7 +76,7 @@ public class LogAspect {
|
|||
|
||||
public String getUsername() {
|
||||
try {
|
||||
return SecurityUtils.getUsername();
|
||||
return SecurityUtils.getCurrentUsername();
|
||||
}catch (Exception e){
|
||||
return "";
|
||||
}
|
||||
|
|
|
@ -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.getCurrentUsername());
|
||||
return new ResponseEntity<>(logService.queryAllByUser(criteria,pageable), HttpStatus.OK);
|
||||
}
|
||||
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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.getCurrentUsername());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -37,7 +37,7 @@ public class DataScope {
|
|||
|
||||
public Set<Long> getDeptIds() {
|
||||
|
||||
UserDto user = userService.findByName(SecurityUtils.getUsername());
|
||||
UserDto user = userService.findByName(SecurityUtils.getCurrentUsername());
|
||||
|
||||
// 用于存储部门id
|
||||
Set<Long> deptIds = new HashSet<>();
|
||||
|
|
|
@ -202,7 +202,7 @@ public class DeployServiceImpl implements DeployService {
|
|||
//还原信息入库
|
||||
DeployHistory deployHistory = new DeployHistory();
|
||||
deployHistory.setAppName(appName);
|
||||
deployHistory.setDeployUser(SecurityUtils.getUsername());
|
||||
deployHistory.setDeployUser(SecurityUtils.getCurrentUsername());
|
||||
deployHistory.setIp(ip);
|
||||
deployHistory.setDeployId(id);
|
||||
deployHistoryService.create(deployHistory);
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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.security.vo.AuthUser;
|
||||
import me.zhengjie.modules.security.security.vo.JwtUser;
|
||||
import me.zhengjie.modules.security.service.dto.AuthUserDto;
|
||||
import me.zhengjie.modules.security.service.dto.JwtUserDto;
|
||||
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 AuthorizationController {
|
||||
|
||||
@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 AuthorizationController(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 AuthUserDto 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 JwtUserDto jwtUserDto = (JwtUserDto) authentication.getPrincipal();
|
||||
// 保存在线信息
|
||||
onlineUserService.save(jwtUser, token, request);
|
||||
onlineUserService.save(jwtUserDto, token, request);
|
||||
// 返回 token 与 用户信息
|
||||
Map<String,Object> authInfo = new HashMap<String,Object>(2){{
|
||||
put("token", properties.getTokenStartWith() + token);
|
||||
put("user", jwtUser);
|
||||
put("user", jwtUserDto);
|
||||
}};
|
||||
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);
|
||||
JwtUserDto jwtUserDto = (JwtUserDto)userDetailsService.loadUserByUsername(SecurityUtils.getCurrentUsername());
|
||||
return ResponseEntity.ok(jwtUserDto);
|
||||
}
|
||||
|
||||
@AnonymousAccess
|
|
@ -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.security.vo.OnlineUser;
|
||||
import me.zhengjie.modules.security.service.dto.OnlineUserDto;
|
||||
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;
|
||||
OnlineUserDto onlineUserDto = null;
|
||||
try {
|
||||
SecurityProperties properties = SpringContextHolder.getBean(SecurityProperties.class);
|
||||
OnlineUserService onlineUserService = SpringContextHolder.getBean(OnlineUserService.class);
|
||||
onlineUser = onlineUserService.getOne(properties.getOnlineKey() + token);
|
||||
onlineUserDto = onlineUserService.getOne(properties.getOnlineKey() + token);
|
||||
} catch (ExpiredJwtException e) {
|
||||
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);
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
log.debug("set Authentication to security context for '{}', uri: {}", authentication.getName(), requestRri);
|
||||
|
|
|
@ -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.security.vo.JwtUser;
|
||||
import me.zhengjie.modules.security.security.vo.OnlineUser;
|
||||
import me.zhengjie.modules.security.service.dto.JwtUserDto;
|
||||
import me.zhengjie.modules.security.service.dto.OnlineUserDto;
|
||||
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 jwtUserDto /
|
||||
* @param token /
|
||||
* @param request /
|
||||
*/
|
||||
public void save(JwtUser jwtUser, String token, HttpServletRequest request){
|
||||
String job = jwtUser.getDept() + "/" + jwtUser.getJob();
|
||||
public void save(JwtUserDto jwtUserDto, String token, HttpServletRequest request){
|
||||
String job = jwtUserDto.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;
|
||||
OnlineUserDto onlineUserDto = null;
|
||||
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) {
|
||||
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 /
|
||||
*/
|
||||
public Map<String,Object> getAll(String filter, Pageable pageable){
|
||||
List<OnlineUser> onlineUsers = getAll(filter);
|
||||
List<OnlineUserDto> onlineUserDtos = getAll(filter);
|
||||
return PageUtil.toPage(
|
||||
PageUtil.toPage(pageable.getPageNumber(),pageable.getPageSize(),onlineUsers),
|
||||
onlineUsers.size()
|
||||
PageUtil.toPage(pageable.getPageNumber(),pageable.getPageSize(), onlineUserDtos),
|
||||
onlineUserDtos.size()
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -67,28 +67,27 @@ public class OnlineUserService {
|
|||
* @param filter /
|
||||
* @return /
|
||||
*/
|
||||
public List<OnlineUser> getAll(String filter){
|
||||
public List<OnlineUserDto> getAll(String filter){
|
||||
List<String> keys = redisUtils.scan(properties.getOnlineKey() + "*");
|
||||
Collections.reverse(keys);
|
||||
List<OnlineUser> onlineUsers = new ArrayList<>();
|
||||
List<OnlineUserDto> onlineUserDtos = new ArrayList<>();
|
||||
for (String key : keys) {
|
||||
OnlineUser onlineUser = (OnlineUser) redisUtils.get(key);
|
||||
OnlineUserDto onlineUserDto = (OnlineUserDto) redisUtils.get(key);
|
||||
if(StringUtils.isNotBlank(filter)){
|
||||
if(onlineUser.toString().contains(filter)){
|
||||
onlineUsers.add(onlineUser);
|
||||
if(onlineUserDto.toString().contains(filter)){
|
||||
onlineUserDtos.add(onlineUserDto);
|
||||
}
|
||||
} else {
|
||||
onlineUsers.add(onlineUser);
|
||||
onlineUserDtos.add(onlineUserDto);
|
||||
}
|
||||
}
|
||||
onlineUsers.sort((o1, o2) -> o2.getLoginTime().compareTo(o1.getLoginTime()));
|
||||
return onlineUsers;
|
||||
onlineUserDtos.sort((o1, o2) -> o2.getLoginTime().compareTo(o1.getLoginTime()));
|
||||
return onlineUserDtos;
|
||||
}
|
||||
|
||||
/**
|
||||
* 踢出用户
|
||||
* @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<OnlineUserDto> all, HttpServletResponse response) throws IOException {
|
||||
List<Map<String, Object>> list = new ArrayList<>();
|
||||
for (OnlineUser user : all) {
|
||||
for (OnlineUserDto 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 OnlineUserDto getOne(String key) {
|
||||
return (OnlineUserDto)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<OnlineUserDto> onlineUserDtos = getAll(userName);
|
||||
if(onlineUserDtos ==null || onlineUserDtos.isEmpty()){
|
||||
return;
|
||||
}
|
||||
for(OnlineUser onlineUser:onlineUsers){
|
||||
if(onlineUser.getUserName().equals(userName)){
|
||||
for(OnlineUserDto onlineUserDto : onlineUserDtos){
|
||||
if(onlineUserDto.getUserName().equals(userName)){
|
||||
try {
|
||||
String token =EncryptUtils.desDecrypt(onlineUser.getKey());
|
||||
String token =EncryptUtils.desDecrypt(onlineUserDto.getKey());
|
||||
if(StringUtils.isNotBlank(igoreToken)&&!igoreToken.equals(token)){
|
||||
this.kickOut(token);
|
||||
}else if(StringUtils.isBlank(igoreToken)){
|
||||
|
|
|
@ -1,16 +1,14 @@
|
|||
package me.zhengjie.modules.security.service;
|
||||
|
||||
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.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 UserDetails loadUserByUsername(String username){
|
||||
public JwtUserDto 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()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
package me.zhengjie.modules.security.security.vo;
|
||||
package me.zhengjie.modules.security.service.dto;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
@ -11,7 +11,7 @@ import javax.validation.constraints.NotBlank;
|
|||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public class AuthUser {
|
||||
public class AuthUserDto {
|
||||
|
||||
@NotBlank
|
||||
private String username;
|
|
@ -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 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 JwtUserDto 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 List<GrantedAuthority> authorities;
|
||||
|
||||
private final String avatar;
|
||||
|
||||
private final String email;
|
||||
|
||||
private final String phone;
|
||||
|
||||
private final String dept;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
@JsonIgnore
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public Collection getRoles() {
|
||||
return authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
|
||||
return user.getEnabled();
|
||||
}
|
||||
}
|
|
@ -1,33 +1,57 @@
|
|||
package me.zhengjie.modules.security.security.vo;
|
||||
package me.zhengjie.modules.security.service.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 在线用户
|
||||
* @author Zheng Jie
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class OnlineUser {
|
||||
public class OnlineUserDto {
|
||||
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
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;
|
||||
|
||||
|
|
@ -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.getCurrentUsername());
|
||||
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);
|
||||
|
|
|
@ -139,7 +139,7 @@ public class RoleController {
|
|||
* @return /
|
||||
*/
|
||||
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());
|
||||
int min = Collections.min(levels);
|
||||
if(level != null){
|
||||
|
|
|
@ -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.getCurrentUsername());
|
||||
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.getCurrentUsername());
|
||||
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.getCurrentUsername()).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.getCurrentUsername());
|
||||
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.getCurrentUsername());
|
||||
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.getCurrentUsername());
|
||||
Integer currentLevel = Collections.min(roleService.findByUsersId(user.getId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
|
||||
Integer optLevel = roleService.findByRoles(resources.getRoles());
|
||||
if (currentLevel > optLevel) {
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -3,9 +3,12 @@ package me.zhengjie.modules.system.service.dto;
|
|||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
|
|
|
@ -153,7 +153,7 @@ public class RoleServiceImpl implements RoleService {
|
|||
|
||||
@Override
|
||||
@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<String> permissions = roles.stream().filter(role -> StringUtils.isNotBlank(role.getPermission())).map(Role::getPermission).collect(Collectors.toSet());
|
||||
permissions.addAll(
|
||||
|
|
|
@ -171,7 +171,7 @@ public class UserServiceImpl implements UserService {
|
|||
@CacheEvict(allEntries = true)
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void updateAvatar(MultipartFile multipartFile) {
|
||||
User user = userRepository.findByUsername(SecurityUtils.getUsername());
|
||||
User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername());
|
||||
UserAvatar userAvatar = user.getUserAvatar();
|
||||
String oldPath = "";
|
||||
if(userAvatar != null){
|
||||
|
|
|
@ -52,7 +52,7 @@ public class PictureController {
|
|||
@PostMapping
|
||||
@ApiOperation("上传图片")
|
||||
public ResponseEntity<Object> upload(@RequestParam MultipartFile file){
|
||||
String userName = SecurityUtils.getUsername();
|
||||
String userName = SecurityUtils.getCurrentUsername();
|
||||
Picture picture = pictureService.upload(file,userName);
|
||||
return new ResponseEntity<>(picture,HttpStatus.OK);
|
||||
}
|
||||
|
|
|
@ -94,7 +94,7 @@ public class LocalStorageServiceImpl implements LocalStorageService {
|
|||
file.getPath(),
|
||||
type,
|
||||
FileUtil.getSize(multipartFile.getSize()),
|
||||
SecurityUtils.getUsername()
|
||||
SecurityUtils.getCurrentUsername()
|
||||
);
|
||||
return localStorageMapper.toDto(localStorageRepository.save(localStorage));
|
||||
}catch (Exception e){
|
||||
|
|
Loading…
Reference in New Issue