Compare commits

..

No commits in common. "a6f4c2ae0073fef427cfb8d78a3d0df7aab2de49" and "f3ebc49a60462c36b412d0cf86e9420131151fe5" have entirely different histories.

42 changed files with 125 additions and 579 deletions

View File

@ -6,14 +6,20 @@ import com.zsc.edu.bill.modules.system.entity.*;
import com.zsc.edu.bill.modules.system.repo.DeptRepository;
import com.zsc.edu.bill.modules.system.repo.RoleRepository;
import com.zsc.edu.bill.modules.system.repo.UserRepository;
import com.zsc.edu.bill.modules.system.repo.UserRolesRepository;
import com.zsc.edu.bill.modules.system.repo.UserRolesReposity;
import com.zsc.edu.bill.modules.system.service.RoleService;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
@RequiredArgsConstructor
@Component
@Profile("!test")
@ -22,7 +28,7 @@ public class FirstTimeInitializer implements CommandLineRunner {
private final DeptRepository deptRepo;
private final RoleRepository roleRepo;
private final RoleService roleService;
private final UserRolesRepository userRolesRepo;
private final UserRolesReposity userRolesRepo;
private final UserRepository userRepo;
private final PasswordEncoder passwordEncoder;
@ -40,7 +46,7 @@ public class FirstTimeInitializer implements CommandLineRunner {
if (roleRepo.selectCount(new QueryWrapper<>()) == 0) {
RoleDto dto = new RoleDto();
dto.setName("超级管理员");
// dto.setAuthorities(new HashSet<>(Arrays.asList(Authority.values())));
dto.setAuthorities(new HashSet<>(Arrays.asList(Authority.values())));
role = roleService.create(dto);
}
if (userRepo.selectCount(new QueryWrapper<>()) == 0) {

View File

@ -5,21 +5,16 @@ import com.zsc.edu.bill.exception.StateException;
import com.zsc.edu.bill.modules.system.entity.Authority;
import com.zsc.edu.bill.modules.system.entity.RoleAuthority;
import com.zsc.edu.bill.modules.system.entity.User;
import com.zsc.edu.bill.modules.system.repo.AuthorityRepository;
import com.zsc.edu.bill.modules.system.repo.RoleAuthoritiesRepository;
import com.zsc.edu.bill.modules.system.repo.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
@ -30,7 +25,7 @@ import java.util.stream.Collectors;
public class JpaUserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepo;
private final AuthorityRepository authorityRepo;
private final RoleAuthoritiesRepository roleAuthoritiesRepository;
@Override
@Transactional(rollbackFor = Exception.class)
@ -40,13 +35,12 @@ public class JpaUserDetailsServiceImpl implements UserDetailsService {
throw new StateException("用户 '" + username + "' 已被禁用!请联系管理员");
}
user.role.authorities=authorityRepo.selectAuthoritiesByRoleId(user.getRoleId());
List<RoleAuthority> roleAuthorities= roleAuthoritiesRepository.selectByRoleId(user.getRoleId());
user.role.authorities=roleAuthorities.stream()
.map(i -> Authority.valueOf(i.getAuthority()))
.collect(Collectors.toSet());
// List<GrantedAuthority> authorities = new ArrayList<>();
// authorities=authorityList.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
// return authorities;
// .orElseThrow(() ->
// new UsernameNotFoundException("用户 '" + username + "' 不存在!")

View File

@ -91,7 +91,7 @@ public class SpringSecurityConfig {
.rememberMe(rememberMe -> rememberMe
.userDetailsService(userDetailsService)
.tokenRepository(persistentTokenRepository()))
.csrf(csrf -> csrf.ignoringRequestMatchers("/api/internal/**", "/api/rest/user/logout","/api/rest/user/login","/api/rest/user/register"))
.csrf(csrf -> csrf.ignoringRequestMatchers("/api/internal/**", "/api/rest/user/logout","/api/rest/user/register"))
.sessionManagement(session -> session
.maximumSessions(3)
.sessionRegistry(sessionRegistry)

View File

@ -7,7 +7,6 @@ import com.zsc.edu.bill.modules.system.entity.User;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
@ -33,7 +32,7 @@ public class UserDetailsImpl implements UserDetails {
public Dept dept;
public Role role;
public Set<SimpleGrantedAuthority> authorities;
public Set<Authority> authorities;
public UserDetailsImpl(Long id, String username, String password, String nickName, Boolean enabled, Dept dept, Role role, Set<Authority> authorities) {
this.id = id;
@ -43,7 +42,7 @@ public class UserDetailsImpl implements UserDetails {
this.nickName = nickName;
this.dept = dept;
this.role = role;
this.authorities = authorities.stream().map(authority -> new SimpleGrantedAuthority(authority.getName())).collect(Collectors.toSet());;
this.authorities = authorities;
}
@ -59,6 +58,7 @@ public class UserDetailsImpl implements UserDetails {
user.dept,
user.role,
user.role.authorities
);
}

View File

@ -75,9 +75,9 @@ public class BillController {
* 删除票据
* @return ture/false
*/
@DeleteMapping("{id}")
@DeleteMapping
@PreAuthorize("hasAuthority('BILL_DELETE')")
public Boolean delete(@PathVariable Long id){
public Boolean delete(Long id){
return service.removeById(id);
}
@ -101,8 +101,8 @@ public class BillController {
public Bill detail(@PathVariable Long id){
return service.getById(id);
}
/**
* 审核票据
/*
*审核票据
**/
@PatchMapping("audit/{id}")
@PreAuthorize("hasAuthority('BILL_AUDIT')")

View File

@ -1,81 +0,0 @@
package com.zsc.edu.bill.modules.system.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsc.edu.bill.modules.system.dto.AuthorityDto;
import com.zsc.edu.bill.modules.system.entity.Authority;
import com.zsc.edu.bill.modules.system.query.AuthorityQuery;
import com.zsc.edu.bill.modules.system.service.AuthorityService;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
/**
* 权限Controller
*
* @author zhuang
*/
@AllArgsConstructor
@RestController
@RequestMapping("/api/rest/auth")
public class AuthorityController {
private AuthorityService service;
/**
* 返回权限列表 hasAuthority('AUTHORITY_QUERY')
*
* @param query 查询表单
* @return 权限列表
*/
@GetMapping
@PreAuthorize("hasAuthority('AUTHORITY_QUERY')")
public Page<Authority> query(AuthorityQuery query, Page<Authority> page) {
return service.page(page, query.wrapper());
}
/**
* 新建权限 hasAuthority('AUTHORITY_CREATE')
*
* @param dto 表单数据
* @return Authority 新建的权限
*/
@PostMapping
@PreAuthorize("hasAuthority('AUTHORITY_CREATE')")
public Authority create(@RequestBody AuthorityDto dto) {
return service.create(dto);
}
/**
* 更新权限 hasAuthority('AUTHORITY_UPDATE')
*
* @param dto 表单数据
* @param id 权限ID
* @return Dept 更新后的权限信息
*/
@PatchMapping("/{id}")
@PreAuthorize("hasAuthority('AUTHORITY_UPDATE')")
public Boolean update(@RequestBody AuthorityDto dto, @PathVariable("id") Long id) {
return service.update(dto, id);
}
/***
* 删除权限 hasAuthority('AUTHORITY_DELETE')
* @param id 权限ID
* @return Boolean 是否删除成功
*/
@DeleteMapping("/{id}")
@PreAuthorize("hasAuthority('AUTHORITY_DELETE')")
public Boolean delete(@PathVariable("id") Long id) {
return service.removeById(id);
}
/**
* 更新权限启用状态
* */
@PatchMapping("/toggle/{id}")
@PreAuthorize("hasAuthority('AUTHORITY_TOGGLE')")
public Boolean toggle(@PathVariable("id") Long id) {
return service.toggle(id);
}
}

View File

@ -1,12 +1,12 @@
package com.zsc.edu.bill.modules.system.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.zsc.edu.bill.modules.system.dto.RoleDto;
import com.zsc.edu.bill.modules.system.entity.Role;
import com.zsc.edu.bill.modules.system.mapper.RoleMapper;
import com.zsc.edu.bill.modules.system.query.RoleQuery;
import com.zsc.edu.bill.modules.system.service.RoleService;
import com.zsc.edu.bill.modules.system.vo.RoleVo;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@ -85,7 +85,7 @@ public class RoleController {
*/
@GetMapping("{id}")
@PreAuthorize("hasAuthority('ROLE_QUERY')")
public RoleVo detail(@PathVariable Long id) {
public Role detail(@PathVariable Long id) {
return service.detail(id);
}

View File

@ -8,11 +8,13 @@ import com.zsc.edu.bill.modules.system.dto.UserCreateDto;
import com.zsc.edu.bill.modules.system.dto.UserSelfUpdateDto;
import com.zsc.edu.bill.modules.system.dto.UserSelfUpdatePasswordDto;
import com.zsc.edu.bill.modules.system.dto.UserUpdateDto;
import com.zsc.edu.bill.modules.system.entity.Authority;
import com.zsc.edu.bill.modules.system.entity.Role;
import com.zsc.edu.bill.modules.system.entity.User;
import com.zsc.edu.bill.modules.system.query.UserQuery;
import com.zsc.edu.bill.modules.system.service.*;
import com.zsc.edu.bill.modules.system.service.DeptService;
import com.zsc.edu.bill.modules.system.service.RoleAuthService;
import com.zsc.edu.bill.modules.system.service.RoleService;
import com.zsc.edu.bill.modules.system.service.UserService;
import com.zsc.edu.bill.modules.system.vo.UserDetail;
import com.zsc.edu.bill.modules.system.vo.UserVo;
import lombok.AllArgsConstructor;
@ -24,7 +26,6 @@ import org.springframework.web.bind.annotation.*;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* 用户Controller
@ -41,7 +42,6 @@ public class UserController {
private final RoleService roleService;
private final DeptService deptService;
private final RoleAuthService roleAuthService;
private final AuthorityService authorityService;
/**
* 登录前获取csrfToken信息
@ -72,8 +72,7 @@ public class UserController {
user.dept = deptService.getById(user.deptId);
Role role= roleService.getOne(new QueryWrapper<Role>().eq("id",user.roleId));
userDetail.setPermissions(role.getName());
Set<Authority> authorities = authorityService.selectAuthoritiesByRoleId(role.getId());
userDetail.setAuthorities(authorities.stream().toList());
userDetail.setAuthorities(roleAuthService.getAuthorityByUserId(role.getId()));
userDetail.setUser(user);
@ -114,7 +113,7 @@ public class UserController {
* @return 分页用户信息
*/
@GetMapping
@PreAuthorize("hasAuthority('USER_QUERY·')")
@PreAuthorize("hasAuthority('USER_QUERY')")
public Page<UserVo> query(UserQuery query, PageDTO<User> page) {
return service.page(query, page);
}

View File

@ -1,39 +0,0 @@
package com.zsc.edu.bill.modules.system.dto;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zsc.edu.bill.modules.system.entity.Authority;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.StringUtils;
/**
* 权限Dto
* @author zhuang
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AuthorityDto {
/**
* 权限名
*/
@NotBlank(message = "名字不能为空")
public String name;
/**
* 启用状态
*/
private Boolean enabled = true;
/**
* 备注
*/
private String remark;
public LambdaUpdateWrapper<Authority> updateWrapper(Long id) {
LambdaUpdateWrapper<Authority> updateWrapper = new LambdaUpdateWrapper<>();
return updateWrapper.eq(Authority::getId, id)
.set(Authority::getName, name)
.set(StringUtils.hasText(remark), Authority::getRemark, remark);
}
}

View File

@ -1,70 +1,49 @@
package com.zsc.edu.bill.modules.system.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
import org.springframework.security.core.GrantedAuthority;
/**
* 操作权限
*
* @author harry yao
*/
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
@TableName("sys_authority")
public class Authority extends BaseEntity {
public enum Authority implements GrantedAuthority {
/**
* 权限名
* 部门管理
*/
public String name;
DEPT_QUERY,
DEPT_CREATE,
DEPT_UPDATE,
DEPT_DELETE,
/**
* 启用状态
* 角色管理
*/
private Boolean enabled = true;
ROLE_CREATE,
ROLE_QUERY,
ROLE_UPDATE,
/**
* 备注
* 用户管理
*/
private String remark;
//
// /**
// * 部门管理
// */
// DEPT_QUERY,
// DEPT_CREATE,
// DEPT_UPDATE,
// DEPT_DELETE,
//
// /**
// * 角色管理
// */
// ROLE_CREATE,
// ROLE_QUERY,
// ROLE_UPDATE,
//
// /**
// * 用户管理
// */
// USER_QUERY,
// USER_CREATE,
// USER_UPDATE,
// USER_DELETE,
// /**
// * 票据管理
// * */
// BILL_QUERY,
// BILL_CREATE,
// BILL_UPDATE,
// BILL_AUDIT,
// BILL_CHOOSE_AUDITOR,
// BILL_DELETE;
//
//
// @Override
// public String getAuthority() {
// return name();
// }
USER_QUERY,
USER_CREATE,
USER_UPDATE,
USER_DELETE,
/**
* 票据管理
* */
BILL_QUERY,
BILL_CREATE,
BILL_UPDATE,
BILL_AUDIT,
BILL_CHOOSE_AUDITOR,
BILL_DELETE;
@Override
public String getAuthority() {
return name();
}
}

View File

@ -1,21 +1,16 @@
package com.zsc.edu.bill.modules.system.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.zsc.edu.bill.modules.system.repo.RoleAuthoritiesRepository;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* sys_role_authorities
* @author zhuang
* @author
*/
@AllArgsConstructor
@Getter
@ -25,8 +20,6 @@ public class RoleAuthority implements Serializable {
private Long roleId;
private Long authorityId;
private String authority;
// @TableField(exist = false)
// private Set<Authority> authorities;
}

View File

@ -7,7 +7,7 @@ import java.io.Serializable;
/**
* sys_users_roles
* @author zhuang
* @author
*/
@Data
@TableName("sys_users_roles")

View File

@ -1,14 +0,0 @@
package com.zsc.edu.bill.modules.system.mapper;
import com.zsc.edu.bill.common.mapstruct.BaseMapper;
import com.zsc.edu.bill.modules.system.dto.AuthorityDto;
import com.zsc.edu.bill.modules.system.entity.Authority;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author zhuang
*/
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface AuthorityMapper extends BaseMapper<AuthorityDto,Authority> {
}

View File

@ -1,32 +0,0 @@
package com.zsc.edu.bill.modules.system.query;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zsc.edu.bill.modules.system.entity.Authority;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.StringUtils;
/**
* @author zhuang
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AuthorityQuery {
/**
* 编码前缀匹配
*/
public String code;
/**
* 名称模糊查询
*/
public String name;
public LambdaQueryWrapper<Authority> wrapper() {
LambdaQueryWrapper<Authority> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.like(StringUtils.hasText(this.name), Authority::getName, this.name);
return queryWrapper;
}
}

View File

@ -2,8 +2,10 @@ package com.zsc.edu.bill.modules.system.query;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zsc.edu.bill.modules.system.entity.User;
import com.zsc.edu.bill.modules.system.vo.UserVo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.util.StringUtils;

View File

@ -1,15 +0,0 @@
package com.zsc.edu.bill.modules.system.repo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zsc.edu.bill.modules.system.entity.Authority;
import org.apache.ibatis.annotations.Param;
import java.util.Set;
/**
* @author zhuang
*/
public interface AuthorityRepository extends BaseMapper<Authority> {
Set<Authority> selectAuthoritiesByRoleId (@Param("roleId") Long roleId);
}

View File

@ -2,6 +2,7 @@ package com.zsc.edu.bill.modules.system.repo;
import com.zsc.edu.bill.modules.system.entity.RoleAuthority;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@ -10,8 +11,6 @@ import java.util.List;
*/
public interface RoleAuthoritiesRepository extends BaseMapper<RoleAuthority> {
// @Select("select * from sys_role_authorities where role_id=#{roleId}")
// List<RoleAuthority> selectByRoleId(Long roleId);
// List<RoleAuthority> selectAuthorityByRoleId(@Param("roleId") Long roleId);
@Select("select * from sys_role_authorities where role_id=#{roleId}")
List<RoleAuthority> selectByRoleId(Long roleId);
}

View File

@ -2,9 +2,6 @@ package com.zsc.edu.bill.modules.system.repo;
import com.zsc.edu.bill.modules.system.entity.Role;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zsc.edu.bill.modules.system.vo.RoleVo;
import org.apache.ibatis.annotations.Param;
/**
* <p>
@ -15,6 +12,4 @@ import org.apache.ibatis.annotations.Param;
* @since 2023-04-06
*/
public interface RoleRepository extends BaseMapper<Role> {
RoleVo selectRoleById(@Param("roleId") Long roleId);
}

View File

@ -1,11 +1,14 @@
package com.zsc.edu.bill.modules.system.repo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.zsc.edu.bill.modules.system.entity.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsc.edu.bill.modules.system.vo.UserVo;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
/**
* <p>

View File

@ -3,8 +3,5 @@ package com.zsc.edu.bill.modules.system.repo;
import com.zsc.edu.bill.modules.system.entity.UserRole;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* @author zhuang
*/
public interface UserRolesRepository extends BaseMapper<UserRole> {
public interface UserRolesReposity extends BaseMapper<UserRole> {
}

View File

@ -1,21 +0,0 @@
package com.zsc.edu.bill.modules.system.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zsc.edu.bill.modules.system.dto.AuthorityDto;
import com.zsc.edu.bill.modules.system.entity.Authority;
import java.util.Set;
/**
* @author zhuang
*/
public interface AuthorityService extends IService<Authority> {
Authority create(AuthorityDto authorityDto);
Boolean update(AuthorityDto authorityDto,Long id);
Boolean toggle(Long id);
Set<Authority> selectAuthoritiesByRoleId(Long roleId);
}

View File

@ -17,6 +17,7 @@ public interface DeptService extends IService<Dept> {
/**
* 创建部门
* @param dto
* @return
*/
Dept create(DeptDto dto);
@ -24,6 +25,7 @@ public interface DeptService extends IService<Dept> {
* 更新部门
* @param dto
* @param id
* @return
*/
Boolean edit(DeptDto dto, Long id);

View File

@ -3,6 +3,7 @@ package com.zsc.edu.bill.modules.system.service;
import com.zsc.edu.bill.modules.system.entity.RoleAuthority;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>
@ -13,8 +14,7 @@ import com.baomidou.mybatisplus.extension.service.IService;
* @since 2023-04-06
*/
public interface RoleAuthService extends IService<RoleAuthority> {
boolean removeByRoleId(Long id);
// List<String> getAuthorityByUserId(Long id);
List<String> getAuthorityByUserId(Long id);
}

View File

@ -4,7 +4,6 @@ package com.zsc.edu.bill.modules.system.service;
import com.zsc.edu.bill.modules.system.dto.RoleDto;
import com.zsc.edu.bill.modules.system.entity.Role;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zsc.edu.bill.modules.system.vo.RoleVo;
/**
* <p>
@ -20,7 +19,7 @@ public interface RoleService extends IService<Role> {
Boolean edit(RoleDto roleDto, Long id);
RoleVo detail(Long id);
Role detail(Long id);
Boolean toggle(Long id);

View File

@ -1,6 +1,7 @@
package com.zsc.edu.bill.modules.system.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zsc.edu.bill.framework.security.UserDetailsImpl;
import com.zsc.edu.bill.modules.system.dto.*;
import com.zsc.edu.bill.modules.system.entity.User;

View File

@ -1,56 +0,0 @@
package com.zsc.edu.bill.modules.system.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.bill.exception.ConstraintException;
import com.zsc.edu.bill.modules.system.dto.AuthorityDto;
import com.zsc.edu.bill.modules.system.entity.Authority;
import com.zsc.edu.bill.modules.system.mapper.AuthorityMapper;
import com.zsc.edu.bill.modules.system.repo.AuthorityRepository;
import com.zsc.edu.bill.modules.system.service.AuthorityService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Set;
/**
* @author zhuang
*/
@AllArgsConstructor
@Service
public class AuthorityServiceImpl extends ServiceImpl<AuthorityRepository, Authority> implements AuthorityService {
private AuthorityMapper mapper;
@Override
public Authority create(AuthorityDto authorityDto) {
boolean existsByName = count(new LambdaQueryWrapper<Authority>().eq(Authority::getName, authorityDto.getName())) > 0;
if (existsByName) {
throw new ConstraintException("name", authorityDto.name, "权限已存在");
}
Authority authority = mapper.toEntity(authorityDto);
save(authority);
return authority;
}
@Override
public Boolean update(AuthorityDto authorityDto, Long id) {
boolean isExists = count(new LambdaQueryWrapper<Authority>().ne(Authority::getId, id).eq(Authority::getName, authorityDto.getName())) > 0;
if (isExists) {
throw new ConstraintException("name", authorityDto.name, "同名权限已存在");
}
return update(authorityDto.updateWrapper(id));
}
@Override
public Boolean toggle(Long id) {
Authority authority = getById(id);
authority.setEnabled(!authority.getEnabled());
return updateById(authority);
}
@Override
public Set<Authority> selectAuthoritiesByRoleId(Long roleId){
return baseMapper.selectAuthoritiesByRoleId(roleId);
}
}

View File

@ -7,10 +7,9 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author zhuang
*/
@Service
public class RoleAuthServiceImpl extends ServiceImpl<RoleAuthoritiesRepository, RoleAuthority> implements RoleAuthService {
@Override
@ -18,11 +17,11 @@ public class RoleAuthServiceImpl extends ServiceImpl<RoleAuthoritiesRepository,
return remove(new LambdaQueryWrapper<RoleAuthority>().eq(RoleAuthority::getRoleId, roleId));
}
// @Override
// public List<String> getAuthorityByUserId(Long id) {
// List<RoleAuthority> list = list(new LambdaQueryWrapper<RoleAuthority>().eq(RoleAuthority::getRoleId, id));
// return list(new LambdaQueryWrapper<RoleAuthority>().eq(RoleAuthority::getRoleId, id)).stream().map(RoleAuthority::getAuthority).collect(Collectors.toList());
//
//
// }
@Override
public List<String> getAuthorityByUserId(Long id) {
List<RoleAuthority> list = list(new LambdaQueryWrapper<RoleAuthority>().eq(RoleAuthority::getRoleId, id));
return list(new LambdaQueryWrapper<RoleAuthority>().eq(RoleAuthority::getRoleId, id)).stream().map(RoleAuthority::getAuthority).collect(Collectors.toList());
}
}

View File

@ -7,14 +7,12 @@ import com.zsc.edu.bill.modules.system.entity.Role;
import com.zsc.edu.bill.modules.system.entity.RoleAuthority;
import com.zsc.edu.bill.modules.system.entity.UserRole;
import com.zsc.edu.bill.modules.system.mapper.RoleMapper;
import com.zsc.edu.bill.modules.system.repo.AuthorityRepository;
import com.zsc.edu.bill.modules.system.repo.RoleRepository;
import com.zsc.edu.bill.modules.system.repo.UserRolesRepository;
import com.zsc.edu.bill.modules.system.repo.UserRolesReposity;
import com.zsc.edu.bill.modules.system.service.RoleAuthService;
import com.zsc.edu.bill.modules.system.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.edu.bill.modules.system.vo.RoleVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
@ -36,11 +34,9 @@ import java.util.stream.Collectors;
public class RoleServiceImpl extends ServiceImpl<RoleRepository, Role> implements RoleService {
private final RoleMapper mapper;
private final UserRolesRepository urRepo;
private final UserRolesReposity urRepo;
private final RoleAuthService roleAuthService;
private final AuthorityRepository authorityRepository;
private final RoleRepository roleRepository;
@Override
public Role create(RoleDto dto) {
@ -80,7 +76,7 @@ public class RoleServiceImpl extends ServiceImpl<RoleRepository, Role> implement
if (dto.getAuthorities() != null && !dto.getAuthorities().isEmpty()) {
roleAuthService.remove(new LambdaQueryWrapper<RoleAuthority>().eq(RoleAuthority::getRoleId, id));
Set<Authority> authorities = new HashSet<>(dto.getAuthorities());
// roleAuthService.saveBatch(authorities.stream().map(authority -> new RoleAuthority(id, authority.getId())).collect(Collectors.toList()));
roleAuthService.saveBatch(authorities.stream().map(authority -> new RoleAuthority(id, authority.getAuthority())).collect(Collectors.toList()));
}
return updateById(role);
@ -99,17 +95,18 @@ public class RoleServiceImpl extends ServiceImpl<RoleRepository, Role> implement
}
@Override
public RoleVo detail(Long id) {
// Role role = getById(id);
// // TODO 联表查询
// // List<RoleAuthority> roleAuthorities = roleAuthService.list(new LambdaQueryWrapper<RoleAuthority>().eq(RoleAuthority::getRoleId, role.id));
// role.authorities = authorityRepository.selectAuthoritiesByRoleId(role.id);
return roleRepository.selectRoleById(id);
public Role detail(Long id) {
Role role = getById(id);
List<RoleAuthority> roleAuthorities = roleAuthService.list(new LambdaQueryWrapper<RoleAuthority>().eq(RoleAuthority::getRoleId, role.id));
role.authorities = roleAuthorities.stream()
.map(roleAuthority -> Authority.valueOf(roleAuthority.getAuthority()))
.collect(Collectors.toSet());
return role;
}
private boolean saveRoleAuths(Long roleId, Set<Authority> authorities) {
// 保存角色关联权限
List<RoleAuthority> roleAuthorities = authorities.stream().map(authority -> new RoleAuthority(roleId, authority.getId())).collect(Collectors.toList());
List<RoleAuthority> roleAuthorities = authorities.stream().map(authority -> new RoleAuthority(roleId, authority.getAuthority())).collect(Collectors.toList());
return roleAuthService.saveBatch(roleAuthorities);
}
}

View File

@ -3,6 +3,8 @@ package com.zsc.edu.bill.modules.system.utils;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.Getter;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

View File

@ -1,60 +0,0 @@
package com.zsc.edu.bill.modules.system.vo;
import com.zsc.edu.bill.modules.system.entity.Authority;
import lombok.Data;
import java.util.Date;
import java.util.List;
/**
* @author lenovo
*/
@Data
public class RoleVo {
/**
* 自增主键
*/
public Long id;
/**
* 角色名
*/
private String name;
/**
*级别
*/
private Integer level;
/**
* 描述
*/
private String description;
/**
* 数据权限
*/
private String dataScope;
/**
* 创建人
*/
private String createBy;
/**
* 更新人
*/
private String updateBy;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
/**
* 启用状态
*/
private Boolean enabled;
/**
* 备注
*/
private String remark;
private List<Authority> authorities;
}

View File

@ -2,10 +2,13 @@ package com.zsc.edu.bill.modules.system.vo;
import com.zsc.edu.bill.modules.system.entity.Authority;
import com.zsc.edu.bill.modules.system.entity.User;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
import java.util.Set;
/**
* @author ftz
@ -16,6 +19,6 @@ import java.util.List;
@Setter
public class UserDetail {
private User user;
private List<Authority> authorities;
private List<String> authorities;
private String permissions;
}

View File

@ -10,9 +10,9 @@ mybatis-plus:
spring:
datasource:
url: jdbc:mysql://localhost:3306/study?useSSL=false&allowPublicKeyRetrieval=true&createDatabaseIfNotExist=true&characterEncoding=utf8&serverTimezone=Hongkong
url: jdbc:mysql://106.53.179.133:3306/study?useSSL=false&allowPublicKeyRetrieval=true&createDatabaseIfNotExist=true&characterEncoding=utf8&serverTimezone=Hongkong
username: root
password: tian14384,
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
servlet:
multipart:

View File

@ -466,8 +466,6 @@ CREATE TABLE `sys_role` (
INDEX `role_name_index`(`name` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 84 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '角色表' ROW_FORMAT = COMPACT;
-- ----------------------------
-- Records of sys_role
-- ----------------------------
@ -475,33 +473,13 @@ INSERT INTO `sys_role` VALUES (50, 'admin', NULL, NULL, NULL, NULL, NULL, '2024-
INSERT INTO `sys_role` VALUES (51, 'user', NULL, NULL, NULL, NULL, NULL, '2024-01-16 09:22:30', '2024-02-21 07:06:10', b'1', '客户');
INSERT INTO `sys_role` VALUES (54, 'auditor', NULL, NULL, NULL, NULL, NULL, '2024-01-19 16:15:45', '2024-01-24 14:48:55', b'1', '审核员');
-- ----------------------------
-- Table structure for sys_authorities
-- ----------------------------
DROP TABLE IF EXISTS `sys_authority`;
CREATE TABLE `sys_authority` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '名称',
`enabled` bit(1) NULL DEFAULT NULL COMMENT '状态',
`create_by` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '创建者',
`update_by` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '更新者',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建日期',
`update_time` datetime NULL DEFAULT NULL COMMENT '更新时间',
`remark` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uniq_name`(`name` ASC) USING BTREE,
INDEX `authority_name_index`(`name` ASC) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci COMMENT = '权限表' ROW_FORMAT = COMPACT;
-- ----------------------------
-- Table structure for sys_role_authorities
-- ----------------------------
DROP TABLE IF EXISTS `sys_role_authorities`;
CREATE TABLE `sys_role_authorities` (
`role_id` bigint NOT NULL,
`authority_id` bigint NOT NULL ,
PRIMARY KEY (`role_id`, `authority_id`) USING BTREE,
`authority` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
INDEX `FKbyfnfkpgrf4jmo3nf97arsphd`(`role_id` ASC) USING BTREE
) ENGINE = InnoDB CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = COMPACT;

View File

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zsc.edu.bill.modules.system.repo.AuthorityRepository">
<!-- <resultMap id="AuthorityMap" type="com.zsc.edu.bill.modules.system.entity.Authority">-->
<!-- <id column="id" jdbcType="BIGINT" property="id"/>-->
<!-- <result column="name" jdbcType="VARCHAR" property="name"/>-->
<!-- <result column="create_by" jdbcType="VARCHAR" property="createBy"/>-->
<!-- <result column="update_by" jdbcType="VARCHAR" property="updateBy"/>-->
<!-- <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>-->
<!-- <result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/>-->
<!-- <result column="enabled" jdbcType="BOOLEAN" property="enabled"/>-->
<!-- <result column="remark" jdbcType="VARCHAR" property="remark"/>-->
<!-- </resultMap>-->
<select id="selectAuthoritiesByRoleId" resultType="authority">
select sa.* from sys_authority sa
left join sys_role_authorities ra on sa.id=ra.authority_id
where ra.role_id=#{roleId}
</select>
</mapper>

View File

@ -11,4 +11,5 @@
<!-- </select>-->
</mapper>

View File

@ -1,37 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zsc.edu.bill.modules.system.repo.RoleRepository">
<!--查角色包含权限-->
<resultMap id="roleMap" type="com.zsc.edu.bill.modules.system.vo.RoleVo" autoMapping="true">
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="create_by" jdbcType="VARCHAR" property="createBy"/>
<result column="update_by" jdbcType="VARCHAR" property="updateBy"/>
<result column="create_time" jdbcType="DATE" property="createTime"/>
<result column="update_time" jdbcType="DATE" property="updateTime"/>
<result column="enabled" jdbcType="BIT" property="enabled"/>
<result column="remark" jdbcType="VARCHAR" property="remark"/>
<collection property="authorities" ofType="com.zsc.edu.bill.modules.system.entity.Authority" autoMapping="true" columnPrefix="authority_">
<id column="id" jdbcType="BIT" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="remark" jdbcType="VARCHAR" property="remark"/>
</collection>
</resultMap>
<!-- <select id="selectRoleById" resultMap="roleMap">-->
<!-- select * from-->
<!-- sys_role sr, sys_role_authorities sra, sys_authority sa-->
<!-- where sr.id=sra.role_id and sra.authority_id=sa.id-->
<!-- and sr.id=#{roleId}-->
<!-- </select>-->
<select id="selectRoleById" resultMap="roleMap">
select sr.*,
sa.id as authority_id, sa.name as authority_name, sa.enabled as authority_enabled,sa.remark as authority_remark,sa.create_by as authority_create_by,sa.create_time as authority_create_time,sa.update_by as authority_update_by,sa.update_time as authority_update_time
from sys_role sr
left join sys_role_authorities sra on sr.id=sra.role_id
left join sys_authority sa on sra.authority_id=sa.id
where sr.id=#{roleId}
</select>
<mapper namespace="com.zsc.edu.bill.modules.system.mapper.RoleMapper">
</mapper>

View File

@ -48,16 +48,15 @@ abstract public class MockMvcConfigBase {
protected CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
@MockBean
protected CustomAccessDeniedHandler customAccessDeniedHandler;
// @Autowired
// protected MockMvc mockMvc;
// @Autowired
// protected ObjectMapper objectMapper;
@Autowired
protected MockMvc mockMvc;
@Autowired
protected ObjectMapper objectMapper;
@BeforeAll
public static void setup() {
Dept dept = DeptBuilder.aDept().name("Platform").build();
Role role = RoleBuilder.aRole().authorities(new HashSet<>()).build();
// Role role = RoleBuilder.aRole().authorities(new HashSet<>(Arrays.asList(Authority))).build();
Role role = RoleBuilder.aRole().authorities(new HashSet<>(Arrays.asList(Authority.values()))).build();
user = UserBuilder.anUser().username("admin").dept(dept).role(role).build();
userDetails = UserDetailsImpl.from(user);
}

View File

@ -1,7 +1,5 @@
package com.zsc.edu.bill.rest;
//import com.zsc.edu.bill.MockMvcConfigBase;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zsc.edu.bill.MockMvcConfigBase;
import com.zsc.edu.bill.domain.DeptBuilder;
import com.zsc.edu.bill.modules.system.controller.DeptController;
@ -16,7 +14,6 @@ import org.mockito.Spy;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
@ -37,10 +34,6 @@ public class DeptControllerTest extends MockMvcConfigBase {
private static Dept dept2;
private MockMvc mockMvc;
private ObjectMapper objectMapper;
@MockBean
protected DeptMapper deptMapper;

View File

@ -1,6 +1,5 @@
package com.zsc.edu.bill.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zsc.edu.bill.MockMvcConfigBase;
import com.zsc.edu.bill.domain.RoleBuilder;
import com.zsc.edu.bill.modules.system.controller.RoleController;
@ -10,11 +9,9 @@ import com.zsc.edu.bill.modules.system.service.RoleService;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
@ -36,10 +33,6 @@ public class RoleControllerTest extends MockMvcConfigBase {
private static Role Role2;
private MockMvc mockMvc;
private ObjectMapper objectMapper;
@MockBean
private RoleService service;

View File

@ -1,9 +0,0 @@
package com.zsc.edu.bill.service;
import com.zsc.edu.bill.modules.system.controller.DeptController;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
@WebMvcTest(DeptController.class)
public class AuthorityServiceTest {
}

View File

@ -6,7 +6,6 @@ import com.zsc.edu.bill.domain.RoleBuilder;
import com.zsc.edu.bill.modules.system.dto.RoleDto;
import com.zsc.edu.bill.modules.system.entity.Authority;
import com.zsc.edu.bill.modules.system.entity.Role;
import com.zsc.edu.bill.modules.system.repo.AuthorityRepository;
import com.zsc.edu.bill.modules.system.repo.RoleRepository;
import com.zsc.edu.bill.modules.system.service.RoleService;
import org.junit.jupiter.api.AfterEach;
@ -41,8 +40,6 @@ class RoleServiceTest {
private Role Role3;
private Role Role4;
private AuthorityRepository authorityRepository;
@BeforeEach
void setUp() {
role1 = RoleBuilder.aRole().name("超级管理员").build();
@ -72,7 +69,7 @@ class RoleServiceTest {
RoleDto dto = new RoleDto();
dto.setName("东菱经销商5");
dto.setRemark("remark...");
dto.setAuthorities(new HashSet<>(Arrays.asList(authorityRepository.selectOne(null))));
dto.setAuthorities(new HashSet<>(Arrays.asList(Authority.values())));
Role Role = service.create(dto);
assertNotNull(Role.getId());
assertEquals(3, service.list().size());
@ -85,12 +82,9 @@ class RoleServiceTest {
RoleDto dto = new RoleDto();
dto.setName("超级管理员2");
dto.setRemark("remark...");
dto.setAuthorities(authorityRepository.selectAuthoritiesByRoleId(1L));
dto.setAuthorities(Set.of(Authority.ROLE_UPDATE, Authority.DEPT_UPDATE));
assertTrue(service.edit(dto, role2.id));
}
@Test
void roleVo(){
repo.deleteById(role1.id);
}
}

View File

@ -3,7 +3,6 @@ package com.zsc.edu.bill.service;
import com.zsc.edu.bill.modules.system.entity.Authority;
import com.zsc.edu.bill.modules.system.entity.RoleAuthority;
import com.zsc.edu.bill.modules.system.entity.User;
import com.zsc.edu.bill.modules.system.repo.AuthorityRepository;
import com.zsc.edu.bill.modules.system.repo.RoleAuthoritiesRepository;
import com.zsc.edu.bill.modules.system.repo.UserRepository;
import jakarta.annotation.Resource;
@ -25,13 +24,13 @@ public class UserServiceTest {
private RoleAuthoritiesRepository roleAuthoritiesRepository;
@Resource
private UserRepository userRepository;
@Resource
private AuthorityRepository authorityRepository;
@Test
void test() {
User user=userRepository.selectByUsername("admin");
Set<Authority> authorities= authorityRepository.selectAuthoritiesByRoleId(user.getRoleId());
user.role.authorities=authorities;
List<RoleAuthority> authorities= roleAuthoritiesRepository.selectByRoleId(user.getRoleId());
Set<Authority> authorities1=new HashSet<>();
authorities.stream().forEach(authority ->authorities1.add(Authority.valueOf(authority.getAuthority())));
user.role.authorities=authorities1;
System.out.println(user);
}