CRM项目后端将对应的操作权限给予用户对象并通过Spring-Security实现权限限定------CRM项目

package com.alatus.service.impl;

import com.alatus.constant.Constants;
import com.alatus.manager.RedisManager;
import com.alatus.manager.UserManager;
import com.alatus.mapper.TUserMapper;
import com.alatus.model.TUser;
import com.alatus.query.BaseQuery;
import com.alatus.query.UserQuery;
import com.alatus.service.UserService;
import com.alatus.util.CacheUtils;
import com.alatus.util.JWTUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private TUserMapper tUserMapper;
    @Resource
    private RedisManager redisManager;
    @Resource
    private UserManager userManager;

//    注入一个密码加密器
    @Resource
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser tUser = tUserMapper.selectByLoginAct(username);
        if(tUser == null){
            throw new UsernameNotFoundException("登陆账号不存在");
        }
//        获取用户ID
        Integer id = tUser.getId();
//        设置用户的角色
        tUser.setRoleList(userManager.loadRoleListByUser(id));
        tUser.setMenuPermissionList(userManager.getMenuPermissionList(id));
        List<String> permissionList = new ArrayList<>();
        userManager.selectButtonPermissionByUserId(id).forEach(tPermission ->  {
//            这里的code就是权限标识符
            permissionList.add(tPermission.getCode());
        });
//        设置用户的权限标识符
        tUser.setPermissionList(permissionList);
        return tUser;
    }

    @Override
    public PageInfo<TUser> getUserByPage(Integer current) {
//        设置PageHelper和分页情况
        PageHelper.startPage(current, Constants.PAGE_SIZE);
//        查询
        ArrayList<TUser> list = tUserMapper.selectUserByPage(BaseQuery.builder().build());
//        封装分页到PageInfo中
        PageInfo<TUser> info = new PageInfo<>(list);
        return info;
    }

    @Override
    public TUser getUserById(Integer id) {
        return tUserMapper.selectDetailByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveUser(UserQuery userQuery) {
        TUser tUser = new TUser();
//        把query对象的数据复制到user对象里面
//        这个工具类的复制要求是两个对象的属性名要相同,属性要相同
        BeanUtils.copyProperties(userQuery,tUser);
        tUser.setLoginPwd(passwordEncoder.encode(userQuery.getLoginPwd()));
//        创建时间
        tUser.setCreateTime(new Date());
//        通过token解析出的用户获取ID作为创建者的ID
        Integer loginId = JWTUtils.parseUserFromJWT(userQuery.getToken()).getId();
        tUser.setCreateBy(loginId);
        return tUserMapper.insertSelective(tUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(UserQuery userQuery) {
        TUser tUser = new TUser();
//        把query对象的数据复制到user对象里面
//        这个工具类的复制要求是两个对象的属性名要相同,属性要相同
        BeanUtils.copyProperties(userQuery,tUser);
        if(StringUtils.hasText(userQuery.getLoginPwd())){
            tUser.setLoginPwd(passwordEncoder.encode(userQuery.getLoginPwd()));
        }
//        编辑时间
        tUser.setEditTime(new Date());
//        通过token解析出的用户获取ID作为编辑者的ID
        Integer loginId = JWTUtils.parseUserFromJWT(userQuery.getToken()).getId();
        tUser.setEditBy(loginId);
        return tUserMapper.updateByPrimaryKeySelective(tUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delUserById(Integer id) {
        return tUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delUsersByIds(List<String> idList) {
//        遍历删除法
//        int result = 0;
//        for (int i = 0; i < idList.size(); i++) {
//            result += tUserMapper.deleteByPrimaryKey(Integer.parseInt(idList.get(i)));
//        }
//        return result;
        return tUserMapper.deleteByIds(idList);
    }

    @Override
    public List<TUser> getOwnerList() {
//        先从redis获取
//        redis没有就走mysql
        return CacheUtils.getCacheData(() -> {
//            从redis查数据
            return (List<TUser>)redisManager.getValue(Constants.OWNER_KEY);
        }
        ,() -> {
//            生产,从mysql查询数据
            return (List<TUser>)tUserMapper.selectByOwner();
        }
        ,(t) -> {
//            消费,把数据放入缓存redis
            redisManager.setValue(Constants.OWNER_KEY,t);
        });
    }
}
package com.alatus.service.impl;

import com.alatus.constant.Constants;
import com.alatus.manager.RedisManager;
import com.alatus.manager.UserManager;
import com.alatus.mapper.TUserMapper;
import com.alatus.model.TUser;
import com.alatus.query.BaseQuery;
import com.alatus.query.UserQuery;
import com.alatus.service.UserService;
import com.alatus.util.CacheUtils;
import com.alatus.util.JWTUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private TUserMapper tUserMapper;
    @Resource
    private RedisManager redisManager;
    @Resource
    private UserManager userManager;

//    注入一个密码加密器
    @Resource
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser tUser = tUserMapper.selectByLoginAct(username);
        if(tUser == null){
            throw new UsernameNotFoundException("登陆账号不存在");
        }
//        获取用户ID
        Integer id = tUser.getId();
//        设置用户的角色
        tUser.setRoleList(userManager.loadRoleListByUser(id));
        tUser.setMenuPermissionList(userManager.getMenuPermissionList(id));
        List<String> permissionList = new ArrayList<>();
        userManager.selectButtonPermissionByUserId(id).forEach(tPermission ->  {
//            这里的code就是权限标识符
            permissionList.add(tPermission.getCode());
        });
//        设置用户的权限标识符
        tUser.setPermissionList(permissionList);
        return tUser;
    }

    @Override
    public PageInfo<TUser> getUserByPage(Integer current) {
//        设置PageHelper和分页情况
        PageHelper.startPage(current, Constants.PAGE_SIZE);
//        查询
        ArrayList<TUser> list = tUserMapper.selectUserByPage(BaseQuery.builder().build());
//        封装分页到PageInfo中
        PageInfo<TUser> info = new PageInfo<>(list);
        return info;
    }

    @Override
    public TUser getUserById(Integer id) {
        return tUserMapper.selectDetailByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveUser(UserQuery userQuery) {
        TUser tUser = new TUser();
//        把query对象的数据复制到user对象里面
//        这个工具类的复制要求是两个对象的属性名要相同,属性要相同
        BeanUtils.copyProperties(userQuery,tUser);
        tUser.setLoginPwd(passwordEncoder.encode(userQuery.getLoginPwd()));
//        创建时间
        tUser.setCreateTime(new Date());
//        通过token解析出的用户获取ID作为创建者的ID
        Integer loginId = JWTUtils.parseUserFromJWT(userQuery.getToken()).getId();
        tUser.setCreateBy(loginId);
        return tUserMapper.insertSelective(tUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(UserQuery userQuery) {
        TUser tUser = new TUser();
//        把query对象的数据复制到user对象里面
//        这个工具类的复制要求是两个对象的属性名要相同,属性要相同
        BeanUtils.copyProperties(userQuery,tUser);
        if(StringUtils.hasText(userQuery.getLoginPwd())){
            tUser.setLoginPwd(passwordEncoder.encode(userQuery.getLoginPwd()));
        }
//        编辑时间
        tUser.setEditTime(new Date());
//        通过token解析出的用户获取ID作为编辑者的ID
        Integer loginId = JWTUtils.parseUserFromJWT(userQuery.getToken()).getId();
        tUser.setEditBy(loginId);
        return tUserMapper.updateByPrimaryKeySelective(tUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delUserById(Integer id) {
        return tUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delUsersByIds(List<String> idList) {
//        遍历删除法
//        int result = 0;
//        for (int i = 0; i < idList.size(); i++) {
//            result += tUserMapper.deleteByPrimaryKey(Integer.parseInt(idList.get(i)));
//        }
//        return result;
        return tUserMapper.deleteByIds(idList);
    }

    @Override
    public List<TUser> getOwnerList() {
//        先从redis获取
//        redis没有就走mysql
        return CacheUtils.getCacheData(() -> {
//            从redis查数据
            return (List<TUser>)redisManager.getValue(Constants.OWNER_KEY);
        }
        ,() -> {
//            生产,从mysql查询数据
            return (List<TUser>)tUserMapper.selectByOwner();
        }
        ,(t) -> {
//            消费,把数据放入缓存redis
            redisManager.setValue(Constants.OWNER_KEY,t);
        });
    }
}
package com.alatus.config;

import com.alatus.config.filter.TokenVerifyFilter;
import com.alatus.config.handler.MyAccessDeniedHandler;
import com.alatus.config.handler.MyAuthenticationFailureHandler;
import com.alatus.config.handler.MyAuthenticationSuccessHandler;
import com.alatus.config.handler.MyLogoutSuccessHandler;
import com.alatus.constant.Constants;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Arrays;

//开启方法级别的权限检查
@EnableMethodSecurity
@Configuration
public class SecurityConfig {
    @Resource
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
    @Resource
    private MyLogoutSuccessHandler myLogoutSuccessHandler;
    @Resource
    private TokenVerifyFilter tokenVerifyFilter;
//    权限不足
    @Resource
    private MyAccessDeniedHandler myAccessDeniedHandler;

//    配置加密器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Resource
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity,CorsConfigurationSource configurationSource) throws Exception{
        return httpSecurity
                .formLogin((formLogin) -> {
                    formLogin.loginProcessingUrl((Constants.LOGIN_URI))
                            .usernameParameter("loginAct")
                            .passwordParameter("loginPwd")
                            .successHandler(myAuthenticationSuccessHandler)
                            .failureHandler(myAuthenticationFailureHandler);
                })
//        SecurityFilterChain改变了默认行为,不再拦截了,需要手动拦截
                .authorizeHttpRequests((authorize) -> {
//                    对任何请求进行拦截,任何请求都需要登录才可以访问
//                    /api/login这个请求放开,其他请求正常拦截
                    authorize.requestMatchers(Constants.LOGIN_URI).permitAll().anyRequest().authenticated();
                })
                .csrf((csrf) -> {
                    //禁用跨站请求伪造
                    csrf.disable();
                })
                //支持跨域请求
                .cors((cors)->{
                    cors.configurationSource(configurationSource);
                })
                .sessionManagement((session) -> {
//                    让session的创建策略为不创建
                    session.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
                })
//                添加我们自定义的filter
                .addFilterBefore(tokenVerifyFilter, LogoutFilter.class)
//                退出登录
                .logout((logout) -> {
//                    退出的地址,这个也不需要我们写controller
                    logout.logoutUrl("/api/logOut").logoutSuccessHandler(myLogoutSuccessHandler);
                })
                //无权限时的处理方法
                .exceptionHandling((exceptionHandling) -> {
                    exceptionHandling.accessDeniedHandler(myAccessDeniedHandler);
                })
                .build();
    }
    @Bean
    public CorsConfigurationSource configurationSource(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));//允许任意来源
        corsConfiguration.setAllowedMethods(Arrays.asList("*"));//允许任意方法请求
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));//允许请求头任意内容
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        任何路径都按这个来
        source.registerCorsConfiguration("/**",corsConfiguration);
        return source;
    }
}
package com.alatus.config;

import com.alatus.config.filter.TokenVerifyFilter;
import com.alatus.config.handler.MyAccessDeniedHandler;
import com.alatus.config.handler.MyAuthenticationFailureHandler;
import com.alatus.config.handler.MyAuthenticationSuccessHandler;
import com.alatus.config.handler.MyLogoutSuccessHandler;
import com.alatus.constant.Constants;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Arrays;

//开启方法级别的权限检查
@EnableMethodSecurity
@Configuration
public class SecurityConfig {
    @Resource
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
    @Resource
    private MyLogoutSuccessHandler myLogoutSuccessHandler;
    @Resource
    private TokenVerifyFilter tokenVerifyFilter;
//    权限不足
    @Resource
    private MyAccessDeniedHandler myAccessDeniedHandler;

//    配置加密器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Resource
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity,CorsConfigurationSource configurationSource) throws Exception{
        return httpSecurity
                .formLogin((formLogin) -> {
                    formLogin.loginProcessingUrl((Constants.LOGIN_URI))
                            .usernameParameter("loginAct")
                            .passwordParameter("loginPwd")
                            .successHandler(myAuthenticationSuccessHandler)
                            .failureHandler(myAuthenticationFailureHandler);
                })
//        SecurityFilterChain改变了默认行为,不再拦截了,需要手动拦截
                .authorizeHttpRequests((authorize) -> {
//                    对任何请求进行拦截,任何请求都需要登录才可以访问
//                    /api/login这个请求放开,其他请求正常拦截
                    authorize.requestMatchers(Constants.LOGIN_URI).permitAll().anyRequest().authenticated();
                })
                .csrf((csrf) -> {
                    //禁用跨站请求伪造
                    csrf.disable();
                })
                //支持跨域请求
                .cors((cors)->{
                    cors.configurationSource(configurationSource);
                })
                .sessionManagement((session) -> {
//                    让session的创建策略为不创建
                    session.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
                })
//                添加我们自定义的filter
                .addFilterBefore(tokenVerifyFilter, LogoutFilter.class)
//                退出登录
                .logout((logout) -> {
//                    退出的地址,这个也不需要我们写controller
                    logout.logoutUrl("/api/logOut").logoutSuccessHandler(myLogoutSuccessHandler);
                })
                //无权限时的处理方法
                .exceptionHandling((exceptionHandling) -> {
                    exceptionHandling.accessDeniedHandler(myAccessDeniedHandler);
                })
                .build();
    }
    @Bean
    public CorsConfigurationSource configurationSource(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));//允许任意来源
        corsConfiguration.setAllowedMethods(Arrays.asList("*"));//允许任意方法请求
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));//允许请求头任意内容
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        任何路径都按这个来
        source.registerCorsConfiguration("/**",corsConfiguration);
        return source;
    }
}
package com.alatus.config.handler;

import com.alatus.result.CodeEnum;
import com.alatus.result.Result;
import com.alatus.util.JSONUtils;
import com.alatus.util.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //执行到这里,说明登录成功,那我们向前端返回json就行了
        //R result = R.FAIL(accessDeniedException.getLocalizedMessage());
        Result result = Result.FAIL(CodeEnum.ACCESS_DENIED);

        //把R对象转成json
        String resultJSON = JSONUtils.toJSON(result);

        //把json写出去,写到浏览器
        ResponseUtils.write(response, resultJSON);
    }
}
package com.alatus.config.handler;

import com.alatus.result.CodeEnum;
import com.alatus.result.Result;
import com.alatus.util.JSONUtils;
import com.alatus.util.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //执行到这里,说明登录成功,那我们向前端返回json就行了
        //R result = R.FAIL(accessDeniedException.getLocalizedMessage());
        Result result = Result.FAIL(CodeEnum.ACCESS_DENIED);

        //把R对象转成json
        String resultJSON = JSONUtils.toJSON(result);

        //把json写出去,写到浏览器
        ResponseUtils.write(response, resultJSON);
    }
}
package com.alatus.result;

import lombok.*;

@Getter
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
public enum CodeEnum {
    OK(200,"成功"),

    FAIL(500,"失败"),

    TOKEN_IS_EMPTY(901,"请求Token参数为空"),

    TOKEN_IS_EXPIRED(902,"Token已过期"),

    TOKEN_IS_ERROR(903,"Token有误"),

    TOKEN_IS_NONE_MATCH(904,"Token信息不合法"),

    USER_LOG_OUT(200,"退出成功"),

    DATA_ACCESS_EXCEPTION(500,"数据库操作失败"),

    ACCESS_DENIED(500, "抱歉,没有权限访问");

//    结果码
    private int code;
//    结果信息
    @NonNull
    private String msg;
}
package com.alatus.result;

import lombok.*;

@Getter
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
public enum CodeEnum {
    OK(200,"成功"),

    FAIL(500,"失败"),

    TOKEN_IS_EMPTY(901,"请求Token参数为空"),

    TOKEN_IS_EXPIRED(902,"Token已过期"),

    TOKEN_IS_ERROR(903,"Token有误"),

    TOKEN_IS_NONE_MATCH(904,"Token信息不合法"),

    USER_LOG_OUT(200,"退出成功"),

    DATA_ACCESS_EXCEPTION(500,"数据库操作失败"),

    ACCESS_DENIED(500, "抱歉,没有权限访问");

//    结果码
    private int code;
//    结果信息
    @NonNull
    private String msg;
}

package com.alatus.web;

import com.alatus.constant.Constants;
import com.alatus.model.TClue;
import com.alatus.query.ClueQuery;
import com.alatus.result.Result;
import com.alatus.service.ClueService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
public class ClueController {
    @Resource
    private ClueService clueService;

    @PreAuthorize(value = "hasAuthority('clue:list')")
    @GetMapping(value = "/api/clues")
    public Result cluePage(@RequestParam(value = Constants.CURRENT,required = false)Integer current){
        if(current == null){
            current = 1;
        }
        PageInfo<TClue> pageInfo = clueService.getClueByPage(current);
        return Result.OK(pageInfo);
    }

    @PreAuthorize(value = "hasAuthority('clue:import')")
    @PostMapping(value = "/api/clue/importExcel")
    public Result importExcel(MultipartFile file, @RequestHeader(value = Constants.TOKEN_NAME)String token) throws IOException {
//        接收到的文件名字需要和前端提交的名字相同,否则无法接收
        clueService.importExcel(file.getInputStream(),token);
        return Result.OK();
    }

    @PreAuthorize(value = "hasAuthority('clue:delete')")
    @DeleteMapping(value = "/api/clue/delete/{id}")
    public Result clueDel(@PathVariable(value = Constants.ID)Integer id){
        Integer result = clueService.deleteClue(id);
        return result >= 1 ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('clue:delete')")
    @DeleteMapping(value = "/api/clue/batchDel")
    public Result batchDelClue(@RequestParam(value = Constants.IDS)String ids,@RequestHeader(value = Constants.TOKEN_NAME)String token){
        List<String> idsList = Arrays.asList(ids.split(","));
        int result = clueService.delClueByIds(idsList);
        return result >= idsList.size() ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('clue:view')")
    @GetMapping(value = "/api/clue/phone/{phone}")
    public Result checkPhone(@PathVariable(value = Constants.PHONE)String phone){
        Boolean check = clueService.checkPhone(phone);
        return check ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('clue:add')")
    @PostMapping(value = "/api/clue/add")
    public Result addClue(@RequestHeader(value = Constants.TOKEN_NAME)String token, ClueQuery clueQuery){
        clueQuery.setToken(token);
        int save = clueService.saveClue(clueQuery);
        return save >= 1 ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('clue:view')")
    @GetMapping(value = "/api/clue/{id}")
    public Result getClue(@PathVariable(value = Constants.ID)Integer id){
        TClue tClue = clueService.getClueById(id);
        return Result.OK(tClue);
    }

    @PreAuthorize(value = "hasAuthority('clue:edit')")
    @PutMapping(value = "/api/clue/edit")
    public Result editClue(@RequestHeader(value = Constants.TOKEN_NAME)String token, ClueQuery clueQuery){
        clueQuery.setToken(token);
        int update = clueService.editClue(clueQuery);
        return update >= 1 ? Result.OK() : Result.FAIL();
    }
}
package com.alatus.web;

import com.alatus.constant.Constants;
import com.alatus.model.TClue;
import com.alatus.query.ClueQuery;
import com.alatus.result.Result;
import com.alatus.service.ClueService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
public class ClueController {
    @Resource
    private ClueService clueService;

    @PreAuthorize(value = "hasAuthority('clue:list')")
    @GetMapping(value = "/api/clues")
    public Result cluePage(@RequestParam(value = Constants.CURRENT,required = false)Integer current){
        if(current == null){
            current = 1;
        }
        PageInfo<TClue> pageInfo = clueService.getClueByPage(current);
        return Result.OK(pageInfo);
    }

    @PreAuthorize(value = "hasAuthority('clue:import')")
    @PostMapping(value = "/api/clue/importExcel")
    public Result importExcel(MultipartFile file, @RequestHeader(value = Constants.TOKEN_NAME)String token) throws IOException {
//        接收到的文件名字需要和前端提交的名字相同,否则无法接收
        clueService.importExcel(file.getInputStream(),token);
        return Result.OK();
    }

    @PreAuthorize(value = "hasAuthority('clue:delete')")
    @DeleteMapping(value = "/api/clue/delete/{id}")
    public Result clueDel(@PathVariable(value = Constants.ID)Integer id){
        Integer result = clueService.deleteClue(id);
        return result >= 1 ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('clue:delete')")
    @DeleteMapping(value = "/api/clue/batchDel")
    public Result batchDelClue(@RequestParam(value = Constants.IDS)String ids,@RequestHeader(value = Constants.TOKEN_NAME)String token){
        List<String> idsList = Arrays.asList(ids.split(","));
        int result = clueService.delClueByIds(idsList);
        return result >= idsList.size() ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('clue:view')")
    @GetMapping(value = "/api/clue/phone/{phone}")
    public Result checkPhone(@PathVariable(value = Constants.PHONE)String phone){
        Boolean check = clueService.checkPhone(phone);
        return check ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('clue:add')")
    @PostMapping(value = "/api/clue/add")
    public Result addClue(@RequestHeader(value = Constants.TOKEN_NAME)String token, ClueQuery clueQuery){
        clueQuery.setToken(token);
        int save = clueService.saveClue(clueQuery);
        return save >= 1 ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('clue:view')")
    @GetMapping(value = "/api/clue/{id}")
    public Result getClue(@PathVariable(value = Constants.ID)Integer id){
        TClue tClue = clueService.getClueById(id);
        return Result.OK(tClue);
    }

    @PreAuthorize(value = "hasAuthority('clue:edit')")
    @PutMapping(value = "/api/clue/edit")
    public Result editClue(@RequestHeader(value = Constants.TOKEN_NAME)String token, ClueQuery clueQuery){
        clueQuery.setToken(token);
        int update = clueService.editClue(clueQuery);
        return update >= 1 ? Result.OK() : Result.FAIL();
    }
}
package com.alatus.web;

import com.alatus.constant.Constants;
import com.alatus.model.TUser;
import com.alatus.query.UserQuery;
import com.alatus.result.Result;
import com.alatus.service.UserService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;

@RestController
public class UserController {
    @Resource
    private UserService userService;

//    获取登录信息
    @GetMapping(value = "/api/login/info")
    public Result loginInfo(Authentication authentication){
        TUser tUser = (TUser) authentication.getPrincipal();
        return Result.OK(tUser);
    }


    //免登录验证
    //因为发送的请求过来首先会过filter那一关,能到这说明token验证都通过了,我们直接返回200即可
    @GetMapping(value = "/api/login/free")
    public Result freeLogin(){
        return Result.OK();
    }
//    查询用户列表,用户分页查询

    @PreAuthorize(value = "hasAuthority('user:list')")
    @GetMapping(value = "/api/users")
//    传递参数current,可传可不传,
    public Result userPage(@RequestParam(value = Constants.CURRENT,required = false) Integer current){
        if(current == null){
            current = 1;
        }
//        返回结果为PageInfo
        PageInfo<TUser> userByPage = userService.getUserByPage(current);
        return Result.OK(userByPage);
    }

    @PreAuthorize(value = "hasAuthority('user:view')")
    @GetMapping(value = "/api/user/{id}")
    public Result userDetail(@PathVariable(value = Constants.ID)Integer id){
        TUser tUser = userService.getUserById(id);
        return Result.OK(tUser);
    }


//    添加用户
    @PreAuthorize(value = "hasAuthority('user:add')")
    @PostMapping(value = "/api/user/add")
    public Result addUser(UserQuery userQuery, @RequestHeader(value = Constants.TOKEN_NAME)String token){
        userQuery.setToken(token);
        int result = userService.saveUser(userQuery);
        return result >= 1 ? Result.OK() : Result.FAIL();
    }


//    编辑用户
    @PreAuthorize(value = "hasAuthority('user:edit')")
    @PutMapping(value = "/api/user/edit")
    public Result editUser(UserQuery userQuery, @RequestHeader(value = Constants.TOKEN_NAME)String token){
        userQuery.setToken(token);
        int result = userService.updateUser(userQuery);
        return result >= 1 ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('user:delete')")
    @DeleteMapping(value = "/api/user/del/{id}")
    public Result delUser(@PathVariable(value = Constants.ID) Integer id, @RequestHeader(value = Constants.TOKEN_NAME)String token){
        int result = userService.delUserById(id);
        return result >= 1 ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('user:delete')")
    @DeleteMapping(value = "/api/user/batchDel")
    public Result batchDelUsers(@RequestParam(value = Constants.IDS) String ids, @RequestHeader(value = Constants.TOKEN_NAME)String token){
//        将我们的字符串拆分并放到list中作为元素
        List<String> idList = Arrays.asList(ids.split(","));
        int result = userService.delUsersByIds(idList);
        return result >= idList.size() ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('user:view')")
    @GetMapping(value = "/api/user/activityOwner")
    public Result loadActivityOwner(){
        return Result.OK(userService.getOwnerList());
    }
}
package com.alatus.web;

import com.alatus.constant.Constants;
import com.alatus.model.TUser;
import com.alatus.query.UserQuery;
import com.alatus.result.Result;
import com.alatus.service.UserService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;

@RestController
public class UserController {
    @Resource
    private UserService userService;

//    获取登录信息
    @GetMapping(value = "/api/login/info")
    public Result loginInfo(Authentication authentication){
        TUser tUser = (TUser) authentication.getPrincipal();
        return Result.OK(tUser);
    }


    //免登录验证
    //因为发送的请求过来首先会过filter那一关,能到这说明token验证都通过了,我们直接返回200即可
    @GetMapping(value = "/api/login/free")
    public Result freeLogin(){
        return Result.OK();
    }
//    查询用户列表,用户分页查询

    @PreAuthorize(value = "hasAuthority('user:list')")
    @GetMapping(value = "/api/users")
//    传递参数current,可传可不传,
    public Result userPage(@RequestParam(value = Constants.CURRENT,required = false) Integer current){
        if(current == null){
            current = 1;
        }
//        返回结果为PageInfo
        PageInfo<TUser> userByPage = userService.getUserByPage(current);
        return Result.OK(userByPage);
    }

    @PreAuthorize(value = "hasAuthority('user:view')")
    @GetMapping(value = "/api/user/{id}")
    public Result userDetail(@PathVariable(value = Constants.ID)Integer id){
        TUser tUser = userService.getUserById(id);
        return Result.OK(tUser);
    }


//    添加用户
    @PreAuthorize(value = "hasAuthority('user:add')")
    @PostMapping(value = "/api/user/add")
    public Result addUser(UserQuery userQuery, @RequestHeader(value = Constants.TOKEN_NAME)String token){
        userQuery.setToken(token);
        int result = userService.saveUser(userQuery);
        return result >= 1 ? Result.OK() : Result.FAIL();
    }


//    编辑用户
    @PreAuthorize(value = "hasAuthority('user:edit')")
    @PutMapping(value = "/api/user/edit")
    public Result editUser(UserQuery userQuery, @RequestHeader(value = Constants.TOKEN_NAME)String token){
        userQuery.setToken(token);
        int result = userService.updateUser(userQuery);
        return result >= 1 ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('user:delete')")
    @DeleteMapping(value = "/api/user/del/{id}")
    public Result delUser(@PathVariable(value = Constants.ID) Integer id, @RequestHeader(value = Constants.TOKEN_NAME)String token){
        int result = userService.delUserById(id);
        return result >= 1 ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('user:delete')")
    @DeleteMapping(value = "/api/user/batchDel")
    public Result batchDelUsers(@RequestParam(value = Constants.IDS) String ids, @RequestHeader(value = Constants.TOKEN_NAME)String token){
//        将我们的字符串拆分并放到list中作为元素
        List<String> idList = Arrays.asList(ids.split(","));
        int result = userService.delUsersByIds(idList);
        return result >= idList.size() ? Result.OK() : Result.FAIL();
    }

    @PreAuthorize(value = "hasAuthority('user:view')")
    @GetMapping(value = "/api/user/activityOwner")
    public Result loadActivityOwner(){
        return Result.OK(userService.getOwnerList());
    }
}
package com.alatus.manager;

import com.alatus.mapper.TPermissionMapper;
import com.alatus.mapper.TRoleMapper;
import com.alatus.model.TPermission;
import com.alatus.model.TRole;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserManager {
    //    注入角色的Mapper
    @Resource
    private TRoleMapper tRoleMapper;
    @Resource
    private TPermissionMapper tPermissionMapper;

    public List<String> loadRoleListByUser(Integer id){
//        查询一下当前登录的角色
        List<TRole> tRoleList = tRoleMapper.selectByUserId(id);
        List<String> roleList = new ArrayList<>();
        tRoleList.forEach(tRole -> {
            roleList.add(tRole.getRole());
        });
        return roleList;
    }
    public List<TPermission> getMenuPermissionList(Integer id){
        List<TPermission> menuPermissionList = tPermissionMapper.selectMenuPermissionByUserId(id);
        return menuPermissionList;
    }

    public List<TPermission> selectButtonPermissionByUserId(Integer id){
        List<TPermission> buttonPermissionByUserId = tPermissionMapper.selectButtonPermissionByUserId(id);
        return buttonPermissionByUserId;
    }
}
package com.alatus.manager;

import com.alatus.mapper.TPermissionMapper;
import com.alatus.mapper.TRoleMapper;
import com.alatus.model.TPermission;
import com.alatus.model.TRole;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserManager {
    //    注入角色的Mapper
    @Resource
    private TRoleMapper tRoleMapper;
    @Resource
    private TPermissionMapper tPermissionMapper;

    public List<String> loadRoleListByUser(Integer id){
//        查询一下当前登录的角色
        List<TRole> tRoleList = tRoleMapper.selectByUserId(id);
        List<String> roleList = new ArrayList<>();
        tRoleList.forEach(tRole -> {
            roleList.add(tRole.getRole());
        });
        return roleList;
    }
    public List<TPermission> getMenuPermissionList(Integer id){
        List<TPermission> menuPermissionList = tPermissionMapper.selectMenuPermissionByUserId(id);
        return menuPermissionList;
    }

    public List<TPermission> selectButtonPermissionByUserId(Integer id){
        List<TPermission> buttonPermissionByUserId = tPermissionMapper.selectButtonPermissionByUserId(id);
        return buttonPermissionByUserId;
    }
}
package com.alatus.mapper;

import com.alatus.model.TPermission;

import java.util.List;

public interface TPermissionMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(TPermission record);

    int insertSelective(TPermission record);

    TPermission selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(TPermission record);

    int updateByPrimaryKey(TPermission record);

    List<TPermission> selectMenuPermissionByUserId(Integer id);

    List<TPermission> selectButtonPermissionByUserId(Integer id);
}
package com.alatus.mapper;

import com.alatus.model.TPermission;

import java.util.List;

public interface TPermissionMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(TPermission record);

    int insertSelective(TPermission record);

    TPermission selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(TPermission record);

    int updateByPrimaryKey(TPermission record);

    List<TPermission> selectMenuPermissionByUserId(Integer id);

    List<TPermission> selectButtonPermissionByUserId(Integer id);
}
<?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.alatus.mapper.TPermissionMapper">
  <resultMap id="BaseResultMap" type="com.alatus.model.TPermission">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="code" jdbcType="VARCHAR" property="code" />
    <result column="url" jdbcType="VARCHAR" property="url" />
    <result column="type" jdbcType="VARCHAR" property="type" />
    <result column="parent_id" jdbcType="INTEGER" property="parentId" />
    <result column="order_no" jdbcType="INTEGER" property="orderNo" />
    <result column="icon" jdbcType="VARCHAR" property="icon" />
  </resultMap>
  <resultMap id="PermissionRoleMap" type="com.alatus.model.TPermission">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="code" jdbcType="VARCHAR" property="code" />
    <result column="url" jdbcType="VARCHAR" property="url" />
    <result column="type" jdbcType="VARCHAR" property="type" />
    <result column="parent_id" jdbcType="INTEGER" property="parentId" />
    <result column="order_no" jdbcType="INTEGER" property="orderNo" />
    <result column="icon" jdbcType="VARCHAR" property="icon" />
<!--    一对多-->
    <collection property="subPermissionList" ofType="com.alatus.model.TPermission">
      <id column="cid" jdbcType="INTEGER" property="id" />
      <result column="cname" jdbcType="VARCHAR" property="name" />
      <result column="curl" jdbcType="VARCHAR" property="url" />
      <result column="cicon" jdbcType="VARCHAR" property="icon" />
    </collection>
  </resultMap>
  
  <sql id="Base_Column_List">
    id, `name`, code, url, `type`, parent_id, order_no, icon
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from t_permission
    where id = #{id,jdbcType=INTEGER}
  </select>


  <select id="selectMenuPermissionByUserId" parameterType="java.lang.Integer" resultMap="PermissionRoleMap">
    SELECT
      tp.*,
      childTp.`id` cid,childTp.`name` cname,childTp.`url` curl,childTp.`icon` cicon
    FROM
      t_permission tp
        LEFT JOIN t_permission childTp
                  ON tp.`id` = childTp.`parent_id`
        LEFT JOIN t_role_permission trp
                  ON tp.`id` = trp.`permission_id`
        LEFT JOIN t_role tr
                  ON tr.`id` = trp.`role_id`
        LEFT JOIN t_user_role tur
                  ON tur.`role_id` = tr.`id`
    WHERE
      tp.type = 'menu' and childTp.`type` = 'menu'
      and tur.`user_id` = #{id,jdbcType=INTEGER}
  </select>


  <select id="selectButtonPermissionByUserId" parameterType="java.lang.Integer" resultMap="PermissionRoleMap">
    SELECT
      tp.*
    FROM
      t_permission tp
        LEFT JOIN t_role_permission trp
                  ON tp.`id` = trp.`permission_id`
        LEFT JOIN t_role tr
                  ON tr.`id` = trp.`role_id`
        LEFT JOIN t_user_role tur
                  ON tur.`role_id` = tr.`id`
    WHERE
      tp.type = 'button' and
	  tur.`user_id` = #{id,jdbcType=INTEGER}
  </select>


    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from t_permission
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.alatus.model.TPermission" useGeneratedKeys="true">
    insert into t_permission (`name`, code, url, 
      `type`, parent_id, order_no, 
      icon)
    values (#{name,jdbcType=VARCHAR}, #{code,jdbcType=VARCHAR}, #{url,jdbcType=VARCHAR}, 
      #{type,jdbcType=VARCHAR}, #{parentId,jdbcType=INTEGER}, #{orderNo,jdbcType=INTEGER}, 
      #{icon,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.alatus.model.TPermission" useGeneratedKeys="true">
    insert into t_permission
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="name != null">
        `name`,
      </if>
      <if test="code != null">
        code,
      </if>
      <if test="url != null">
        url,
      </if>
      <if test="type != null">
        `type`,
      </if>
      <if test="parentId != null">
        parent_id,
      </if>
      <if test="orderNo != null">
        order_no,
      </if>
      <if test="icon != null">
        icon,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="code != null">
        #{code,jdbcType=VARCHAR},
      </if>
      <if test="url != null">
        #{url,jdbcType=VARCHAR},
      </if>
      <if test="type != null">
        #{type,jdbcType=VARCHAR},
      </if>
      <if test="parentId != null">
        #{parentId,jdbcType=INTEGER},
      </if>
      <if test="orderNo != null">
        #{orderNo,jdbcType=INTEGER},
      </if>
      <if test="icon != null">
        #{icon,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.alatus.model.TPermission">
    update t_permission
    <set>
      <if test="name != null">
        `name` = #{name,jdbcType=VARCHAR},
      </if>
      <if test="code != null">
        code = #{code,jdbcType=VARCHAR},
      </if>
      <if test="url != null">
        url = #{url,jdbcType=VARCHAR},
      </if>
      <if test="type != null">
        `type` = #{type,jdbcType=VARCHAR},
      </if>
      <if test="parentId != null">
        parent_id = #{parentId,jdbcType=INTEGER},
      </if>
      <if test="orderNo != null">
        order_no = #{orderNo,jdbcType=INTEGER},
      </if>
      <if test="icon != null">
        icon = #{icon,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.alatus.model.TPermission">
    update t_permission
    set `name` = #{name,jdbcType=VARCHAR},
      code = #{code,jdbcType=VARCHAR},
      url = #{url,jdbcType=VARCHAR},
      `type` = #{type,jdbcType=VARCHAR},
      parent_id = #{parentId,jdbcType=INTEGER},
      order_no = #{orderNo,jdbcType=INTEGER},
      icon = #{icon,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>
<?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.alatus.mapper.TPermissionMapper">
  <resultMap id="BaseResultMap" type="com.alatus.model.TPermission">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="code" jdbcType="VARCHAR" property="code" />
    <result column="url" jdbcType="VARCHAR" property="url" />
    <result column="type" jdbcType="VARCHAR" property="type" />
    <result column="parent_id" jdbcType="INTEGER" property="parentId" />
    <result column="order_no" jdbcType="INTEGER" property="orderNo" />
    <result column="icon" jdbcType="VARCHAR" property="icon" />
  </resultMap>
  <resultMap id="PermissionRoleMap" type="com.alatus.model.TPermission">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="code" jdbcType="VARCHAR" property="code" />
    <result column="url" jdbcType="VARCHAR" property="url" />
    <result column="type" jdbcType="VARCHAR" property="type" />
    <result column="parent_id" jdbcType="INTEGER" property="parentId" />
    <result column="order_no" jdbcType="INTEGER" property="orderNo" />
    <result column="icon" jdbcType="VARCHAR" property="icon" />
<!--    一对多-->
    <collection property="subPermissionList" ofType="com.alatus.model.TPermission">
      <id column="cid" jdbcType="INTEGER" property="id" />
      <result column="cname" jdbcType="VARCHAR" property="name" />
      <result column="curl" jdbcType="VARCHAR" property="url" />
      <result column="cicon" jdbcType="VARCHAR" property="icon" />
    </collection>
  </resultMap>
  
  <sql id="Base_Column_List">
    id, `name`, code, url, `type`, parent_id, order_no, icon
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from t_permission
    where id = #{id,jdbcType=INTEGER}
  </select>


  <select id="selectMenuPermissionByUserId" parameterType="java.lang.Integer" resultMap="PermissionRoleMap">
    SELECT
      tp.*,
      childTp.`id` cid,childTp.`name` cname,childTp.`url` curl,childTp.`icon` cicon
    FROM
      t_permission tp
        LEFT JOIN t_permission childTp
                  ON tp.`id` = childTp.`parent_id`
        LEFT JOIN t_role_permission trp
                  ON tp.`id` = trp.`permission_id`
        LEFT JOIN t_role tr
                  ON tr.`id` = trp.`role_id`
        LEFT JOIN t_user_role tur
                  ON tur.`role_id` = tr.`id`
    WHERE
      tp.type = 'menu' and childTp.`type` = 'menu'
      and tur.`user_id` = #{id,jdbcType=INTEGER}
  </select>


  <select id="selectButtonPermissionByUserId" parameterType="java.lang.Integer" resultMap="PermissionRoleMap">
    SELECT
      tp.*
    FROM
      t_permission tp
        LEFT JOIN t_role_permission trp
                  ON tp.`id` = trp.`permission_id`
        LEFT JOIN t_role tr
                  ON tr.`id` = trp.`role_id`
        LEFT JOIN t_user_role tur
                  ON tur.`role_id` = tr.`id`
    WHERE
      tp.type = 'button' and
      tur.`user_id` = #{id,jdbcType=INTEGER}
  </select>


    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from t_permission
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.alatus.model.TPermission" useGeneratedKeys="true">
    insert into t_permission (`name`, code, url, 
      `type`, parent_id, order_no, 
      icon)
    values (#{name,jdbcType=VARCHAR}, #{code,jdbcType=VARCHAR}, #{url,jdbcType=VARCHAR}, 
      #{type,jdbcType=VARCHAR}, #{parentId,jdbcType=INTEGER}, #{orderNo,jdbcType=INTEGER}, 
      #{icon,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.alatus.model.TPermission" useGeneratedKeys="true">
    insert into t_permission
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="name != null">
        `name`,
      </if>
      <if test="code != null">
        code,
      </if>
      <if test="url != null">
        url,
      </if>
      <if test="type != null">
        `type`,
      </if>
      <if test="parentId != null">
        parent_id,
      </if>
      <if test="orderNo != null">
        order_no,
      </if>
      <if test="icon != null">
        icon,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="code != null">
        #{code,jdbcType=VARCHAR},
      </if>
      <if test="url != null">
        #{url,jdbcType=VARCHAR},
      </if>
      <if test="type != null">
        #{type,jdbcType=VARCHAR},
      </if>
      <if test="parentId != null">
        #{parentId,jdbcType=INTEGER},
      </if>
      <if test="orderNo != null">
        #{orderNo,jdbcType=INTEGER},
      </if>
      <if test="icon != null">
        #{icon,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.alatus.model.TPermission">
    update t_permission
    <set>
      <if test="name != null">
        `name` = #{name,jdbcType=VARCHAR},
      </if>
      <if test="code != null">
        code = #{code,jdbcType=VARCHAR},
      </if>
      <if test="url != null">
        url = #{url,jdbcType=VARCHAR},
      </if>
      <if test="type != null">
        `type` = #{type,jdbcType=VARCHAR},
      </if>
      <if test="parentId != null">
        parent_id = #{parentId,jdbcType=INTEGER},
      </if>
      <if test="orderNo != null">
        order_no = #{orderNo,jdbcType=INTEGER},
      </if>
      <if test="icon != null">
        icon = #{icon,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.alatus.model.TPermission">
    update t_permission
    set `name` = #{name,jdbcType=VARCHAR},
      code = #{code,jdbcType=VARCHAR},
      url = #{url,jdbcType=VARCHAR},
      `type` = #{type,jdbcType=VARCHAR},
      parent_id = #{parentId,jdbcType=INTEGER},
      order_no = #{orderNo,jdbcType=INTEGER},
      icon = #{icon,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值