Commit 61f09ef1 LN

增加异常处理。

1 个父辈 877e30a6
package com.neotel.smfcore.common.exception; package com.neotel.smfcore.common.exception;
import lombok.Data;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
/** /**
* Created by kangmor on 2015/12/2. * Created by kangmor on 2015/12/2.
*/ */
public class ValidateException extends Exception{ @Data
public class ValidateException extends RuntimeException{
private Integer status = BAD_REQUEST.value();
private String[] params; private String[] params;
private String defaultMsg; private String defaultMsg;
...@@ -29,19 +35,4 @@ public class ValidateException extends Exception{ ...@@ -29,19 +35,4 @@ public class ValidateException extends Exception{
this.defaultMsg = defaultMsg; this.defaultMsg = defaultMsg;
} }
public String[] getParams() {
return params;
}
public void setParams(String[] params) {
this.params = params;
}
public String getDefaultMsg() {
return defaultMsg;
}
public void setDefaultMsg(String defaultMsg) {
this.defaultMsg = defaultMsg;
}
} }
package com.neotel.smfcore.common.exception.handler;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class ApiError {
private Integer status = 400;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime timestamp;
private String message;
private ApiError() {
timestamp = LocalDateTime.now();
}
public static ApiError error(String message){
ApiError apiError = new ApiError();
apiError.setMessage(message);
return apiError;
}
public static ApiError error(Integer status, String message){
ApiError apiError = new ApiError();
apiError.setStatus(status);
apiError.setMessage(message);
return apiError;
}
}
package com.neotel.smfcore.common.exception.handler;
import com.neotel.smfcore.common.exception.BadRequestException;
import com.neotel.smfcore.common.exception.EntityExistException;
import com.neotel.smfcore.common.exception.EntityNotFoundException;
import com.neotel.smfcore.common.exception.ValidateException;
import com.neotel.smfcore.common.utils.ThrowableUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Objects;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.NOT_FOUND;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 处理所有不可知的异常
*/
@ExceptionHandler(Throwable.class)
public ResponseEntity<ApiError> handleException(Throwable e){
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
return buildResponseEntity(ApiError.error(e.getMessage()));
}
/**
* BadCredentialsException
*/
@ExceptionHandler(BadCredentialsException.class)
public ResponseEntity<ApiError> badCredentialsException(BadCredentialsException e){
// 打印堆栈信息
String message = "坏的凭证".equals(e.getMessage()) ? "用户名或密码不正确" : e.getMessage();
log.error(message);
return buildResponseEntity(ApiError.error(message));
}
/**
* 处理自定义异常
*/
@ExceptionHandler(value = BadRequestException.class)
public ResponseEntity<ApiError> badRequestException(BadRequestException e) {
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
return buildResponseEntity(ApiError.error(e.getStatus(),e.getMessage()));
}
/**
* 处理 EntityExist
*/
@ExceptionHandler(value = EntityExistException.class)
public ResponseEntity<ApiError> entityExistException(EntityExistException e) {
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
return buildResponseEntity(ApiError.error(e.getMessage()));
}
/**
* 处理 EntityNotFound
*/
@ExceptionHandler(value = EntityNotFoundException.class)
public ResponseEntity<ApiError> entityNotFoundException(EntityNotFoundException e) {
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
return buildResponseEntity(ApiError.error(NOT_FOUND.value(),e.getMessage()));
}
public ResponseEntity<ApiError> validateException(ValidateException e){
log.error(ThrowableUtil.getStackTrace(e));
return buildResponseEntity(ApiError.error(e.getStatus(),e.getMessage()));
}
/**
* 处理所有接口数据验证异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
String[] str = Objects.requireNonNull(e.getBindingResult().getAllErrors().get(0).getCodes())[1].split("\\.");
String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
String msg = "不能为空";
if(msg.equals(message)){
message = str[1] + ":" + message;
}
return buildResponseEntity(ApiError.error(message));
}
/**
* 统一返回
*/
private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) {
return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus()));
}
}
package com.neotel.smfcore.common.init; package com.neotel.smfcore.common.init;
import com.neotel.smfcore.common.utils.Constants;
import com.neotel.smfcore.security.service.manager.IGroupManager; import com.neotel.smfcore.security.service.manager.IGroupManager;
import com.neotel.smfcore.security.service.manager.IMenuManager; import com.neotel.smfcore.security.service.manager.IMenuManager;
import com.neotel.smfcore.security.service.manager.IRoleManager; import com.neotel.smfcore.security.service.manager.IRoleManager;
...@@ -38,7 +39,7 @@ public class DataInitManager { ...@@ -38,7 +39,7 @@ public class DataInitManager {
try { try {
log.info("初始化环境..."); log.info("初始化环境...");
//查询admin的用户是否存在 //查询admin的用户是否存在
String userName = "admin"; String userName = Constants.SUPER_USERNAME;
User admin = userManager.findByUserName(userName); User admin = userManager.findByUserName(userName);
if (admin == null) { if (admin == null) {
...@@ -102,11 +103,11 @@ public class DataInitManager { ...@@ -102,11 +103,11 @@ public class DataInitManager {
Set<String> groupIds= new HashSet<>(); Set<String> groupIds= new HashSet<>();
groupIds.add(group.getId()); groupIds.add(group.getId());
Role role = new Role(menuIdSet,"admin","全部",1,"管理员"); Role role = new Role(menuIdSet,"admin","管理员");
role= roleManager.save(role); role= roleManager.save(role);
log.info("创建默认角色:" + role.toString()); log.info("创建默认角色:" + role.toString());
admin = new User(role.getId(), userName, "", "$2a$10$Egp1/gvFlt7zhlXVfEFw4OfWQCGPw0ClmMcc6FjTnvXNRVf9zdMRa", true, true, new Date(), groupIds ); admin = new User( userName, "","",role.getId(), "$2a$10$Egp1/gvFlt7zhlXVfEFw4OfWQCGPw0ClmMcc6FjTnvXNRVf9zdMRa", true, true, new Date(), groupIds );
userManager.save(admin); userManager.save(admin);
log.info("创建默认用户:" + admin.toString()); log.info("创建默认用户:" + admin.toString());
......
...@@ -7,6 +7,10 @@ public class Constants { ...@@ -7,6 +7,10 @@ public class Constants {
//~ Static fields/initializers ============================================= //~ Static fields/initializers =============================================
/** /**
* 超级管理员用户名
*/
public static final String SUPER_USERNAME= "admin";
/**
* Assets Version constant * Assets Version constant
*/ */
public static final String ASSETS_VERSION = "assetsVersion"; public static final String ASSETS_VERSION = "assetsVersion";
......
package com.neotel.smfcore.common.utils;
import java.awt.print.PrinterGraphics;
import java.io.PrintWriter;
import java.io.StringWriter;
public class ThrowableUtil {
public static String getStackTrace(Throwable throwable){
StringWriter sw=new StringWriter();
try(PrintWriter pw=new PrintWriter(sw)) {
throwable.printStackTrace(pw);
return sw.toString();
}
}
}
package com.neotel.smfcore.security.config; package com.neotel.smfcore.security.config;
import com.neotel.smfcore.common.utils.Constants;
import com.neotel.smfcore.common.utils.SecurityUtils; import com.neotel.smfcore.common.utils.SecurityUtils;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -11,6 +12,12 @@ import java.util.stream.Collectors; ...@@ -11,6 +12,12 @@ import java.util.stream.Collectors;
@Service(value = "el") @Service(value = "el")
public class ElPermissionConfig { public class ElPermissionConfig {
public Boolean check(String ... permissions){ public Boolean check(String ... permissions){
//超级管理员
if(SecurityUtils.getCurrentUsername().equals(Constants.SUPER_USERNAME)) {
return true;
}
// 获取当前用户的所有权限 // 获取当前用户的所有权限
List<String> elPermissions = SecurityUtils.getCurrentUser().getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()); List<String> elPermissions = SecurityUtils.getCurrentUser().getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
// 判断当前用户的所有权限是否包含接口上定义的权限 // 判断当前用户的所有权限是否包含接口上定义的权限
......
...@@ -17,6 +17,7 @@ package com.neotel.smfcore.security.rest; ...@@ -17,6 +17,7 @@ package com.neotel.smfcore.security.rest;
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.collection.CollectionUtil;
import com.neotel.smfcore.common.annotation.QueryCondition; import com.neotel.smfcore.common.annotation.QueryCondition;
import com.neotel.smfcore.common.exception.BadRequestException;
import com.neotel.smfcore.common.exception.ValidateException; import com.neotel.smfcore.common.exception.ValidateException;
import com.neotel.smfcore.common.utils.PageUtil; import com.neotel.smfcore.common.utils.PageUtil;
import com.neotel.smfcore.common.utils.QueryHelp; import com.neotel.smfcore.common.utils.QueryHelp;
...@@ -67,16 +68,16 @@ public class MenuController { ...@@ -67,16 +68,16 @@ public class MenuController {
@GetMapping(value = "/build") @GetMapping(value = "/build")
@ApiOperation("获取前端所需菜单") @ApiOperation("获取前端所需菜单")
@AnonymousAccess @AnonymousAccess
public ResponseEntity<Object> buildMenus(){ public ResponseEntity<Object> buildMenus() {
String userId="1"; String userId = "1";
try { try {
userId=SecurityUtils.getCurrentUserId(); userId = SecurityUtils.getCurrentUserId();
}catch (Exception ex){ } catch (Exception ex) {
log.error("获取当前用户出错:"+ex); log.error("获取当前用户出错:" + ex);
} }
List<Menu> menuList = menuManager.findByUserId(userId); List<Menu> menuList = menuManager.findByUserId(userId);
List<MenuDto> menuDtoList=menuMapper.toDto(menuManager.buildTree(menuList)); List<MenuDto> menuDtoList = menuMapper.toDto(menuManager.buildTree(menuList));
List<MenuVo> vos=menuManager.buildMenus(menuDtoList); List<MenuVo> vos = menuManager.buildMenus(menuDtoList);
return new ResponseEntity<>(vos, HttpStatus.OK); return new ResponseEntity<>(vos, HttpStatus.OK);
} }
...@@ -84,23 +85,24 @@ public class MenuController { ...@@ -84,23 +85,24 @@ public class MenuController {
@GetMapping(value = "/download") @GetMapping(value = "/download")
@PreAuthorize("@el.check('menu:list')") @PreAuthorize("@el.check('menu:list')")
public void download(HttpServletResponse response, MenuQueryCondition criteria) throws Exception { public void download(HttpServletResponse response, MenuQueryCondition criteria) throws Exception {
Query query= QueryHelp.getQuery(criteria); Query query = QueryHelp.getQuery(criteria);
query.addCriteria(Criteria.where("type").ne(2)); query.addCriteria(Criteria.where("type").ne(2));
//Query query=new Query(Criteria.where("type").ne(2)); //Query query=new Query(Criteria.where("type").ne(2));
menuManager.download(menuManager.findByQuery(query), response); menuManager.download(menuManager.findByQuery(query), response);
} }
//
//
@ApiOperation("返回全部的菜单") @ApiOperation("返回全部的菜单")
@GetMapping(value = "/lazy") @GetMapping(value = "/lazy")
@PreAuthorize("@el.check('menu:list','roles:list')") @PreAuthorize("@el.check('menu:list','roles:list')")
public ResponseEntity<Object> query(@RequestParam String pid){ public ResponseEntity<Object> query(@RequestParam String pid) {
return new ResponseEntity<>(menuManager.getMenusByPid(pid), HttpStatus.OK); return new ResponseEntity<>(menuManager.getMenusByPid(pid), HttpStatus.OK);
} }
@ApiOperation("根据菜单ID返回所有子节点ID,包含自身ID") @ApiOperation("根据菜单ID返回所有子节点ID,包含自身ID")
@GetMapping(value = "/child") @GetMapping(value = "/child")
@PreAuthorize("@el.check('menu:list','roles:list')") @PreAuthorize("@el.check('menu:list','roles:list')")
public ResponseEntity<Object> child(@RequestParam String id){ public ResponseEntity<Object> child(@RequestParam String id) {
Set<Menu> menuSet = new HashSet<>(); Set<Menu> menuSet = new HashSet<>();
List<Menu> menuList = menuManager.getMenusByPid(id); List<Menu> menuList = menuManager.getMenusByPid(id);
menuSet.add(menuManager.get(id)); menuSet.add(menuManager.get(id));
...@@ -113,9 +115,9 @@ public class MenuController { ...@@ -113,9 +115,9 @@ public class MenuController {
@ApiOperation("查询菜单") @ApiOperation("查询菜单")
@PreAuthorize("@el.check('menu:list')") @PreAuthorize("@el.check('menu:list')")
public ResponseEntity<Object> query(MenuQueryCondition criteria) throws Exception { public ResponseEntity<Object> query(MenuQueryCondition criteria) throws Exception {
Query query=QueryHelp.getQuery(criteria); Query query = QueryHelp.getQuery(criteria);
query.addCriteria(Criteria.where("type").ne(2)); query.addCriteria(Criteria.where("type").ne(2));
List<MenuDto> menuDtoList =menuMapper.toDto( menuManager.findByQuery(query)); List<MenuDto> menuDtoList = menuMapper.toDto(menuManager.findByQuery(query));
return new ResponseEntity<>(PageUtil.toPage(menuDtoList, menuDtoList.size()), HttpStatus.OK); return new ResponseEntity<>(PageUtil.toPage(menuDtoList, menuDtoList.size()), HttpStatus.OK);
} }
...@@ -124,69 +126,50 @@ public class MenuController { ...@@ -124,69 +126,50 @@ public class MenuController {
@PreAuthorize("@el.check('menu:list')") @PreAuthorize("@el.check('menu:list')")
public ResponseEntity<Object> getSuperior(@RequestBody List<String> ids) { public ResponseEntity<Object> getSuperior(@RequestBody List<String> ids) {
Set<Menu> menus = new LinkedHashSet<>(); Set<Menu> menus = new LinkedHashSet<>();
if(CollectionUtil.isNotEmpty(ids)){ if (CollectionUtil.isNotEmpty(ids)) {
for (String id : ids) { for (String id : ids) {
Menu menu = menuManager.get(id); Menu menu = menuManager.get(id);
menus.addAll(menuManager.getSuperior(menu, new ArrayList<>())); menus.addAll(menuManager.getSuperior(menu, new ArrayList<>()));
} }
return new ResponseEntity<>(menuManager.buildTree(new ArrayList<>(menus)), HttpStatus.OK); return new ResponseEntity<>(menuManager.buildTree(new ArrayList<>(menus)), HttpStatus.OK);
} }
return new ResponseEntity<>(menuMapper.toDto(menuManager.getMenusByPid("")) , HttpStatus.OK); return new ResponseEntity<>(menuMapper.toDto(menuManager.getMenusByPid("")), HttpStatus.OK);
} }
// @Log("新增菜单") // @Log("新增菜单")
@ApiOperation("新增菜单") @ApiOperation("新增菜单")
@PostMapping @PostMapping
@PreAuthorize("@el.check('menu:add')") @PreAuthorize("@el.check('menu:add')")
public ResponseEntity<Object> create(@Validated @RequestBody Menu resources){ public ResponseEntity<Object> create(@Validated @RequestBody Menu resources) {
if (resources.getId() != null) { menuManager.saveMenu(resources);
// throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
log.error("menu:add 参数错误:ID不能为空");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
try {
menuManager.saveMenu(resources);
}catch ( Exception exception){
log.error("menu:add 新增菜单["+resources.toString()+"]出错:"+exception);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(HttpStatus.CREATED); return new ResponseEntity<>(HttpStatus.CREATED);
} }
// @Log("修改菜单") // @Log("修改菜单")
@ApiOperation("修改菜单") @ApiOperation("修改菜单")
@PutMapping @PutMapping
@PreAuthorize("@el.check('menu:edit')") @PreAuthorize("@el.check('menu:edit')")
public ResponseEntity<Object> update(@Validated @RequestBody Menu resources){ public ResponseEntity<Object> update(@Validated @RequestBody Menu resources) {
// public ResponseEntity<Object> update(@Validated(Menu.Update.class) @RequestBody Menu resources){ if (resources.getId() == null) {
throw new BadRequestException(" 修改菜单 :ID不能为空");
try {
menuManager.saveMenu(resources);
} catch (ValidateException e) {
log.error("menu:add 修改菜单["+resources.toString()+"]出错:"+e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} }
menuManager.saveMenu(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT); return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} }
// @Log("删除菜单") // @Log("删除菜单")
@ApiOperation("删除菜单") @ApiOperation("删除菜单")
@DeleteMapping @DeleteMapping
@PreAuthorize("@el.check('menu:del')") @PreAuthorize("@el.check('menu:del')")
public ResponseEntity<Object> delete(@RequestBody Set<String> ids){ public ResponseEntity<Object> delete(@RequestBody Set<String> ids) {
Set<Menu> menuSet = new HashSet<>(); Set<Menu> menuSet = new HashSet<>();
for (String id : ids) { for (String id : ids) {
List<Menu> menuList = menuManager.getMenusByPid(id); List<Menu> menuList = menuManager.getMenusByPid(id);
menuSet.add(menuManager.get(id)); menuSet.add(menuManager.get(id));
menuSet = menuManager.getChildMenus(menuList, menuSet); menuSet = menuManager.getChildMenus(menuList, menuSet);
} }
try { menuManager.delete(menuSet);
menuManager.delete(menuSet);
} catch (ValidateException e) {
log.error("menu:add 删除菜单["+ids+"]出错:"+e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} }
} }
package com.neotel.smfcore.security.rest; package com.neotel.smfcore.security.rest;
import cn.hutool.core.lang.Dict; import cn.hutool.core.lang.Dict;
import com.neotel.smfcore.common.exception.BadRequestException;
import com.neotel.smfcore.common.exception.ValidateException; import com.neotel.smfcore.common.exception.ValidateException;
import com.neotel.smfcore.common.utils.PageUtil; import com.neotel.smfcore.common.utils.PageUtil;
import com.neotel.smfcore.common.utils.QueryHelp; import com.neotel.smfcore.common.utils.QueryHelp;
...@@ -83,123 +84,57 @@ public class RoleController { ...@@ -83,123 +84,57 @@ public class RoleController {
return new ResponseEntity<>(data,HttpStatus.OK); return new ResponseEntity<>(data,HttpStatus.OK);
} }
@ApiOperation("获取用户级别")
@GetMapping(value = "/level")
public ResponseEntity<Object> getLevel(){
User curruser = userManager.get(SecurityUtils.getCurrentUserId());
Role currRole=roleManager.get(curruser.getRoleId());
return new ResponseEntity<>(Dict.create().set("level", currRole.getLevel() ),HttpStatus.OK);
}
@ApiOperation("新增角色") @ApiOperation("新增角色")
@PostMapping @PostMapping
@PreAuthorize("@el.check('roles:add')") @PreAuthorize("@el.check('roles:add')")
public ResponseEntity<Object> create(@Validated @RequestBody Role resources){ public ResponseEntity<Object> create(@Validated @RequestBody Role resources) {
if (resources.getId() != null) { roleManager.saveRole(resources);
// throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
log.error("新增角色:角色ID不为空:"+resources.getId());
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
if(!hasLevel(resources.getLevel()) ) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
try {
roleManager.saveRole(resources);
} catch (ValidateException e) {
log.error("新增角色["+resources.toString()+"]出错::"+e);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.CREATED); return new ResponseEntity<>(HttpStatus.CREATED);
} }
@ApiOperation("修改角色") @ApiOperation("修改角色")
@PutMapping @PutMapping
@PreAuthorize("@el.check('roles:edit')") @PreAuthorize("@el.check('roles:edit')")
public ResponseEntity<Object> update(@Validated @RequestBody Role resources){ public ResponseEntity<Object> update(@Validated @RequestBody Role resources) {
if(resources.getId()==null){ if (resources.getId() == null) {
log.error("修改角色:角色ID为空:"); throw new BadRequestException("修改角色:ID不能为空");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
if(!hasLevel(resources.getLevel()) ) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
try {
roleManager.saveRole(resources);
} catch (ValidateException e) {
log.error("修改角色["+resources.toString()+"]出错::"+e);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} }
roleManager.saveRole(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT); return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} }
@ApiOperation("修改角色菜单") @ApiOperation("修改角色菜单")
@PutMapping(value = "/menu") @PutMapping(value = "/menu")
@PreAuthorize("@el.check('roles:edit')") @PreAuthorize("@el.check('roles:edit')")
public ResponseEntity<Object> updateMenu(@RequestBody Role resources){ public ResponseEntity<Object> updateMenu(@RequestBody Role resources) {
if(resources.getId()==null){ if (resources.getId() == null) {
log.error("修改角色菜单["+resources.toString()+"]失败:角色ID不能是空"); throw new BadRequestException("修改角色菜单:ID不能为空");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} }
Role role = roleManager.get(resources.getId()); Role role = roleManager.get(resources.getId());
if(!hasLevel(resources.getLevel()) ) { roleManager.updateMenu(resources);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
try {
roleManager.updateMenu(resources);
} catch (ValidateException e) {
log.error("修改角色["+resources.toString()+"]出错::"+e);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.NO_CONTENT); return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} }
@ApiOperation("删除角色") @ApiOperation("删除角色")
@DeleteMapping @DeleteMapping
@PreAuthorize("@el.check('roles:del')") @PreAuthorize("@el.check('roles:del')")
public ResponseEntity<Object> delete(@RequestBody Set<String> ids){ public ResponseEntity<Object> delete(@RequestBody Set<String> ids) {
List<Role> roles=new ArrayList<Role>(); List<Role> roles = new ArrayList<Role>();
for (String id : ids) { for (String id : ids) {
if(id ==null){ if (id == null) {
log.error("删除角色出错:ID为空"); throw new BadRequestException("删除角色:ID不能为空");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} }
Role role = roleManager.get(id); Role role = roleManager.get(id);
if(!hasLevel(role.getLevel()) ) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
// 验证是否被用户关联 // 验证是否被用户关联
List<User> users=userManager.findByRoleId(role.getId()); List<User> users = userManager.findByRoleId(role.getId());
if(users!=null&& users.size()>0){ if (users != null && users.size() > 0) {
log.error("删除角色["+role.toString()+"]出错:有["+users.size()+"]个用户关联改角色"); throw new BadRequestException("删除失败:角色[" + role.getName() + "]有[" + users.size() + "]个用户关联改角色");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} }
roles.add(role); roles.add(role);
} }
roleManager.deleteRoles(roles);
try {
roleManager.deleteRoles(roles);
} catch (ValidateException e) {
log.error("删除角色 ["+ids+"] 出错::"+e);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} }
/**
* 如果当前用户的角色级别低于创建用户的角色级别,则抛出权限不足的错误
* @param level /
*/
private boolean hasLevel(Integer level) {
User curruser = userManager.get(SecurityUtils.getCurrentUserId());
Role currRole=roleManager.get(curruser.getRoleId());
if (level < currRole.getLevel()) {
log.error("当前用户["+curruser.getUsername()+"]权限低于 ["+level+"],操作失败");
return false;
}
return true;
}
} }
...@@ -16,11 +16,9 @@ ...@@ -16,11 +16,9 @@
package com.neotel.smfcore.security.rest; package com.neotel.smfcore.security.rest;
import com.neotel.smfcore.common.annotation.QueryCondition; import com.neotel.smfcore.common.annotation.QueryCondition;
import com.neotel.smfcore.common.exception.BadRequestException;
import com.neotel.smfcore.common.exception.ValidateException; import com.neotel.smfcore.common.exception.ValidateException;
import com.neotel.smfcore.common.utils.PageUtil; import com.neotel.smfcore.common.utils.*;
import com.neotel.smfcore.common.utils.QueryHelp;
import com.neotel.smfcore.common.utils.RsaUtils;
import com.neotel.smfcore.common.utils.SecurityUtils;
import com.neotel.smfcore.security.bean.RsaProperties; import com.neotel.smfcore.security.bean.RsaProperties;
import com.neotel.smfcore.security.rest.bean.dto.RoleSmallDto; import com.neotel.smfcore.security.rest.bean.dto.RoleSmallDto;
import com.neotel.smfcore.security.rest.bean.dto.UserDto; import com.neotel.smfcore.security.rest.bean.dto.UserDto;
...@@ -67,15 +65,14 @@ public class UserController { ...@@ -67,15 +65,14 @@ public class UserController {
private IUserManager userManager; private IUserManager userManager;
@Autowired @Autowired
private IRoleManager roleManager; private IRoleManager roleManager;
// @Autowired
// private UserMapper userMapper;
@ApiOperation("导出用户数据") @ApiOperation("导出用户数据")
@GetMapping(value = "/download") @GetMapping(value = "/download")
@PreAuthorize("@el.check('user:list')") @PreAuthorize("@el.check('user:list')")
public void download(HttpServletResponse response, UserQueryCriteria criteria) throws IOException { public void download(HttpServletResponse response, UserQueryCriteria criteria) throws IOException {
Query query=QueryHelp.getQuery(criteria); Query query = QueryHelp.getQuery(criteria);
List<User> users=userManager.findByQuery(query); List<User> users = userManager.findByQuery(query);
userManager.download(users, response); userManager.download(users, response);
} }
...@@ -94,18 +91,10 @@ public class UserController { ...@@ -94,18 +91,10 @@ public class UserController {
@ApiOperation("新增用户") @ApiOperation("新增用户")
@PostMapping @PostMapping
@PreAuthorize("@el.check('user:add')") @PreAuthorize("@el.check('user:add')")
public ResponseEntity<Object> create(@Validated @RequestBody User resources){ public ResponseEntity<Object> create(@Validated @RequestBody User resources) {
if(!hasLevel(resources)) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
// 默认密码 123456
resources.setPassword(passwordEncoder.encode("123456")); resources.setPassword(passwordEncoder.encode("123456"));
try { userManager.save(resources);
userManager.save(resources);
} catch (ValidateException e) {
log.error("新增用户 user:add ["+resources.toString()+"]出错:"+e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(HttpStatus.CREATED); return new ResponseEntity<>(HttpStatus.CREATED);
} }
...@@ -113,27 +102,26 @@ public class UserController { ...@@ -113,27 +102,26 @@ public class UserController {
@PutMapping @PutMapping
@PreAuthorize("@el.check('user:edit')") @PreAuthorize("@el.check('user:edit')")
// public ResponseEntity<Object> update(@Validated(User.Update.class) @RequestBody User resources) throws Exception { // public ResponseEntity<Object> update(@Validated(User.Update.class) @RequestBody User resources) throws Exception {
public ResponseEntity<Object> update(@Validated @RequestBody User resources) { public ResponseEntity<Object> update(@Validated @RequestBody User resources) {
if(!hasLevel(resources)) { if (resources.getId() == null) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST); throw new BadRequestException("修改用户:ID不能为空");
} }
try { if (resources.getUsername().equals(Constants.SUPER_USERNAME)) {
userManager.update(resources); if (!resources.getId().equals(SecurityUtils.getCurrentUserId())) {
} catch (Exception e) { throw new BadRequestException("无权限修改此用户信息");
log.error("修改用户 user:edit ["+resources.toString()+"]出错:"+e); }
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} }
userManager.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT); return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} }
@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){
public ResponseEntity<Object> center(@Validated @RequestBody User resources){ public ResponseEntity<Object> center(@Validated @RequestBody User resources) {
if(!resources.getId().equals(SecurityUtils.getCurrentUserId())){ if (!resources.getId().equals(SecurityUtils.getCurrentUserId())) {
// throw new BadRequestException("不能修改他人资料"); throw new BadRequestException("不能修改他人资料");
log.error("修改用户:个人中心:不能修改他人资料,操作失败");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} }
userManager.updateCenter(resources); userManager.updateCenter(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT); return new ResponseEntity<>(HttpStatus.NO_CONTENT);
...@@ -143,32 +131,21 @@ public class UserController { ...@@ -143,32 +131,21 @@ public class UserController {
@ApiOperation("删除用户") @ApiOperation("删除用户")
@DeleteMapping @DeleteMapping
@PreAuthorize("@el.check('user:del')") @PreAuthorize("@el.check('user:del')")
public ResponseEntity<Object> delete(@RequestBody Set<String> ids){ public ResponseEntity<Object> delete(@RequestBody Set<String> ids) {
for (String id : ids) { for (String id : ids) {
//不能删除自己 //不能删除自己
String currId=SecurityUtils.getCurrentUserId(); String currId = SecurityUtils.getCurrentUserId();
if(currId==id){ if (currId == id) {
log.error("删除用户:不能删除自己"); throw new BadRequestException("删除用户:不能删除自己");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} }
User user=userManager.get(id); User user = userManager.get(id);
//admin的用户不让删除 //admin的用户不让删除
if(user.getUsername().equals("admin")){ if (user.getUsername().equals(Constants.SUPER_USERNAME)) {
log.error("删除用户:admin用户不能删除"); throw new BadRequestException("删除用户:此用户不能删除");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
if(!hasLevel(user)) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} }
} }
try { userManager.deleteUsers(ids);
userManager.deleteUsers(ids);
} catch (ValidateException e) {
log.error("删除用户出错:"+e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} }
...@@ -176,59 +153,28 @@ public class UserController { ...@@ -176,59 +153,28 @@ public class UserController {
@PostMapping(value = "/updatePass") @PostMapping(value = "/updatePass")
public ResponseEntity<Object> updatePass(@RequestBody UserPassVo passVo) throws Exception { public ResponseEntity<Object> updatePass(@RequestBody UserPassVo passVo) throws Exception {
User user = userManager.get(SecurityUtils.getCurrentUserId()); User user = userManager.get(SecurityUtils.getCurrentUserId());
if(!passwordEncoder.matches(passVo.getOldPass(), user.getPassword())){ if (!passwordEncoder.matches(passVo.getOldPass(), user.getPassword())) {
// throw new BadRequestException("修改失败,旧密码错误"); throw new BadRequestException("修改失败,旧密码错误");
log.error("用户["+SecurityUtils.getCurrentUsername()+"]修改密码失败:旧密码错误");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} }
if(passwordEncoder.matches(passVo.getNewPass(), user.getPassword())){ if (passwordEncoder.matches(passVo.getNewPass(), user.getPassword())) {
// throw new BadRequestException("新密码不能与旧密码相同"); throw new BadRequestException("新密码不能与旧密码相同");
log.error("用户["+SecurityUtils.getCurrentUsername()+"]修改密码失败:新密码不能与旧密码相同");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} }
userManager.updatePass(user.getUsername(),passwordEncoder.encode(passVo.getNewPass())); userManager.updatePass(user.getUsername(), passwordEncoder.encode(passVo.getNewPass()));
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} }
@ApiOperation("修改邮箱") @ApiOperation("修改邮箱")
@PostMapping(value = "/updateEmail/{code}") @PostMapping(value = "/updateEmail/{code}")
public ResponseEntity<Object> updateEmail(@PathVariable String code, @RequestBody User user) throws Exception { public ResponseEntity<Object> updateEmail(@PathVariable String code, @RequestBody User user) throws Exception {
String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, user.getPassword()); String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, user.getPassword());
User myUser = userManager.findByUserName(SecurityUtils.getCurrentUsername()); User myUser = userManager.findByUserName(SecurityUtils.getCurrentUsername());
if(!passwordEncoder.matches(password, myUser.getPassword())){ if (!passwordEncoder.matches(password, myUser.getPassword())) {
log.error("用户["+SecurityUtils.getCurrentUsername()+"]修改邮箱失败,密码错误"); throw new BadRequestException("修改邮箱失败,密码错误");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} }
// verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + user.getEmail(), code); // verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + user.getEmail(), code);
userManager.updateEmail(myUser.getUsername(),myUser.getEmail()); userManager.updateEmail(myUser.getUsername(), myUser.getEmail());
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} }
/**
* 如果当前用户的角色级别低于创建用户的角色级别,则抛出权限不足的错误
* @param resources /
*/
private boolean hasLevel(User resources) {
User curruser = userManager.get(SecurityUtils.getCurrentUserId());
Role currRole=roleManager.get(curruser.getRoleId());
Role resRole=roleManager.get(resources.getRoleId());
if (resRole.getLevel() > currRole.getLevel()) {
log.error("当前用户["+curruser.getUsername()+"]权限低于用户["+resources.getUsername()+"],操作失败");
return false;
}
//如果当前用户不是管理员,不能修改管理员
if(resources.getIsAdmin()){
if(curruser.getIsAdmin().equals(false)){
log.error("当前用户["+curruser.getUsername()+"]权限低于管理员用户["+resources.getUsername()+"],操作失败");
return false;
}
}
return true;
}
} }
...@@ -15,9 +15,9 @@ public class RoleDto implements Serializable { ...@@ -15,9 +15,9 @@ public class RoleDto implements Serializable {
private String name; private String name;
private String dataScope; // private String dataScope;
private Integer level; // private Integer level;
private String description; private String description;
} }
...@@ -19,6 +19,8 @@ public class UserDto implements Serializable { ...@@ -19,6 +19,8 @@ public class UserDto implements Serializable {
private String email; private String email;
private String language="";
@JSONField(serialize = false) @JSONField(serialize = false)
private String password; private String password;
......
...@@ -63,7 +63,7 @@ public class RoleManagerImpl implements IRoleManager { ...@@ -63,7 +63,7 @@ public class RoleManagerImpl implements IRoleManager {
for (Role role : roles) { for (Role role : roles) {
Map<String, Object> map = new LinkedHashMap<>(); Map<String, Object> map = new LinkedHashMap<>();
map.put("角色名称", role.getName()); map.put("角色名称", role.getName());
map.put("角色级别", role.getLevel()); // map.put("角色级别", role.getLevel());
map.put("描述", role.getDescription()); map.put("描述", role.getDescription());
map.put("创建日期", role.getCreateDate()); map.put("创建日期", role.getCreateDate());
list.add(map); list.add(map);
...@@ -73,15 +73,15 @@ public class RoleManagerImpl implements IRoleManager { ...@@ -73,15 +73,15 @@ public class RoleManagerImpl implements IRoleManager {
@Override @Override
public Role saveRole(Role role) throws ValidateException { public Role saveRole(Role role) throws ValidateException {
if (role.getLevel() == null) { // if (role.getLevel() == null) {
role.setLevel(99); // role.setLevel(99);
} // }
if (role.getMenus() == null) { if (role.getMenus() == null) {
role.setMenus(new HashSet<String>()); role.setMenus(new HashSet<String>());
} }
if (role.getDataScope() == null) { // if (role.getDataScope() == null) {
role.setDataScope("全部"); // role.setDataScope("全部");
} // }
if (role.getDescription() == null) { if (role.getDescription() == null) {
role.setDescription(""); role.setDescription("");
} }
......
...@@ -2,6 +2,7 @@ package com.neotel.smfcore.security.service.manager.impl; ...@@ -2,6 +2,7 @@ package com.neotel.smfcore.security.service.manager.impl;
import com.google.common.base.Strings; import com.google.common.base.Strings;
import com.neotel.smfcore.common.exception.ValidateException; import com.neotel.smfcore.common.exception.ValidateException;
import com.neotel.smfcore.common.utils.Constants;
import com.neotel.smfcore.common.utils.FileUtil; import com.neotel.smfcore.common.utils.FileUtil;
import com.neotel.smfcore.security.rest.bean.dto.RoleSmallDto; import com.neotel.smfcore.security.rest.bean.dto.RoleSmallDto;
import com.neotel.smfcore.security.rest.bean.dto.UserDto; import com.neotel.smfcore.security.rest.bean.dto.UserDto;
...@@ -47,7 +48,7 @@ public class UserManagerImpl implements IUserManager { ...@@ -47,7 +48,7 @@ public class UserManagerImpl implements IUserManager {
public void updatePass(String username, String encryptPassword) { public void updatePass(String username, String encryptPassword) {
Criteria c = Criteria.where("username").is(username); Criteria c = Criteria.where("username").is(username);
Query query = Query.query(c); Query query = Query.query(c);
Update update = Update.update("password","password"); Update update = Update.update("password",encryptPassword);
userDao.updateFirst(query,update); userDao.updateFirst(query,update);
} }
@Override @Override
...@@ -59,14 +60,15 @@ public class UserManagerImpl implements IUserManager { ...@@ -59,14 +60,15 @@ public class UserManagerImpl implements IUserManager {
} }
//用户名admin不能修改 //用户名admin不能修改
if(!dataUser.equals("admin")){ if(!dataUser.equals(Constants.SUPER_USERNAME)){
dataUser.setUsername(user.getUsername()); dataUser.setUsername(user.getUsername());
} }
dataUser.setEmail(user.getEmail()); dataUser.setEmail(user.getEmail());
dataUser.setEnabled(user.getEnabled()); dataUser.setEnabled(user.getEnabled());
dataUser.setIsAdmin(user.getIsAdmin());; // dataUser.setIsAdmin(user.getIsAdmin());;
dataUser.setRoleId(user.getRoleId()); dataUser.setRoleId(user.getRoleId());
dataUser.setGroups(user.getGroups()); dataUser.setGroups(user.getGroups());
dataUser.setLanguage(user.getLanguage());
userDao.save(dataUser); userDao.save(dataUser);
} }
} }
...@@ -75,11 +77,11 @@ public class UserManagerImpl implements IUserManager { ...@@ -75,11 +77,11 @@ public class UserManagerImpl implements IUserManager {
User dataUser=this.get(resources.getId()); User dataUser=this.get(resources.getId());
if(dataUser!=null){ if(dataUser!=null){
//用户名admin不能修改 //用户名admin不能修改
if(!dataUser.equals("admin")){ if(!dataUser.equals(Constants.SUPER_USERNAME)){
dataUser.setUsername(resources.getUsername()); dataUser.setUsername(resources.getUsername());
} }
dataUser.setUsername(resources.getUsername());
dataUser.setEmail(resources.getEmail()); dataUser.setEmail(resources.getEmail());
dataUser.setLanguage(resources.getLanguage());
} }
userDao.save(dataUser); userDao.save(dataUser);
...@@ -134,6 +136,7 @@ public class UserManagerImpl implements IUserManager { ...@@ -134,6 +136,7 @@ public class UserManagerImpl implements IUserManager {
map.put("角色", user.getRoleId()); map.put("角色", user.getRoleId());
map.put("邮箱", user.getEmail()); map.put("邮箱", user.getEmail());
map.put("状态", user.getEnabled() ? "启用" : "禁用"); map.put("状态", user.getEnabled() ? "启用" : "禁用");
map.put("语言",user.getLanguage());
map.put("修改密码的时间", user.getPwdResetTime()); map.put("修改密码的时间", user.getPwdResetTime());
map.put("创建日期", user.getCreateDate()); map.put("创建日期", user.getCreateDate());
list.add(map); list.add(map);
...@@ -145,7 +148,7 @@ public class UserManagerImpl implements IUserManager { ...@@ -145,7 +148,7 @@ public class UserManagerImpl implements IUserManager {
public void updateEmail(String username, String email) { public void updateEmail(String username, String email) {
Criteria c = Criteria.where("username").is(username); Criteria c = Criteria.where("username").is(username);
Query query = Query.query(c); Query query = Query.query(c);
Update update = Update.update("email","email"); Update update = Update.update("email",email);
userDao.updateFirst(query,update); userDao.updateFirst(query,update);
} }
......
...@@ -34,14 +34,14 @@ import java.util.Set; ...@@ -34,14 +34,14 @@ import java.util.Set;
public class Role extends BasePo implements Serializable { public class Role extends BasePo implements Serializable {
private Set<String> menus; private Set<String> menus;
private String name;
private String description;
// private Set<Dept> depts; // private Set<Dept> depts;
private String name;
private String dataScope; // private String dataScope;
private Integer level; // private Integer level;
private String description;
} }
...@@ -35,12 +35,15 @@ import java.util.Set; ...@@ -35,12 +35,15 @@ import java.util.Set;
public class User extends BasePo implements Serializable { public class User extends BasePo implements Serializable {
private String roleId;
private String username; private String username;
private String email; private String email;
private String language="";
private String roleId;
@JSONField(serialize = false) @JSONField(serialize = false)
private String password; private String password;
......
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!