自定义注解生成权限到数据库工具优化

This commit is contained in:
79493 2022-10-11 15:21:09 +08:00
parent 4323c9394f
commit 23d467e4e9
14 changed files with 306 additions and 50 deletions

View File

@ -0,0 +1,27 @@
package com.rzyc.enums;
/**
* 企业表
* 启用 禁用 状态
* @author Xuwanxin
* @date 2022/10/10
*/
public enum SysEnterpriseState {
USE("启用"),
DISABLE("禁用");
private String state;
SysEnterpriseState(String state) {
this.state = state;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}

View File

@ -346,4 +346,12 @@ public interface SysEnterpriseMapper {
/*用户企业列表*/ /*用户企业列表*/
List<SysEnterprise> userEntList(@Param("condition") String condition, List<SysEnterprise> userEntList(@Param("condition") String condition,
@Param("areaCode") String areaCode); @Param("areaCode") String areaCode);
/**
* 通过企业用户名查询企业
* @param entUserName 企业用户名
* @return SysEnterprise 企业表
* */
SysEnterprise findEnterpriseByName(@Param("entUserName")String entUserName);
} }

View File

@ -2837,5 +2837,9 @@
ORDER BY dangerNum DESC,se.SysEnterpriseId desc ORDER BY dangerNum DESC,se.SysEnterpriseId desc
</select> </select>
<select id="findEnterpriseByName" resultMap="BaseResultMap">
select sysent.EntName,sysent.state from ent_user eu left join sysenterprise sysent on eu.enterprise_id = sysent.SysEnterpriseId where eu.name = #{entUserName}
</select>
</mapper> </mapper>

View File

@ -3,11 +3,18 @@ package com.rzyc.config;
import com.common.utils.DateUtils; import com.common.utils.DateUtils;
import com.common.utils.RandomNumber; import com.common.utils.RandomNumber;
import com.rzyc.controller.PersonalController; import com.rzyc.controller.PersonalController;
import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.File;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.sql.*; import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** /**
* 获取方法中的注解参数插入数据库 * 获取方法中的注解参数插入数据库
@ -19,10 +26,73 @@ import java.sql.*;
public class EntMethodSignature { public class EntMethodSignature {
public static void main(String[] args) { public static void main(String[] args) throws ClassNotFoundException {
String [] packageName = {"inventory-ent/src/main/java/com/rzyc/controller"};
List<Class<?>> classes = new ArrayList<>();
HashMap<String,String> classNames = scanForPackageName(packageName);
for (Map.Entry<String, String> next: classNames.entrySet()) {
try {
classes.add(Class.forName(next.getValue()));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
for (Class<?> c:classes) {
//反射获取所有方法 //反射获取所有方法
Method[] methods = PersonalController.class.getMethods(); Method[] methods = c.getMethods();
insertAnnotation(methods); RequestMapping requestMapping = c.getAnnotation(RequestMapping.class);
if (null != requestMapping && null != requestMapping.value()[0]) {
String controllerName = requestMapping.value()[0];
insertAnnotation(controllerName, methods);
}
}
}
public static HashMap<String,String> scanForPackageName(String [] path){
HashMap<String,String> classNames = new HashMap<>();
String fileName = null;
for (String s:path) {
//根据传入文件夹路径创建File对象
File dir = new File(s);
//检查是否为文件夹
if (dir.isDirectory()){
//遍历文件夹内的文件
for (File f : dir.listFiles()){
if (f.isDirectory()){
for (File f2 : f.listFiles()){
//获取文件名,并删除后缀
fileName = f2.getName();
try {
fileName = fileName.substring(0,fileName.lastIndexOf("."));
}catch (Exception e){
System.err.println(fileName);
}
//添加到结果中
String filePath = f2.getPath().substring(f2.getPath().indexOf("java")+5,f2.getPath().length()).replace("\\",".").replace(".java","");
classNames.put(fileName,filePath);
continue;
}
}else {
//获取文件名,并删除后缀
fileName = f.getName();
try {
fileName = fileName.substring(0,fileName.lastIndexOf("."));
}catch (Exception e){
System.err.println(fileName);
}
//添加到结果中
String filePath = f.getPath().substring(f.getPath().indexOf("java")+5,f.getPath().length()).replace("\\",".").replace(".java","");
classNames.put(fileName,filePath);
continue;
}
}
}
}
return classNames;
} }
@ -41,7 +111,7 @@ public class EntMethodSignature {
return ds; return ds;
} }
private static void insertAnnotation(Method[] methods) { private static void insertAnnotation(String controllerName,Method[] methods) {
try { try {
//创建connection //创建connection
@ -60,17 +130,16 @@ public class EntMethodSignature {
for (String name : annotation.authorizations()) { for (String name : annotation.authorizations()) {
String str = name.substring(name.indexOf(":")+1,name.length());
ResultSet rs = statement.executeQuery("select auth_key from authority_key where auth_key ='"+str+"'"); ResultSet rs = statement.executeQuery("select auth_key from authority_key where auth_key ='"+name+"'");
//取数据 //取数据
if (rs.next()) { if (rs.next()) {
} else { } else {
String category = name.substring(0,name.indexOf(":"));
preparedStatement.setString(1, RandomNumber.getUUid()); preparedStatement.setString(1, RandomNumber.getUUid());
preparedStatement.setString(2,null); preparedStatement.setString(2,null);
preparedStatement.setString(3,str); preparedStatement.setString(3,name);
preparedStatement.setString(4,category); preparedStatement.setString(4,controllerName);
preparedStatement.setString(5, DateUtils.getNowDateTimeStr()); preparedStatement.setString(5, DateUtils.getNowDateTimeStr());
preparedStatement.setString(6,DateUtils.getNowDateTimeStr()); preparedStatement.setString(6,DateUtils.getNowDateTimeStr());
preparedStatement.setString(7,annotation.name()); preparedStatement.setString(7,annotation.name());

View File

@ -64,7 +64,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
http http
.authorizeRequests() .authorizeRequests()
// 对于登录接口 允许匿名访问 // 对于登录接口 允许匿名访问
.antMatchers("/personal/login","/personal/entlogin").anonymous() .antMatchers("/personal/login","/personal/entlogin","/common/generateCode").anonymous()
//放行swagger //放行swagger
.antMatchers("/swagger-ui.html","/swagger-resources/**","/webjars/**","/v2/**","/api/**").permitAll() .antMatchers("/swagger-ui.html","/swagger-resources/**","/webjars/**","/v2/**","/api/**").permitAll()
// 除上面外的所有请求全部需要鉴权认证,配置退出路径 // 除上面外的所有请求全部需要鉴权认证,配置退出路径

View File

@ -17,6 +17,7 @@ public class UserDetailsAndId extends User {
private String id; private String id;
public String getId() { public String getId() {
return id; return id;
} }
@ -25,6 +26,8 @@ public class UserDetailsAndId extends User {
this.id = id; this.id = id;
} }
public UserDetailsAndId(String username, String password, Collection<? extends GrantedAuthority> authorities, String id) { public UserDetailsAndId(String username, String password, Collection<? extends GrantedAuthority> authorities, String id) {
super(username, password, authorities); super(username, password, authorities);
setId(id); setId(id);

View File

@ -0,0 +1,51 @@
package com.rzyc.controller;
import com.common.utils.verification.Verification;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
/**
* @author Xuwanxin
* @date 2022-10-10
*/
@Api(tags = "企业端公共接口")
@CrossOrigin("*")
@RequestMapping("common")
@Controller
@Validated
public class CommonController extends BaseController{
/**
* 验证码
* @param request
* @param response
* @throws Exception
*/
@ApiOperation(value = "验证码", notes = "验证码")
@GetMapping("/generateCode")
@ResponseBody
public void generateCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
BufferedImage image = Verification.getVerify(constantsConfigure.getGenerateCodeKey(),request);
OutputStream out = response.getOutputStream();
ImageIO.write(image, "JPEG", out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -76,7 +76,6 @@ public class PcCompanyController extends BaseController{
}) })
@PostMapping("/companyDetail") @PostMapping("/companyDetail")
@ResponseBody @ResponseBody
@PreAuthorize("hasRole('ADMIN')")
public SingleResult<String> companyDetail(String SysEnterpriseId)throws Exception { public SingleResult<String> companyDetail(String SysEnterpriseId)throws Exception {
SingleResult singleResult = new SingleResult(); SingleResult singleResult = new SingleResult();
List<SysEnterprise> sysEnterprises = sysEnterpriseMapper.companyDetail(SysEnterpriseId); List<SysEnterprise> sysEnterprises = sysEnterpriseMapper.companyDetail(SysEnterpriseId);

View File

@ -7,9 +7,8 @@ import com.common.utils.StringUtils;
import com.common.utils.encryption.PasswdFactory; import com.common.utils.encryption.PasswdFactory;
import com.common.utils.jwt.JwtUtil; import com.common.utils.jwt.JwtUtil;
import com.common.utils.model.SingleResult; import com.common.utils.model.SingleResult;
import com.rzyc.advice.PageOperation;
import com.rzyc.bean.user.dto.LoginDto; import com.rzyc.bean.user.dto.LoginDto;
import com.rzyc.model.EntUserCredential; import com.rzyc.config.MethodAnnotation;
import com.rzyc.model.dto.EntUserCredentialUpdateDto; import com.rzyc.model.dto.EntUserCredentialUpdateDto;
import com.rzyc.model.ent.EntUser; import com.rzyc.model.ent.EntUser;
import com.rzyc.service.PcBusinessService; import com.rzyc.service.PcBusinessService;
@ -17,7 +16,6 @@ import com.rzyc.service.UserLoginService;
import com.rzyc.bean.user.dto.WeChartLoginDto; import com.rzyc.bean.user.dto.WeChartLoginDto;
import com.rzyc.model.ent.SysEnterprise; import com.rzyc.model.ent.SysEnterprise;
import com.rzyc.model.user.SysUser; import com.rzyc.model.user.SysUser;
import com.rzyc.config.MethodAnnotation;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParams;
@ -159,8 +157,8 @@ public class PersonalController extends BaseController{
@ApiImplicitParam(name = "postId", value = "企业用户岗位id",required = false, dataType = "string"), @ApiImplicitParam(name = "postId", value = "企业用户岗位id",required = false, dataType = "string"),
}) })
@GetMapping(value = "/entUserTree") @GetMapping(value = "/entUserTree")
@PreAuthorize("hasAnyAuthority('PERSONAL:ENTUSERTREE','PERSONAL:ENTUSERTREE:UPDATE')") @PreAuthorize("hasAnyAuthority('entUserTree','entUserTree:update')")
@MethodAnnotation(authorizations = {"PERSONAL:ENTUSERTREE","PERSONAL:ENTUSERTREE:UPDATE"},name = "企业用户组织树") @MethodAnnotation(authorizations = {"entUserTree","entUserTree:update"},name = "企业用户组织树")
@ResponseBody @ResponseBody
public SingleResult<List<EntUser>> entUserTree(String enterpriseId, String postId)throws Exception{ public SingleResult<List<EntUser>> entUserTree(String enterpriseId, String postId)throws Exception{
return pcBusinessService.entUserTree(enterpriseId,postId); return pcBusinessService.entUserTree(enterpriseId,postId);
@ -182,8 +180,8 @@ public class PersonalController extends BaseController{
@ApiImplicitParam(name = "postId", value = "企业用户岗位id",required = false, dataType = "string"), @ApiImplicitParam(name = "postId", value = "企业用户岗位id",required = false, dataType = "string"),
}) })
@GetMapping(value = "/entUserPostList") @GetMapping(value = "/entUserPostList")
@PreAuthorize("hasAnyAuthority('PERSONAL:ENTUSERPOSTLIST','PERSONAL:ENTUSERPOSTLIST:UPDATE')") @PreAuthorize("hasAnyAuthority('entUserPostList','entUserPostList:update')")
@MethodAnnotation(authorizations = {"PERSONAL:ENTUSERPOSTLIST","PERSONAL:ENTUSERPOSTLIST:UPDATE"},name = "企业用户工作要务") @MethodAnnotation(authorizations = {"entUserPostList","entUserPostList:update"},name = "企业用户工作要务")
@ResponseBody @ResponseBody
public SingleResult entUserPostList(String enterpriseId, String entUserId,String postId,Integer page,Integer pageSize)throws Exception{ public SingleResult entUserPostList(String enterpriseId, String entUserId,String postId,Integer page,Integer pageSize)throws Exception{
return pcBusinessService.entUserPostList(enterpriseId,entUserId,postId,page,pageSize); return pcBusinessService.entUserPostList(enterpriseId,entUserId,postId,page,pageSize);
@ -210,8 +208,8 @@ public class PersonalController extends BaseController{
}) })
@GetMapping(value = "/entUserPostTask") @GetMapping(value = "/entUserPostTask")
@PreAuthorize("hasAnyAuthority('PERSONAL:ENTUSERPOSTTASK','PERSONAL:ENTUSERPOSTTASK:UPDATE')") @PreAuthorize("hasAnyAuthority('entUserPostTask','entUserPostTask:update')")
@MethodAnnotation(authorizations = {"PERSONAL:ENTUSERPOSTTASK","PERSONAL:ENTUSERPOSTTASK:UPDATE"},name = "企业用户工作清单") @MethodAnnotation(authorizations = {"entUserPostTask","entUserPostTask:update"},name = "企业用户工作清单")
@ResponseBody @ResponseBody
public SingleResult entUserPostTask(String enterpriseId, String entUserId,String postId,String listId,String content,Integer taskState,Integer page,Integer pageSize)throws Exception{ public SingleResult entUserPostTask(String enterpriseId, String entUserId,String postId,String listId,String content,Integer taskState,Integer page,Integer pageSize)throws Exception{
return pcBusinessService.entUserPostTask(enterpriseId,entUserId,postId,listId,content,taskState,page,pageSize); return pcBusinessService.entUserPostTask(enterpriseId,entUserId,postId,listId,content,taskState,page,pageSize);
@ -232,8 +230,8 @@ public class PersonalController extends BaseController{
}) })
@GetMapping(value = "/entUserPostDuty") @GetMapping(value = "/entUserPostDuty")
@PreAuthorize("hasAnyAuthority('PERSONAL:POSTDUTY','PERSONAL:POSTDUTY:UPDATE')") @PreAuthorize("hasAnyAuthority('entUserPostDuty','entUserPostDuty:update')")
@MethodAnnotation(authorizations = {"PERSONAL:POSTDUTY","PERSONAL:POSTDUTY:UPDATE"},name = "企业用户岗位职责") @MethodAnnotation(authorizations = {"entUserPostDuty","entUserPostDuty:update"},name = "企业用户岗位职责")
@ResponseBody @ResponseBody
public SingleResult entUserPostDuty(String enterpriseId, String postId,Integer page,Integer pageSize)throws Exception{ public SingleResult entUserPostDuty(String enterpriseId, String postId,Integer page,Integer pageSize)throws Exception{
return pcBusinessService.entUserPostDuty(enterpriseId,postId,page,pageSize); return pcBusinessService.entUserPostDuty(enterpriseId,postId,page,pageSize);
@ -250,8 +248,8 @@ public class PersonalController extends BaseController{
@ApiImplicitParam(name = "entUserId", value = "企业用户id",required = true, dataType = "string"), @ApiImplicitParam(name = "entUserId", value = "企业用户id",required = true, dataType = "string"),
}) })
@GetMapping(value = "/entUserCredential") @GetMapping(value = "/entUserCredential")
@PreAuthorize("hasAnyAuthority('PERSONAL:ENTUSERCREDENTIAL','PERSONAL:ENTUSERCREDENTIAL:UPDATE')") @PreAuthorize("hasAnyAuthority('entUserCredential','entUserCredential:update')")
@MethodAnnotation(authorizations = {"PERSONAL:ENTUSERCREDENTIAL","PERSONAL:ENTUSERCREDENTIAL:UPDATE"},name = "企业用户证照表") @MethodAnnotation(authorizations = {"entUserCredential","entUserCredential:update"},name = "企业用户证照表")
@ResponseBody @ResponseBody
public SingleResult entUserCredential(String entUserId,Integer page,Integer pageSize)throws Exception{ public SingleResult entUserCredential(String entUserId,Integer page,Integer pageSize)throws Exception{
return pcBusinessService.entUserCredential(null,entUserId,page,pageSize); return pcBusinessService.entUserCredential(null,entUserId,page,pageSize);
@ -268,8 +266,8 @@ public class PersonalController extends BaseController{
@ApiImplicitParam(name = "entUserId", value = "企业用户id",required = true, dataType = "string"), @ApiImplicitParam(name = "entUserId", value = "企业用户id",required = true, dataType = "string"),
}) })
@PostMapping(value = "/entUserCredentialUpdate") @PostMapping(value = "/entUserCredentialUpdate")
@PreAuthorize("hasAnyAuthority('PERSONAL:ENTUSERCREDENTIAL:UPDATE')") @PreAuthorize("hasAnyAuthority('entUserCredentialUpdate:update')")
@MethodAnnotation(authorizations = {"PERSONAL:ENTUSERCREDENTIAL:UPDATE"},name = "企业用户证照表-新增,修改") @MethodAnnotation(authorizations = {"entUserCredentialUpdate:update"},name = "企业用户证照表-新增,修改")
@ResponseBody @ResponseBody
public SingleResult entUserCredentialUpdate(@RequestBody EntUserCredentialUpdateDto entUserCredentialUpdateDto)throws Exception{ public SingleResult entUserCredentialUpdate(@RequestBody EntUserCredentialUpdateDto entUserCredentialUpdateDto)throws Exception{
return pcBusinessService.entUserCredentialUpdate(entUserCredentialUpdateDto); return pcBusinessService.entUserCredentialUpdate(entUserCredentialUpdateDto);
@ -287,8 +285,8 @@ public class PersonalController extends BaseController{
@ApiImplicitParam(name = "credentialId", value = "证件照id",required = true, dataType = "string"), @ApiImplicitParam(name = "credentialId", value = "证件照id",required = true, dataType = "string"),
}) })
@PostMapping(value = "/entUserCredentialDelete") @PostMapping(value = "/entUserCredentialDelete")
@PreAuthorize("hasAnyAuthority('PERSONAL:ENTUSERCREDENTIAL:DELETE')") @PreAuthorize("hasAnyAuthority('entUserCredentialDelete')")
@MethodAnnotation(authorizations = {"PERSONAL:ENTUSERCREDENTIAL:DELETE"},name = "企业用户证照表-删除") @MethodAnnotation(authorizations = {"entUserCredentialDelete"},name = "企业用户证照表-删除")
@ResponseBody @ResponseBody
public SingleResult entUserCredentialDelete(String credentialId)throws Exception{ public SingleResult entUserCredentialDelete(String credentialId)throws Exception{
return pcBusinessService.entUserCredentialDelete(credentialId); return pcBusinessService.entUserCredentialDelete(credentialId);
@ -306,8 +304,8 @@ public class PersonalController extends BaseController{
@ApiImplicitParam(name = "keyContent", value = "搜索关键字",required = false, dataType = "string"), @ApiImplicitParam(name = "keyContent", value = "搜索关键字",required = false, dataType = "string"),
}) })
@GetMapping(value = "/entUserList") @GetMapping(value = "/entUserList")
@PreAuthorize("hasAnyAuthority('PERSONAL:ENTUSERLIST','PERSONAL:ENTUSERLIST:UPDATE')") @PreAuthorize("hasAnyAuthority('entUserList','entUserList:update')")
@MethodAnnotation(authorizations = {"PERSONAL:ENTUSERLIST","PERSONAL:ENTUSERLIST:UPDATE"},name ="企业岗位总体信息列表") @MethodAnnotation(authorizations = {"entUserList","entUserList:update"},name = "企业岗位总体信息列表")
@ResponseBody @ResponseBody
public SingleResult entUserList(String keyContent,Integer page,Integer pageSize)throws Exception{ public SingleResult entUserList(String keyContent,Integer page,Integer pageSize)throws Exception{
return pcBusinessService.entUserList(keyContent,page,pageSize); return pcBusinessService.entUserList(keyContent,page,pageSize);

View File

@ -2,10 +2,13 @@ package com.rzyc.service;
import com.rzyc.config.UserDetailsAndId; import com.rzyc.config.UserDetailsAndId;
import com.rzyc.enums.SysEnterpriseState;
import com.rzyc.mapper.AuthorityKeyMapper; import com.rzyc.mapper.AuthorityKeyMapper;
import com.rzyc.mapper.ent.EntUserMapper; import com.rzyc.mapper.ent.EntUserMapper;
import com.rzyc.mapper.ent.SysEnterpriseMapper;
import com.rzyc.model.AuthorityKey; import com.rzyc.model.AuthorityKey;
import com.rzyc.model.ent.EntUser; import com.rzyc.model.ent.EntUser;
import com.rzyc.model.ent.SysEnterprise;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
@ -40,6 +43,9 @@ public class UserDetailsServiceImpl implements UserDetailsService {
* */ * */
private EntUserMapper entUserMapper; private EntUserMapper entUserMapper;
/**
* 权限表mapper
* */
private AuthorityKeyMapper authorityKeyMapper; private AuthorityKeyMapper authorityKeyMapper;
@Autowired @Autowired
@ -53,11 +59,12 @@ public class UserDetailsServiceImpl implements UserDetailsService {
@Override @Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String name){
//判断数据库用户 //判断数据库用户
EntUser entUser = entUserMapper.selectByName(name); EntUser entUser = entUserMapper.selectByName(name);
if (Objects.isNull(entUser)){ if (Objects.isNull(entUser)){
throw new UsernameNotFoundException("用户名或密码错误"); throw new UsernameNotFoundException("用户名不存在");
} }
List<GrantedAuthority> authority= new ArrayList<GrantedAuthority>(); List<GrantedAuthority> authority= new ArrayList<GrantedAuthority>();
List<AuthorityKey>authorizations = authorityKeyMapper.allAuthorizations(); List<AuthorityKey>authorizations = authorityKeyMapper.allAuthorizations();

View File

@ -3,7 +3,11 @@ package com.rzyc.service;
import com.common.utils.jwt.JwtUtil; import com.common.utils.jwt.JwtUtil;
import com.rzyc.advice.CustomException;
import com.rzyc.config.UserDetailsAndId; import com.rzyc.config.UserDetailsAndId;
import com.rzyc.enums.SysEnterpriseState;
import com.rzyc.mapper.ent.SysEnterpriseMapper;
import com.rzyc.model.ent.SysEnterprise;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@ -25,25 +29,41 @@ import java.util.Objects;
@Service @Service
public class UserLoginService { public class UserLoginService {
/**
* spring security 登陆业务接口service
* */
private UserDetailsService userDetailsService; private UserDetailsService userDetailsService;
/**
* spring security 内存中加密
* */
private PasswordEncoder passwordEncoder; private PasswordEncoder passwordEncoder;
/**
* 企业端公司
* */
private SysEnterpriseMapper sysEnterpriseMapper;
@Autowired @Autowired
public void UserLoginServiceFinder(UserDetailsService userDetailsService,PasswordEncoder passwordEncoder){ public void UserLoginServiceFinder(UserDetailsService userDetailsService,PasswordEncoder passwordEncoder,SysEnterpriseMapper sysEnterpriseMapper){
this.userDetailsService = userDetailsService; this.userDetailsService = userDetailsService;
this.passwordEncoder = passwordEncoder; this.passwordEncoder = passwordEncoder;
this.sysEnterpriseMapper= sysEnterpriseMapper;
} }
public String login(String username, String password) { public String login(String username, String password)throws Exception {
String token = null; String token = null;
try { try {
UserDetails userDetails = userDetailsService.loadUserByUsername(username); UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (Objects.isNull(userDetails)) { if (Objects.isNull(userDetails)) {
throw new UsernameNotFoundException("账号不存在"); throw new UsernameNotFoundException("账号不存在");
} }
SysEnterprise sysEnterprise = sysEnterpriseMapper.findEnterpriseByName(username);
if (Objects.isNull(sysEnterprise) || sysEnterprise.getState().equals(SysEnterpriseState.DISABLE)){
throw new CustomException("企业不存在或已经禁用");
}
//这里可能会不对因为我们是MD5这个是spring security 中的 encoder加密 //这里可能会不对因为我们是MD5这个是spring security 中的 encoder加密
if (!passwordEncoder.matches(password, userDetails.getPassword())) { if (!passwordEncoder.matches(password, userDetails.getPassword())) {
throw new BadCredentialsException("密码不正确"); throw new BadCredentialsException("密码不正确");

View File

@ -5,9 +5,15 @@ import com.common.utils.RandomNumber;
import com.rzyc.controller.EmergencyController; import com.rzyc.controller.EmergencyController;
import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.File;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.sql.*; import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** /**
* 工具 * 工具
@ -17,12 +23,75 @@ import java.sql.*;
*/ */
public class GovMethodSignature { public class GovMethodSignature {
public static void main(String[] args) throws ClassNotFoundException {
String [] packageName = {"inventory-gov/src/main/java/com/rzyc/controller"};
List<Class<?>> classes = new ArrayList<>();
HashMap<String,String> classNames = scanForPackageName(packageName);
for (Map.Entry<String, String> next: classNames.entrySet()) {
try {
classes.add(Class.forName(next.getValue()));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//反射controller获取所有方法 for (Class<?> c:classes) {
Method[] methods = EmergencyController.class.getMethods(); //反射获取所有方法
insertAnnotation(methods); Method[] methods = c.getMethods();
RequestMapping requestMapping = c.getAnnotation(RequestMapping.class);
if (null != requestMapping && null != requestMapping.value()[0]) {
String controllerName = requestMapping.value()[0];
insertAnnotation(controllerName, methods);
}
}
}
public static HashMap<String,String> scanForPackageName(String [] path){
HashMap<String,String> classNames = new HashMap<>();
String fileName = null;
for (String s:path) {
//根据传入文件夹路径创建File对象
File dir = new File(s);
//检查是否为文件夹
if (dir.isDirectory()){
//遍历文件夹内的文件
for (File f : dir.listFiles()){
if (f.isDirectory()){
for (File f2 : f.listFiles()){
//获取文件名,并删除后缀
fileName = f2.getName();
try {
fileName = fileName.substring(0,fileName.lastIndexOf("."));
}catch (Exception e){
System.err.println(fileName);
}
//添加到结果中
String filePath = f2.getPath().substring(f2.getPath().indexOf("java")+5,f2.getPath().length()).replace("\\",".").replace(".java","");
classNames.put(fileName,filePath);
continue;
}
}else {
//获取文件名,并删除后缀
fileName = f.getName();
try {
fileName = fileName.substring(0,fileName.lastIndexOf("."));
}catch (Exception e){
System.err.println(fileName);
}
//添加到结果中
String filePath = f.getPath().substring(f.getPath().indexOf("java")+5,f.getPath().length()).replace("\\",".").replace(".java","");
classNames.put(fileName,filePath);
continue;
}
}
}
}
return classNames;
} }
@ -41,7 +110,7 @@ public class GovMethodSignature {
return ds; return ds;
} }
private static void insertAnnotation(Method[] methods) { private static void insertAnnotation(String controllerName,Method[] methods) {
try { try {
//创建connection //创建connection
@ -60,17 +129,16 @@ public class GovMethodSignature {
for (String name : annotation.authorizations()) { for (String name : annotation.authorizations()) {
String str = name.substring(name.indexOf(":")+1,name.length());
ResultSet rs = statement.executeQuery("select auth_key from authority_key where auth_key ='"+str+"'"); ResultSet rs = statement.executeQuery("select auth_key from authority_key where auth_key ='"+name+"'");
//取数据 //取数据
if (rs.next()) { if (rs.next()) {
} else { } else {
String category = name.substring(0,name.indexOf(":"));
preparedStatement.setString(1, RandomNumber.getUUid()); preparedStatement.setString(1, RandomNumber.getUUid());
preparedStatement.setString(2,null); preparedStatement.setString(2,null);
preparedStatement.setString(3,str); preparedStatement.setString(3,name);
preparedStatement.setString(4,category); preparedStatement.setString(4,controllerName);
preparedStatement.setString(5, DateUtils.getNowDateTimeStr()); preparedStatement.setString(5, DateUtils.getNowDateTimeStr());
preparedStatement.setString(6,DateUtils.getNowDateTimeStr()); preparedStatement.setString(6,DateUtils.getNowDateTimeStr());
preparedStatement.setString(7,annotation.name()); preparedStatement.setString(7,annotation.name());
@ -92,4 +160,6 @@ public class GovMethodSignature {
} }
} }

View File

@ -64,7 +64,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
http http
.authorizeRequests() .authorizeRequests()
// 对于登录接口 允许匿名访问 // 对于登录接口 允许匿名访问
.antMatchers("/personal/login","/personal/entlogin").anonymous() .antMatchers("/personal/login","/personal/entlogin","/common/generateCode").anonymous()
//放行swagger //放行swagger
.antMatchers("/swagger-ui.html","/swagger-resources/**","/webjars/**","/v2/**","/api/**").permitAll() .antMatchers("/swagger-ui.html","/swagger-resources/**","/webjars/**","/v2/**","/api/**").permitAll()
// 除上面外的所有请求全部需要鉴权认证,配置退出路径 // 除上面外的所有请求全部需要鉴权认证,配置退出路径

View File

@ -623,8 +623,8 @@ public class EmergencyController extends BaseController {
* */ * */
@ApiOperation(value = "事故类型", notes = "事故类型") @ApiOperation(value = "事故类型", notes = "事故类型")
@GetMapping("/accidentType") @GetMapping("/accidentType")
@PreAuthorize("hasAnyAuthority('PCEMERGENCY:ACCIDENTTYPE','PCEMERGENCY:ACCIDENTTYPE:UPDATE')") @PreAuthorize("hasAnyAuthority('accidentType','accidentType:updatae')")
@MethodAnnotation(authorizations = {"PCEMERGENCY:ACCIDENTTYPE","PCEMERGENCY:ACCIDENTTYPE:UPDATE"},name = "事故类型") @MethodAnnotation(authorizations = {"accidentType","accidentType:update"},name = "事故类型")
@ResponseBody @ResponseBody
public SingleResult<AccidentType> accidentType()throws Exception{ public SingleResult<AccidentType> accidentType()throws Exception{
SingleResult singleResult = new SingleResult(); SingleResult singleResult = new SingleResult();