实现权限校验

This commit is contained in:
tortoise 2024-08-21 21:21:48 +08:00
parent a04c901b04
commit 68ef028a1b
4 changed files with 69 additions and 15 deletions

View File

@ -1,9 +1,16 @@
package top.suyiiyii.sims.common;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import top.suyiiyii.sims.service.RoleService;
import top.suyiiyii.sims.service.UserService;
import top.suyiiyii.sims.utils.JwtUtils;
/**
* @Author tortoise
@ -15,13 +22,23 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupp
*/
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
@Autowired
private RoleService roleService;
//UserService userService;
@Override
protected void addInterceptors(InterceptorRegistry registry) {
// registry.addInterceptor(jwtInterceptor())
// .addPathPatterns("/**")
// .excludePathPatterns("/user/login") // 排除不需要验证的路径
// .excludePathPatterns("/user/register")
// .excludePathPatterns("/v3/api-docs/**");
registry.addInterceptor(jwtInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/user/login") // 排除不需要验证的路径
.excludePathPatterns("/user/register")
.excludePathPatterns("/v3/api-docs/**");
// 注册AdminInterceptor只拦截以admin/开头的路径
registry.addInterceptor(new AdminInterceptor())
.addPathPatterns("/admin/**");
super.addInterceptors(registry);
}
@ -30,5 +47,36 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupp
return new JwtInterceptor();
}
// AdminInterceptor的实现
public class AdminInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String path = request.getRequestURI();
if (path.startsWith("/admin/") && !hasAdminPermission(request)) {
// 如果用户没有管理员权限返回403 Forbidden
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return false;
}
return true;
}
private boolean hasAdminPermission(HttpServletRequest request) {
// 这里应该实现检查用户权限的逻辑
// 例如从sessiontoken或者数据库中获取用户信息并判断权限
// 以下仅为示例
String token = (String) request.getAttribute("token");
//非空
if (token == null) {
return false;
}
try {
Integer userId = Integer.valueOf(JwtUtils.extractUserId(token));
return roleService.isRoleNameAdmin(userId);
} catch (Exception e) {
// 处理令牌解析过程中可能出现的异常
return false;
}
}
}
}

View File

@ -66,7 +66,7 @@ RecordController {
public Result<List<RecordDto>> record(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
HttpServletRequest request) {
String token = request.getHeader("Authorization").replace("Bearer ", "");
String token = (String) request.getAttribute("token");
String userId= JwtUtils.extractUserId(token);
List<RecordDto> recordDtos=new ArrayList<>();
@ -104,6 +104,7 @@ RecordController {
@PostMapping("/admin/record")
public Result<CommonResponse> adminAddRecord(@RequestBody RecordDto recordDto) {
Integer categoryId = categoryService.getIdBySubCategoryName(recordDto.getSubCategoryName());
Record record = modelMapper.map(recordDto, Record.class);
if (categoryId == null) {
Result.error("请选择奖惩类别,以及类型");

View File

@ -55,4 +55,6 @@ public interface RoleMapper {
@Select("SELECT role_name FROM role WHERE role_id=#{roleId}")
List<String> selectRoleNamesByRoleId(Integer roleId);
}

View File

@ -22,15 +22,7 @@ import java.util.List;
public class RoleService {
@Autowired
RoleMapper roleMapper;
public void addRole(String name){
roleMapper.addRole(name);
}
public void deleteRole(String name){
roleMapper.deleteRole(name);
}
public void updateRole(String name,String newName){
roleMapper.updateRole(name,newName);
}
public List<User> findAllUsersWithRoles(){
return roleMapper.selectAllUsersWithRoles();
}
@ -46,4 +38,15 @@ public class RoleService {
}
public boolean isRoleNameAdmin(Integer id) {
List<Role> roles = roleMapper.selectRolesById(id);
for (Role role : roles) {
if (role.getRoleName().equals("admin")) {
return true;
}
}
return false;
}
}