feat(系统管理): 菜单页面,按钮添加权限验证

master
wayn 5 years ago
parent b91db0eff4
commit ad7c89caa1

@ -5,6 +5,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@ -33,6 +34,15 @@ public class GlobalExceptionHandler {
return R.error(e.getCode(), e.getMessage());
}
/**
*
*/
@ExceptionHandler(UsernameNotFoundException.class)
public R usernameNotFoundException(UsernameNotFoundException e) {
log.error(e.getMessage(), e);
return R.error(e.getMessage());
}
/**
*
*/

@ -9,6 +9,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@ -18,6 +19,7 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled=true,jsr250Enabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired

@ -27,12 +27,17 @@ public class WaynConfig {
public static String getUploadDir() {
return uploadDir;
}
public void setUploadDir(String uploadDir) {
WaynConfig.uploadDir = uploadDir;
}
public static String getDownloadPath() {
return getUploadDir() + "/download/";
}
public void setUploadDir(String uploadDir) {
WaynConfig.uploadDir = uploadDir;
public static String getAvatarPath() {
return getUploadDir() + "/avatar/";
}
public static String getName() {

@ -37,6 +37,11 @@ public class LoginUserDetail implements UserDetails {
this.user = user;
}
public LoginUserDetail(SysUser user, Set<String> permissions) {
this.user = user;
this.permissions = permissions;
}
public LoginUserDetail() {
}

@ -0,0 +1,153 @@
package com.wayn.framework.security.service;
import com.wayn.common.util.ServletUtils;
import com.wayn.framework.security.LoginUserDetail;
import com.wayn.project.system.domain.SysRole;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.Objects;
import java.util.Set;
/**
* RuoYi ssSpringSecurity
*
* @author ruoyi
*/
@Service("ss")
public class PermissionService {
/**
*
*/
private static final String ALL_PERMISSION = "*:*:*";
/**
*
*/
private static final String SUPER_ADMIN = "admin";
private static final String ROLE_DELIMETER = ",";
private static final String PERMISSION_DELIMETER = ",";
@Autowired
private TokenService tokenService;
/**
*
*
* @param permission
* @return
*/
public boolean hasPermi(String permission) {
if (StringUtils.isEmpty(permission)) {
return false;
}
LoginUserDetail loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
if (Objects.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) {
return false;
}
return hasPermissions(loginUser.getPermissions(), permission);
}
/**
* hasPermi
*
* @param permission
* @return
*/
public boolean lacksPermi(String permission) {
return hasPermi(permission) != true;
}
/**
*
*
* @param permissions PERMISSION_NAMES_DELIMETER
* @return
*/
public boolean hasAnyPermi(String permissions) {
if (StringUtils.isEmpty(permissions)) {
return false;
}
LoginUserDetail loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
if (Objects.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) {
return false;
}
Set<String> authorities = loginUser.getPermissions();
for (String permission : permissions.split(PERMISSION_DELIMETER)) {
if (permission != null && hasPermissions(authorities, permission)) {
return true;
}
}
return false;
}
/**
*
*
* @param role
* @return
*/
public boolean hasRole(String role) {
if (StringUtils.isEmpty(role)) {
return false;
}
LoginUserDetail loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
if (Objects.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles())) {
return false;
}
for (SysRole sysRole : loginUser.getUser().getRoles()) {
String roleKey = sysRole.getRoleKey();
if (SUPER_ADMIN.contains(roleKey) || roleKey.contains(StringUtils.trim(role))) {
return true;
}
}
return false;
}
/**
* isRole
*
* @param role
* @return
*/
public boolean lacksRole(String role) {
return hasRole(role) != true;
}
/**
*
*
* @param roles ROLE_NAMES_DELIMETER
* @return
*/
public boolean hasAnyRoles(String roles) {
if (StringUtils.isEmpty(roles)) {
return false;
}
LoginUserDetail loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
if (Objects.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles())) {
return false;
}
for (String role : roles.split(ROLE_DELIMETER)) {
if (hasRole(role)) {
return true;
}
}
return false;
}
/**
*
*
* @param permissions
* @param permission
* @return
*/
private boolean hasPermissions(Set<String> permissions, String permission) {
return permissions.contains(ALL_PERMISSION) || permissions.contains(StringUtils.trim(permission));
}
}

@ -3,6 +3,7 @@ package com.wayn.framework.security.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wayn.framework.security.LoginUserDetail;
import com.wayn.project.system.domain.SysUser;
import com.wayn.project.system.service.IDeptService;
import com.wayn.project.system.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
@ -20,9 +21,15 @@ public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private IUserService iUserService;
@Autowired
private IDeptService iDeptService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private SysPermissionService permissionService;
public static void main(String[] args) {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
System.out.println(bCryptPasswordEncoder.encode("123456"));
@ -30,13 +37,14 @@ public class UserDetailsServiceImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
SysUser dbUser = iUserService.getOne(new QueryWrapper<SysUser>().eq("user_name", username));
if (dbUser == null) {
SysUser user = iUserService.getOne(new QueryWrapper<SysUser>().eq("user_name", username));
if (user == null) {
// List<GrantedAuthority> authorityLists = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER");
log.info("登录用户:{} 不存在.", username);
throw new UsernameNotFoundException("登录用户:" + username + " 不存在");
}
return new LoginUserDetail(dbUser);
user.setSysDept(iDeptService.getById(user.getDeptId()));
return new LoginUserDetail(user, permissionService.getMenuPermission(user));
}
}

@ -8,6 +8,7 @@ import com.wayn.project.system.service.IDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@ -22,6 +23,7 @@ public class DeptController {
@Autowired
private IDeptService iDeptService;
@PreAuthorize("@ss.hasPermi('system:dept:list')")
@ApiOperation(value = "部门列表", notes = "部门列表")
@GetMapping("/list")
public R list(SysDept dept) {
@ -29,6 +31,7 @@ public class DeptController {
return R.success().add("data", depts);
}
@PreAuthorize("@ss.hasPermi('system:dept:add')")
@ApiOperation(value = "保存部门", notes = "保存部门")
@PostMapping
public R addDept(@Validated @RequestBody SysDept dept) {
@ -42,6 +45,7 @@ public class DeptController {
return R.result(iDeptService.save(dept));
}
@PreAuthorize("@ss.hasPermi('system:dept:update')")
@ApiOperation(value = "更新角色", notes = "更新部门")
@PutMapping
public R updateDept(@Validated @RequestBody SysDept dept) {
@ -66,12 +70,14 @@ public class DeptController {
return R.success().add("deptTree", iDeptService.buildDeptTreeSelect(depts));
}
@PreAuthorize("@ss.hasPermi('system:dept:query')")
@ApiOperation(value = "获取部门详细", notes = "获取部门详细")
@GetMapping("{deptId}")
public R getDept(@PathVariable Long deptId) {
return R.success().add("data", iDeptService.getById(deptId));
}
@PreAuthorize("@ss.hasPermi('system:dept:delete')")
@ApiOperation(value = "删除部门", notes = "删除部门")
@DeleteMapping("{deptId}")
public R deleteDept(@PathVariable Long deptId) {

@ -13,6 +13,7 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@ -31,6 +32,7 @@ public class MenuController extends BaseController {
@Autowired
private TokenService tokenService;
@PreAuthorize("@ss.hasPermi('system:menu:list')")
@ApiOperation(value = "菜单列表", notes = "菜单列表")
@GetMapping("/list")
public R list(SysMenu menu) {
@ -58,10 +60,11 @@ public class MenuController extends BaseController {
public R roleMenuTreeselect(@PathVariable Long roleId) {
LoginUserDetail loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
Long userId = loginUser.getUser().getUserId();
List<SysMenu> menus = iMenuService.selectMenuList(null, userId);
List<SysMenu> menus = iMenuService.selectMenuList(new SysMenu(), userId);
return R.success().add("menuTree", iMenuService.buildMenuTreeSelect(menus)).add("checkedKeys", iMenuService.selectCheckedkeys(roleId));
}
@PreAuthorize("@ss.hasPermi('system:menu:add')")
@ApiOperation(value = "保存菜单", notes = "保存菜单")
@PostMapping
public R addRole(@Validated @RequestBody SysMenu menu) {
@ -73,6 +76,7 @@ public class MenuController extends BaseController {
return R.result(iMenuService.save(menu));
}
@PreAuthorize("@ss.hasPermi('system:menu:update')")
@ApiOperation(value = "更新菜单", notes = "更新菜单")
@PutMapping
public R updateRole(@Validated @RequestBody SysMenu menu) {
@ -84,12 +88,14 @@ public class MenuController extends BaseController {
return R.result(iMenuService.updateById(menu));
}
@PreAuthorize("@ss.hasPermi('system:menu:query')")
@ApiOperation(value = "获取菜单详细", notes = "获取菜单详细")
@GetMapping("/{menuId}")
public R getMenu(@PathVariable Long menuId) {
return R.success().add("data", iMenuService.getById(menuId));
}
@PreAuthorize("@ss.hasPermi('system:menu:delete')")
@ApiOperation(value = "删除菜单", notes = "删除菜单")
@DeleteMapping("/{menuId}")
public R deleteMenu(@PathVariable Long menuId) {
@ -101,5 +107,4 @@ public class MenuController extends BaseController {
}
return R.success().add("data", iMenuService.removeById(menuId));
}
}

@ -0,0 +1,92 @@
package com.wayn.project.system.controller;
import com.wayn.common.util.R;
import com.wayn.common.util.SecurityUtils;
import com.wayn.common.util.ServletUtils;
import com.wayn.common.util.file.FileUploadUtil;
import com.wayn.common.util.http.HttpUtil;
import com.wayn.framework.config.WaynConfig;
import com.wayn.framework.security.LoginUserDetail;
import com.wayn.framework.security.service.TokenService;
import com.wayn.project.system.domain.SysUser;
import com.wayn.project.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@RestController
@RequestMapping("system/user/profile")
public class ProfileController {
@Autowired
private IUserService iUserService;
@Autowired
private TokenService tokenService;
@GetMapping
public R profile() {
R success = R.success();
LoginUserDetail loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
success.add("user", loginUser.getUser());
success.add("roleGroup", iUserService.selectUserRoleGroup(loginUser.getUsername()));
return success;
}
@PutMapping
public R updateProfile(@RequestBody SysUser user) {
if (iUserService.updateById(user)) {
LoginUserDetail loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
// 更新缓存用户信息
loginUser.getUser().setNickName(user.getNickName());
loginUser.getUser().setPhone(user.getPhone());
loginUser.getUser().setEmail(user.getEmail());
loginUser.getUser().setSex(user.getSex());
tokenService.refreshToken(loginUser);
return R.success();
}
return R.error("修改个人信息异常,请联系管理员");
}
@PutMapping("/updatePwd")
public R updatePwd(String oldPassword, String newPassword) {
LoginUserDetail loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
String password = loginUser.getPassword();
if (!password.equals(oldPassword)) {
return R.error("旧密码错误");
} else if (oldPassword.equals(newPassword)) {
return R.error("新密码不能与旧密码相同");
}
boolean result = iUserService.update().set("password", SecurityUtils.encryptPassword(newPassword)).update();
if (result) {
// 更新缓存用户信息
loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
tokenService.refreshToken(loginUser);
return R.success();
}
return R.error("修改密码异常,请联系管理员");
}
@PostMapping("/avatar")
public R avatar(@RequestParam("avatarfile") MultipartFile file, HttpServletRequest request) throws IOException {
if (!file.isEmpty()) {
LoginUserDetail loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
String avatar = FileUploadUtil.uploadFile(file, WaynConfig.getAvatarPath());
String requestUrl = HttpUtil.getRequestContext(request);
String imgUrl = requestUrl + "/upload/avatar/" + avatar;
boolean result = iUserService.update().set("avatar", imgUrl).eq("user_name", loginUser.getUsername()).update();
if (result) {
R success = R.success();
success.add("imgUrl", imgUrl);
// 更新缓存用户头像
loginUser.getUser().setAvatar(imgUrl);
tokenService.refreshToken(loginUser);
return success;
}
}
return R.error("上传图片异常,请联系管理员");
}
}

@ -12,6 +12,7 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@ -27,6 +28,8 @@ public class RoleController extends BaseController {
@Autowired
private IRoleService iRoleService;
@PreAuthorize("@ss.hasPermi('system:role:list')")
@ApiOperation(value = "角色列表", notes = "角色列表")
@GetMapping("/list")
public R list(SysRole role) {
@ -34,6 +37,7 @@ public class RoleController extends BaseController {
return R.success().add("page", iRoleService.listPage(page, role));
}
@PreAuthorize("@ss.hasPermi('system:role:add')")
@ApiOperation(value = "保存角色", notes = "保存角色")
@PostMapping
public R addRole(@Validated @RequestBody SysRole role) {
@ -47,6 +51,7 @@ public class RoleController extends BaseController {
return R.result(iRoleService.insertRoleAndMenu(role));
}
@PreAuthorize("@ss.hasPermi('system:role:update')")
@ApiOperation(value = "更新用户", notes = "更新用户")
@PutMapping
public R updateRole(@Validated @RequestBody SysRole role) {
@ -60,6 +65,7 @@ public class RoleController extends BaseController {
return R.result(iRoleService.updateRoleAndMenu(role));
}
@PreAuthorize("@ss.hasPermi('system:role:update')")
@ApiOperation(value = "更新角色状态", notes = "更新角色状态")
@PutMapping("changeStatus")
public R changeStatus(@RequestBody SysRole role) {
@ -68,12 +74,14 @@ public class RoleController extends BaseController {
return R.result(iRoleService.updateById(role));
}
@PreAuthorize("@ss.hasPermi('system:role:query')")
@ApiOperation("获取角色详细")
@GetMapping("/{roleId}")
public R getRole(@PathVariable Long roleId) {
return R.success().add("data", iRoleService.getById(roleId));
}
@PreAuthorize("@ss.hasPermi('system:role:delete')")
@ApiOperation("删除角色")
@DeleteMapping("/{roleIds}")
public R deleteRole(@PathVariable List<Long> roleIds) {
@ -81,6 +89,7 @@ public class RoleController extends BaseController {
return R.success();
}
@PreAuthorize("@ss.hasPermi('system:role:export')")
@GetMapping("/export")
public R export(SysRole role) {
List<SysRole> list = iRoleService.list(role);

@ -14,6 +14,7 @@ import com.wayn.project.system.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@ -34,6 +35,7 @@ public class UserController extends BaseController {
@Autowired
private IRoleService iRoleService;
@PreAuthorize("@ss.hasPermi('system:user:list')")
@ApiOperation(value = "用户列表", notes = "用户列表")
@GetMapping("/list")
public R list(SysUser user) {
@ -41,6 +43,7 @@ public class UserController extends BaseController {
return R.success().add("page", iUserService.listPage(page, user));
}
@PreAuthorize("@ss.hasPermi('system:user:query')")
@ApiOperation("获取用户详细")
@GetMapping(value = {"/", "/{userId}"})
public R getInfo(@PathVariable(value = "userId", required = false) Long userId) {
@ -53,6 +56,7 @@ public class UserController extends BaseController {
return success;
}
@PreAuthorize("@ss.hasPermi('system:user:add')")
@ApiOperation("添加用户")
@PostMapping
public R addUser(@Validated @RequestBody SysUser user) {
@ -69,6 +73,7 @@ public class UserController extends BaseController {
return R.result(iUserService.insertUserAndRole(user));
}
@PreAuthorize("@ss.hasPermi('system:user:update')")
@ApiOperation("更新用户")
@PutMapping
public R updateUser(@Validated @RequestBody SysUser user) {
@ -83,6 +88,7 @@ public class UserController extends BaseController {
return R.result(iUserService.updateUserAndRole(user));
}
@PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
@PutMapping("resetPwd")
public R resetPwd(@RequestBody SysUser user) {
iUserService.checkUserAllowed(user);
@ -92,6 +98,7 @@ public class UserController extends BaseController {
return R.result(iUserService.updateById(user));
}
@PreAuthorize("@ss.hasPermi('system:user:update')")
@ApiOperation(value = "更新用户状态", notes = "更新用户状态")
@PutMapping("changeStatus")
public R changeStatus(@RequestBody SysUser user) {
@ -100,6 +107,7 @@ public class UserController extends BaseController {
return R.result(iUserService.updateById(user));
}
@PreAuthorize("@ss.hasPermi('system:user:delete')")
@ApiOperation("删除用户")
@DeleteMapping("/{userIds}")
public R deleteUser(@PathVariable List<Long> userIds) {
@ -107,6 +115,7 @@ public class UserController extends BaseController {
return R.success();
}
@PreAuthorize("@ss.hasPermi('system:user:export')")
@GetMapping("/export")
public R export(SysUser user) {
List<SysUser> list = iUserService.list(user);
@ -114,6 +123,7 @@ public class UserController extends BaseController {
return R.success(ExcelUtil.exportExcel(list, SysUser.class, "用户数据.xls"));
}
@PreAuthorize("@ss.hasPermi('system:user:import')")
@ResponseBody
@PostMapping("/importData")
public R importData(@RequestParam("file") MultipartFile file) throws Exception {

@ -16,4 +16,6 @@ public interface RoleMapper extends BaseMapper<SysRole> {
List<Integer> selectRoleListByUserId(Long userId);
List<SysRole> selectRoleList(SysRole role);
List<SysRole> selectRolesByUserName(String userName);
}

@ -65,4 +65,12 @@ public interface IUserService extends IService<SysUser> {
* @return
*/
List<SysUser> list(SysUser user);
/**
* ID
*
* @param userName
* @return
*/
String selectUserRoleGroup(String userName);
}

@ -6,11 +6,14 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wayn.common.constant.SysConstants;
import com.wayn.common.exception.BusinessException;
import com.wayn.project.system.domain.SysRole;
import com.wayn.project.system.domain.SysUser;
import com.wayn.project.system.domain.SysUserRole;
import com.wayn.project.system.mapper.RoleMapper;
import com.wayn.project.system.mapper.UserMapper;
import com.wayn.project.system.service.IUserRoleService;
import com.wayn.project.system.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -25,6 +28,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements
@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;
@Autowired
private IUserRoleService iUserRoleService;
@ -88,4 +94,17 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements
public List<SysUser> list(SysUser user) {
return userMapper.selectUserList(user);
}
@Override
public String selectUserRoleGroup(String userName) {
List<SysRole> list = roleMapper.selectRolesByUserName(userName);
StringBuffer idsStr = new StringBuffer();
for (SysRole role : list) {
idsStr.append(role.getRoleName()).append(",");
}
if (StringUtils.isNotEmpty(idsStr.toString())) {
return idsStr.substring(0, idsStr.length() - 1);
}
return idsStr.toString();
}
}

@ -77,4 +77,8 @@
and r.del_flag = 0
</where>
</select>
<select id="selectRolesByUserName" parameterType="string" resultMap="SysRoleResult">
<include refid="selectRoleVo"/>
WHERE r.del_flag = '0' and u.user_name = #{userName}
</select>
</mapper>
Loading…
Cancel
Save