Commit 9486e95a by 陈皓

init

parents
HELP.md
.gradle
/build/
/logs/
**/build/
**/out/
**/logs/
!gradle/wrapper/gradle-wrapper.jar
*.log
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
/out/
**/target/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
This diff is collapsed. Click to expand it.
package com.mailu.ocrCloudPlatformAdmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class OcrCloudPlatformAdminApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(OcrCloudPlatformAdminApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(OcrCloudPlatformAdminApplication.class);
}
}
package com.mailu.ocrCloudPlatformAdmin.config;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 跨域配置
*/
//@Configuration
public class CorsConfig implements WebMvcConfigurer {
/* @Autowired
private File sysDir;
@Autowired
private File sysSettingFile;*/
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
String[] domains = {"http://localhost:63342","http://localhost:9090"};
/* XmlUtil xmlUtil = new XmlUtil(sysSettingFile);
List list = xmlUtil.getRoot().selectNodes("//domain");
if (!Objects.isNull(list) && list.size() > 0) {
List<String> domainList = new ArrayList<>();
for (Object obj : list) {
Element element = (Element) obj;
if (!StringUtils.isEmpty(element.getTextTrim())) {
domainList.add(element.getTextTrim());
System.out.println("域名:" + element.getTextTrim());
}
}
domains = new String[domainList.size()];
domainList.toArray(domains);
}
System.out.println(Arrays.toString(domains));*/
registry.addMapping("/**").
allowedOrigins("*"). //允许跨域的域名,可以用*表示允许任何域名使用
allowedMethods("*"). //允许任何方法(post、get等)
allowedHeaders("*"). //允许任何请求头
allowCredentials(true). //带上cookie信息
exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); //maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果
}
};
}
}
package com.mailu.ocrCloudPlatformAdmin.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.mailu.ocrCloudPlatformAdmin.mapper", sqlSessionFactoryRef = "mysql1SqlSessionFactory")
public class Datasource1Config {
@Bean(name = "mysql1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.mysql1")
@Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "mysql1SqlSessionFactory")
@Primary
public SqlSessionFactory testSqlSessionFactory(@Qualifier("mysql1DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setTypeAliasesPackage("com.mailu.ocrCloudPlatformAdmin.entity");
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mappers/*.xml"));
return bean.getObject();
}
@Bean(name = "mysql1TransactionManager")
@Primary
public DataSourceTransactionManager testTransactionManager(@Qualifier("mysql1DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "mysql1SqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("mysql1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
package com.mailu.ocrCloudPlatformAdmin.config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.mailu.ocrCloudPlatformAdmin.mapper1", sqlSessionFactoryRef = "mysql2SqlSessionFactory")
//@MapperScan(basePackages = "com.mailu.ocrCloudPlatformAdmin.mapper1", sqlSessionFactoryRef = "mysql2SqlSessionFactory", sqlSessionTemplateRef = "mysql2SqlSessionTemplate")
//@MapperScan(basePackages = "com.mailu.ocrCloudPlatformAdmin.mapper1", sqlSessionFactoryRef = "mysql2SqlSessionTemplate")
public class Datasource2Config {
@Bean(name = "mysql2DataSource")
@ConfigurationProperties(prefix = "spring.datasource.mysql2")
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
/* @Bean(name = "mysql2SqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("mysql2DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setTypeAliasesPackage("com.mailu.ocrCloudPlatformAdmin.entity");
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mappers1/*.xml"));
return bean.getObject();
}*/
@Bean(name = "mysql2TransactionManager")
public DataSourceTransactionManager testTransactionManager(@Qualifier("mysql2DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
/* @Bean(name = "mysql2SqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("mysql2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}*/
}
package com.mailu.ocrCloudPlatformAdmin.config;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @Author HuangHao
* @Date 2023/3/6 10:48
* @Description TODO
*/
@Configuration
public class RedisConfig {
@SuppressWarnings("all")
@Bean(name = "redisTemplate")
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
//序列化
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
// value值的序列化采用fastJsonRedisSerializer
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
// 全局开启AutoType,这里方便开发,使用全局的方式
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
// 建议使用这种方式,小范围指定白名单
// ParserConfig.getGlobalInstance().addAccept("me.zhengjie.domain");
// key的序列化采用StringRedisSerializer
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
\ No newline at end of file
package com.mailu.ocrCloudPlatformAdmin.config;
import com.mailu.ocrCloudPlatformAdmin.filter.CasProperties;
import com.mailu.ocrCloudPlatformAdmin.filter.CustomCasFilter;
import com.mailu.ocrCloudPlatformAdmin.filter.SpmsFilterInvocationSecurityMetadataSource;
import com.mailu.ocrCloudPlatformAdmin.manager.SpmsAccessDecisionManager;
import com.mailu.ocrCloudPlatformAdmin.service.CustomUserDetailsService;
import org.jasig.cas.client.session.SingleSignOutFilter;
import org.jasig.cas.client.validation.Cas20ServiceTicketValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.authentication.CasAuthenticationProvider;
import org.springframework.security.cas.web.CasAuthenticationEntryPoint;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
@Configuration
@EnableWebSecurity //启用web权限
@EnableGlobalMethodSecurity(securedEnabled = true) //启用方法验证
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CasProperties casProperties;
/**
* @Description: 配置放行的资源
**/
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/static/**", "/favicon.ico")
.antMatchers("/layuiadmin/**", "/layui/**", "/view/**", "/js/**", "/css/**", "/img/**", "/images/**")
.antMatchers("/pub/**", "/client/add", "/client/changeStatus", "/client/pub/**", "/user/addClerk")
.antMatchers("/session/invalid", "/city/**", "/token/**")
.antMatchers("/courtTrial/pub/**", "/tribunal/**", "/note/pub/**", "/assistRecord/pub/**")
.antMatchers("/websocket/**", "/template/**", "/file/**","/caption/**","/user/password","/password")
.antMatchers("/case/**","/doorUser/**","/client/syncData","/client/syncAssistant","/door/**")
.antMatchers("/test/**");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
auth.authenticationProvider(casAuthenticationProvider());
}
@Autowired
private SpmsFilterInvocationSecurityMetadataSource spmsFilterInvocationSecurityMetadataSource; //权限过滤器(当前url所需要的访问权限)
@Autowired
private SpmsAccessDecisionManager spmsAccessDecisionManager;//权限决策器
@Override
protected void configure(HttpSecurity http) throws Exception {
//禁用csrf保护机制
http.csrf().disable();
//禁用cors保护机制
http.cors().disable();
http.headers().frameOptions().disable();
http.authorizeRequests()//配置安全策略
.anyRequest().authenticated()
/*.antMatchers("/**").hasAnyAuthority("ROLE_USER")*/
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O o) {
o.setSecurityMetadataSource(spmsFilterInvocationSecurityMetadataSource);
o.setAccessDecisionManager(spmsAccessDecisionManager);
return o;
}
})
.and().exceptionHandling()
.authenticationEntryPoint(casAuthenticationEntryPoint())
.and()
.addFilterAt(casAuthenticationFilter(), CasAuthenticationFilter.class)
.addFilterBefore(logoutFilter(), LogoutFilter.class)
.addFilterBefore(singleSignOutFilter(), CasAuthenticationFilter.class);
}
/**
* CAS认证入口点开始 =============================================================================
*/
@Bean
public CasAuthenticationEntryPoint casAuthenticationEntryPoint() {
CasAuthenticationEntryPoint casAuthenticationEntryPoint = new CasAuthenticationEntryPoint();
casAuthenticationEntryPoint.setLoginUrl(casProperties.getCasServerLoginUrl());
casAuthenticationEntryPoint.setServiceProperties(serviceProperties());
return casAuthenticationEntryPoint;
}
@Bean
public ServiceProperties serviceProperties() {
ServiceProperties serviceProperties = new ServiceProperties();
//serviceProperties.setService(casProperties.getAppServerLoginUrl());
serviceProperties.setService(casProperties.getAppServerLoginUrl());
serviceProperties.setSendRenew(false);
return serviceProperties;
}
/**
* CAS认证入口点结束 =============================================================================
*/
/**
* CAS认证过滤器开始 =============================================================================
*/
@Bean
public CasAuthenticationFilter casAuthenticationFilter() throws Exception {
CustomCasFilter casAuthenticationFilter = new CustomCasFilter(casProperties);
casAuthenticationFilter.setAuthenticationManager(authenticationManager());
// casAuthenticationFilter.setFilterProcessesUrl(casProperties.getAppServerLoginUrl());
return casAuthenticationFilter;
}
@Bean
public Cas20ServiceTicketValidator cas20ServiceTicketValidator() {
return new Cas20ServiceTicketValidator(casProperties.getCasServerUrl());
}
@Bean
public CasAuthenticationProvider casAuthenticationProvider() {
CasAuthenticationProvider casAuthenticationProvider = new CasAuthenticationProvider();
casAuthenticationProvider.setAuthenticationUserDetailsService(userDetailsByNameServiceWrapper());
casAuthenticationProvider.setServiceProperties(serviceProperties());
casAuthenticationProvider.setTicketValidator(cas20ServiceTicketValidator());
casAuthenticationProvider.setKey("an_id_for_this_auth_provider_only");
return casAuthenticationProvider;
}
@Bean
public UserDetailsByNameServiceWrapper userDetailsByNameServiceWrapper() {
UserDetailsByNameServiceWrapper userDetailsByNameServiceWrapper = new UserDetailsByNameServiceWrapper();
userDetailsByNameServiceWrapper.setUserDetailsService(userDetailsService());
return userDetailsByNameServiceWrapper;
}
@Bean
public UserDetailsService userDetailsService() {
return new CustomUserDetailsService();
}
/**
* CAS认证过滤器结束 =============================================================================
*/
/**
* CAS登出过滤器开始 =============================================================================
*/
@Bean
public LogoutFilter logoutFilter() {
LogoutFilter logoutFilter = new LogoutFilter(casProperties.getCasServerLogoutUrl(), new SecurityContextLogoutHandler());
logoutFilter.setFilterProcessesUrl(casProperties.getAppServerLogoutUrl());
return logoutFilter;
}
@Bean
public SingleSignOutFilter singleSignOutFilter() {
SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter();
singleSignOutFilter.setCasServerUrlPrefix(casProperties.getCasServerUrl());
singleSignOutFilter.setIgnoreInitConfiguration(true);
return singleSignOutFilter;
}
/**
* CAS登出过滤器结束 =============================================================================
*/
}
package com.mailu.ocrCloudPlatformAdmin.config;
import com.mailu.ocrCloudPlatformAdmin.utils.MD5Util;
import org.springframework.security.crypto.password.PasswordEncoder;
public class SpmsPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
return MD5Util.encode((String) rawPassword);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return encodedPassword.equals(MD5Util.encode((String)rawPassword));
}
}
package com.mailu.ocrCloudPlatformAdmin.config;
import com.mailu.ocrCloudPlatformAdmin.utils.SystemCheckUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import java.io.File;
@Configuration
public class SystemConfig {
private static Logger log = LogManager.getLogger(SystemConfig.class);
@Value("${project.windows.sys-path}")
private String winPath;
@Value("${project.linux.sys-path}")
private String linuxPath;
private File sysPath;
private File captionPath;
/**
* 获取系统目录
*
* @return
*/
@Bean("sysDir")
@Order(1)
public File getSysDir() {
File file;
if (SystemCheckUtil.isWindows()) {
file = new File(winPath);
if (!file.exists()) {
file.mkdirs();
}
} else if (SystemCheckUtil.isLinux()) {
file = new File(linuxPath);
if (!file.exists()) {
file.setWritable(true, false);
file.mkdirs();
}
} else {
file = null;
}
this.sysPath = file;
return file;
}
@Bean("captionDir")
@Order(2)
public File getCaptionDir(){
File captionFile;
if (SystemCheckUtil.isWindows()) {
captionFile = new File(winPath,"caption");
if (!captionFile.exists()) {
captionFile.mkdirs();
}
} else if (SystemCheckUtil.isLinux()) {
captionFile = new File(linuxPath,"caption");
if (!captionFile.exists()) {
captionFile.setWritable(true, false);
captionFile.mkdirs();
}
} else {
captionFile = null;
}
this.captionPath = captionFile;
return captionFile;
}
@Bean("templateDir")
@Order(3)
public File getTemplateDir(){
File file;
if (SystemCheckUtil.isWindows()) {
file = new File(winPath,"template");
if (!file.exists()) {
file.mkdirs();
}
} else if (SystemCheckUtil.isLinux()) {
file = new File(linuxPath,"template");
if (!file.exists()) {
file.setWritable(true, false);
file.mkdirs();
}
} else {
file = null;
}
return file;
}
@Bean("publicDir")
@Order(4)
public File getPublicDir(){
File file;
if (SystemCheckUtil.isWindows()) {
file = new File(winPath,"public");
if (!file.exists()) {
file.mkdirs();
}
} else if (SystemCheckUtil.isLinux()) {
file = new File(linuxPath,"public");
if (!file.exists()) {
file.setWritable(true, false);
file.mkdirs();
}
} else {
file = null;
}
log.info("【public目录位置】"+file.getPath());
return file;
}
}
package com.mailu.ocrCloudPlatformAdmin.config;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.io.File;
@Configuration
public class SystemWebAppConfigurer implements WebMvcConfigurer {
private static Logger log = LogManager.getLogger(SystemWebAppConfigurer.class);
@Autowired
private File sysDir;
@Autowired
private File captionDir;
@Autowired
private File templateDir;
@Autowired
private File publicDir;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String tempFilePath = "file:" + templateDir.getPath() + File.separator;
log.info("【映射模板路径】" + tempFilePath);
String captionFilePath = "file:" + captionDir.getPath() +File.separator;
log.info("【映射字幕投屏路径】" + captionFilePath);
String pubFilePth = "file:" + publicDir.getPath() + File.separator;
log.info("【映射公开路径】" + pubFilePth);
registry.addResourceHandler("/template/**").addResourceLocations(tempFilePath);
registry.addResourceHandler("/caption/**").addResourceLocations(captionFilePath);
registry.addResourceHandler("/pub/**").addResourceLocations(pubFilePth);
registry.addResourceHandler("/viewFile/**").addResourceLocations("file:"+publicDir.getParent()+File.separator);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
.maxAge(3600);
}
}
package com.mailu.ocrCloudPlatformAdmin.config;
import com.mailu.ocrCloudPlatformAdmin.filter.SpmsFilterInvocationSecurityMetadataSource;
import com.mailu.ocrCloudPlatformAdmin.handler.SpmsAccessDeniedHandler;
import com.mailu.ocrCloudPlatformAdmin.handler.SpmsAuthenticationFailureHandler;
import com.mailu.ocrCloudPlatformAdmin.handler.SpmsAuthenticationSuccessHandler;
import com.mailu.ocrCloudPlatformAdmin.handler.SpmsLogoutSuccessHandler;
import com.mailu.ocrCloudPlatformAdmin.manager.SpmsAccessDecisionManager;
import com.mailu.ocrCloudPlatformAdmin.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.session.HttpSessionEventPublisher;
/**
* @Description: spring-security权限管理的核心配置
**/
/*@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) //全局*/
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserServiceImpl userService; //实现了UserDetailsService接口
@Autowired
private SpmsFilterInvocationSecurityMetadataSource spmsFilterInvocationSecurityMetadataSource; //权限过滤器(当前url所需要的访问权限)
@Autowired
private SpmsAccessDecisionManager spmsAccessDecisionManager;//权限决策器
@Autowired
private SpmsAccessDeniedHandler spmsAccessDeniedHandler;//自定义错误(403)返回数据
@Autowired
private SpmsAuthenticationSuccessHandler spmsAuthenticationSuccessHandler; //登录成功后处理
@Value("${login-page}")
private String loginPage;
/* @Autowired
SessionRegistryHandler sessionRegistry;*/
/**
* @Description: 配置userDetails的数据源,密码加密格式
**/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService)
.passwordEncoder(new SpmsPasswordEncoder());
}
/**
* @Description: 配置放行的资源
**/
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/static/**", loginPage, "/favicon.ico")
.antMatchers("/layuiadmin/**", "/layui/**", "/view/**", "/js/**", "/css/**", "/img/**", "/images/**")
.antMatchers("/pub/**", "/client/add", "/client/changeStatus", "/client/pub/**", "/user/addClerk")
.antMatchers("/session/invalid", "/city/**", "/token/**", "/court/**")
.antMatchers("/courtTrial/pub/**", "/tribunal/**", "/note/pub/**", "/assistRecord/pub/**")
.antMatchers("/websocket/**", "/template/**", "/file/**","/caption/**","/user/password","/password")
.antMatchers("/case/**","/doorUser/**","/client/syncData","/client/syncAssistant","/door/**");
}
/**
* @Description: HttpSecurity包含了原数据(主要是url)
* 通过withObjectPostProcessor将MyFilterInvocationSecurityMetadataSource和MyAccessDecisionManager注入进来
* 此url先被MyFilterInvocationSecurityMetadataSource处理,然后 丢给 MyAccessDecisionManager处理
* 如果不匹配,返回 MyAccessDeniedHandler
**/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().frameOptions().sameOrigin()
.httpStrictTransportSecurity().disable();
/* //session并发控制过滤器
http.addFilterAt(new ConcurrentSessionFilter(sessionRegistry),ConcurrentSessionFilter.class);*/
http.authorizeRequests()
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O o) {
o.setSecurityMetadataSource(spmsFilterInvocationSecurityMetadataSource);
o.setAccessDecisionManager(spmsAccessDecisionManager);
return o;
}
})
.and()
.formLogin().loginPage(this.loginPage).loginProcessingUrl("/login")
.usernameParameter("username").passwordParameter("password")
.failureHandler(new SpmsAuthenticationFailureHandler())
.successHandler(spmsAuthenticationSuccessHandler)
.permitAll()
/*.and() //session管理
.sessionManagement()//.sessionAuthenticationStrategy(new SpmsSessionAuthenticationStrategy(sessionRegistry)).sessionAuthenticationStrategy(new SpmsRegisterSessionAuthenticationStrategy(sessionRegistry))
.maximumSessions(1)//.sessionRegistry(sessionRegistry)
.maxSessionsPreventsLogin(true)//false之后登录踢掉之前登录,true则不允许之后登录*/
//.
// .sessionRegistry(sessionRegistry)
//.expiredSessionStrategy(new SessionExpiredStrategyHandler())
//.and()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(new SpmsLogoutSuccessHandler(this.loginPage))
.permitAll()
.and().csrf().disable()
.exceptionHandling().accessDeniedHandler(spmsAccessDeniedHandler);
//http.addFilter(new ConcurrentSessionFilter());
//http.sessionManagement().sessionAuthenticationFailureHandler();
//.invalidSessionUrl("/session/invalid"); session过期处理
}
@Bean
public SessionRegistry getSessionRegistry() {
return new SessionRegistryImpl();
}
@Bean
HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
}
package com.mailu.ocrCloudPlatformAdmin.constant;
/**
* @author: HuangHao
* @create: 2023-08-20 18:31
* @Description:
*/
public class RedisConstant {
//用户法庭信息前缀
public static final String COURT_INFO_USER_PREFIX = "court-role-user:";
}
package com.mailu.ocrCloudPlatformAdmin.constant;
/**
* @author: HuangHao
* @create: 2023-08-21 09:29
* @Description:
*/
public class RoleConstant {
//管理员
public static final String ADMIN = "admin";
//法院用户管理员
public static final String FY_USER_ADMIN = "fy_user_admin";
//业务系统管理员前缀
public static final String BUSINESS = "business_";
//普通用户
public static final String CLERK = "clerk";
//运维人员
public static final String YUNWEI = "yunwei";
}
package com.mailu.ocrCloudPlatformAdmin.controller;
import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
import com.mailu.ocrCloudPlatformAdmin.vo.OfsApiVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @Author HuangHao
* @Date 2023/9/14 10:14
* @Description TODO
*/
@RestController
@RequestMapping("/test")
public class ApiTestController {
@Value("${api.ml-cloud.ocrCloudPlatform}")
private String ocrCloudPlatformUrl;
@Value("${ocr.api-config.test.appId}")
private String appId;
@Value("${ocr.api-config.test.appKey}")
private String appKey;
@Value("${temp.dir}")
private String tempDir;
@Value("${app.server.host.url}")
private String hostUrl;
/**
* 文件上传
* <p>
* Authorization": "AppId d17cdc596f154dff91c2637ffc98ac24",
* X-Timestamp": "1694510167829",
* X-Checksum": "e43cd76a3bb8abaa168a00f2d27971ee"
*/
@PostMapping("/upload")
public Result upload(@RequestBody MultipartFile file) {
File tempDirF = new File(tempDir);
if (!tempDirF.exists()) {
tempDirF.mkdir();
}
File tempFile = new File(tempDirF, System.currentTimeMillis() + "_" + file.getOriginalFilename());
String result = null;
try {
//请求参数
Map<String, Object> paramMap = new HashMap<>();
file.transferTo(tempFile);
paramMap.put("file", tempFile);
paramMap.put("fileId", UUID.randomUUID().toString().replace("-", ""));
paramMap.put("createOfd", true);
//请求头
String time = String.valueOf(new Date().getTime());
Map<String, String> heads = new HashMap<>();
heads.put("Authorization", "AppId " + appId);
heads.put("X-Timestamp", time);
heads.put("X-Checksum", DigestUtil.md5Hex(appKey + time));
String url = ocrCloudPlatformUrl + "/ofs/api/sync/v1/1001";
result = HttpRequest.post(url).headerMap(heads, false).form(paramMap).execute().body();
JSONObject jsonObject = JSONUtil.parseObj(result);
if ("000000".equals(jsonObject.get("code"))){
OfsApiVo ofsApiVo = JSONUtil.toBean(jsonObject.get("data").toString(),OfsApiVo.class);
//处理sid精度丢失问题
jsonObject.set("data",ofsApiVo);
}
//删除临时文件
FileUtil.del(tempFile);
return Result.success("", jsonObject);
} catch (Exception e) {
e.printStackTrace();
}
return Result.error("", result);
}
/**
* 下载文件
*
* @param fileId
* @param sid
*/
@PostMapping("/download")
public void download(@RequestBody JSONObject pamar, HttpServletResponse response) {
OutputStream out;
try {
//请求头
String time = String.valueOf(new Date().getTime());
Map<String, String> heads = new HashMap<>();
heads.put("Authorization", "AppId " + appId);
heads.put("X-Timestamp", time);
heads.put("X-Checksum", DigestUtil.md5Hex(appKey + time));
//请求地址
String url = ocrCloudPlatformUrl + "/ofs/api/sync/v1/pdf";
//参数
HttpResponse execute = HttpRequest.post(url).headerMap(heads, true).body(pamar.toString()).execute();
if (execute.isOk()) {
//下载文件名
String fileName = pamar.get("fileId") + ".pdf";
//响应数据
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setContentType("application/pdf");
}
out = response.getOutputStream();
execute.writeBody(out, false, null);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.mailu.ocrCloudPlatformAdmin.controller;
import cn.hutool.core.util.StrUtil;
import com.mailu.ocrCloudPlatformAdmin.constant.RedisConstant;
import com.mailu.ocrCloudPlatformAdmin.constant.RoleConstant;
import com.mailu.ocrCloudPlatformAdmin.dto.AppAbilityRecordAllDto;
import com.mailu.ocrCloudPlatformAdmin.entity.Court;
import com.mailu.ocrCloudPlatformAdmin.entity.DoorUser;
import com.mailu.ocrCloudPlatformAdmin.entity.Role;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
import com.mailu.ocrCloudPlatformAdmin.service.AppAbilityRecordAllService;
import com.mailu.ocrCloudPlatformAdmin.service.CourtService;
import com.mailu.ocrCloudPlatformAdmin.service.RedisService;
import com.mailu.ocrCloudPlatformAdmin.service.RoleService;
import com.mailu.ocrCloudPlatformAdmin.utils.CourtUtil;
import com.mailu.ocrCloudPlatformAdmin.utils.UserUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author: HuangHao
* @create: 2023-08-20 18:07
* @Description:
*/
@RestController
@RequestMapping("appAbilityRecordAll")
public class AppAbilityRecordAllController {
@Resource
private AppAbilityRecordAllService appAbilityRecordAllService;
@Resource
private RedisService redisService;
@Resource
private RoleService roleService;
@Resource
private CourtService courtService;
/**
* 根据用户角色、权限 获取所有法院信息
*/
@GetMapping("/getCourtByRole")
public Result getCourtByRole() {
DoorUser currentUser = UserUtil.getCurrentUser();
//缓存取
List<Court> courts = redisService.getList(RedisConstant.COURT_INFO_USER_PREFIX + currentUser.getYouxiang(), Court.class, 1L, TimeUnit.DAYS);
if (courts == null) {
String role = UserUtil.getCurrentUserRole();
switch (role) {
case RoleConstant.ADMIN:
//内部管理员,返回全部数据
courts = courtService.getAll();
if (courts != null && courts.size() > 0) {
//加入缓存
redisService.set(RedisConstant.COURT_INFO_USER_PREFIX + currentUser.getYouxiang(), courts, 1L, TimeUnit.DAYS);
}
CourtUtil.listAddAll(courts);
return Result.success("", courts);
case RoleConstant.FY_USER_ADMIN:
//法院用户管理员(高院管理员:可查看全区数据,各下级法院管理员:仅看本院数据)
String fydm = currentUser.getFydm();
if (StrUtil.isNotEmpty(fydm)) {
courts = courtService.getByCode(Integer.valueOf(fydm));
if (courts != null && courts.size() > 0) {
//加入缓存
redisService.set(RedisConstant.COURT_INFO_USER_PREFIX + currentUser.getYouxiang(), courts, 1L, TimeUnit.DAYS);
}
CourtUtil.listAddAll(courts);
return Result.success("", courts);
}
break;
default:
//业务管理员 返回全部数据
if (role.startsWith(RoleConstant.BUSINESS)) {
courts = courtService.getAll();
if (courts != null && courts.size() > 0) {
//加入缓存
redisService.set(RedisConstant.COURT_INFO_USER_PREFIX + currentUser.getYouxiang(), courts, 1L, TimeUnit.DAYS);
}
CourtUtil.listAddAll(courts);
return Result.success("", courts);
} else if (RoleConstant.CLERK.equals(role) || RoleConstant.YUNWEI.equals(role)) {
//普通用户 和 运维人员 一样
String fydmClerk = currentUser.getFydm();
if (StrUtil.isNotEmpty(fydmClerk)) {
Court court = courtService.getByCourtCode(Integer.valueOf(fydmClerk));
if (court != null) {
courts = new LinkedList<>();
courts.add(court);
//加入缓存
redisService.set(RedisConstant.COURT_INFO_USER_PREFIX + currentUser.getYouxiang(), courts, 1L, TimeUnit.DAYS);
}
CourtUtil.listAddAll(courts);
return Result.success("", courts);
}
}
return Result.success("");
}
} else {
CourtUtil.listAddAll(courts);
return Result.success("", courts);
}
return Result.error("");
}
@PostMapping("/getListByPage")
public Result getListByPage(AppAbilityRecordAllDto dto) {
String roleName = UserUtil.getCurrentUserRole();
//是否是管理员
if (RoleConstant.ADMIN.equals(roleName)) {
if (dto.getCourtId() != null) {
List<Integer> courtCodeList = new ArrayList<>();
courtCodeList.add(dto.getCourtId());
dto.setCourtCodeList(courtCodeList);
}
return appAbilityRecordAllService.getListByPage(dto);
}
//获取用户所有的法庭信息
DoorUser currentUser = UserUtil.getCurrentUser();
List<Court> courts = redisService.getList(RedisConstant.COURT_INFO_USER_PREFIX + currentUser.getYouxiang(), Court.class, 1L, TimeUnit.DAYS);
if (courts != null) {
List<Integer> courtCodeList = new ArrayList<>();
if (dto.getCourtId() != null && CourtUtil.exist(courts, dto.getCourtId())) {
courtCodeList.add(dto.getCourtId());
} else {
//查全部
for (Court court : courts) {
courtCodeList.add(court.getCourtCode());
}
}
dto.setCourtCodeList(courtCodeList);
//业务管理员
if (roleName.startsWith(RoleConstant.BUSINESS)) {
Role role = roleService.selectByName(roleName);
dto.setDescription(role.getNameZh());
}
return appAbilityRecordAllService.getListByPage(dto);
}
return Result.error("");
}
}
package com.mailu.ocrCloudPlatformAdmin.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author: HuangHao
* @create: 2023-08-20 11:41
* @Description:
*/
@RestController
@RequestMapping("court")
public class CourtController {
}
package com.mailu.ocrCloudPlatformAdmin.controller;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
import com.mailu.ocrCloudPlatformAdmin.service.DoorUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("door")
public class DoorController {
@Autowired
private DoorUserService doorUserService;
@GetMapping("downloadUserAll")
public Result downloadUserAll() {
return doorUserService.downloadDoorUserAll();
}
@GetMapping("downloadOrdAll")
public Result downloadOrdAll() {
return doorUserService.downloadDoorOrgAll();
}
@GetMapping("getUserInfoByName")
public Result getUserInfoByName(String name) {
return doorUserService.getUserInfoByName(name);
}
}
package com.mailu.ocrCloudPlatformAdmin.controller;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
import com.mailu.ocrCloudPlatformAdmin.service.DoorUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/doorUser")
public class DoorUserController {
@Autowired
private DoorUserService userService;
@GetMapping("/downloadDoorMsg")
public Result downloadDoorMsg(){
return userService.updateUser();
}
@GetMapping("/updateOrg")
public Result updateOrg(){
return userService.updateOrg();
}
}
package com.mailu.ocrCloudPlatformAdmin.controller;
import com.mailu.ocrCloudPlatformAdmin.dto.MenuDto;
import com.mailu.ocrCloudPlatformAdmin.entity.Menu;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
import com.mailu.ocrCloudPlatformAdmin.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/menu")
public class MenuController {
@Autowired
private MenuService menuService;
/**
* 获取列表
* @return
*/
@RequestMapping("/list")
public Result list(MenuDto dto) {
return menuService.getAll(dto);
}
@GetMapping("/deleteByPrimaryKey")
public Result deleteByPrimaryKey(@RequestParam Integer id){
return menuService.deleteByPrimaryKey(id);
}
/**
* 新增
* @param menu
*/
@PostMapping(value = "/insertSelective",produces = "application/json")
public Result insertSelective(@RequestBody Menu menu){
return menuService.insertSelective(menu);
}
/**
* 根据ID获取数据
* @param id
* @return
*/
@GetMapping("/selectByPrimaryKey")
public Result selectByPrimaryKey(Integer id){
// System.out.println(id);
List<Menu> list = new ArrayList<>();
list.add(menuService.selectByPrimaryKey(id));
return Result.success("成功", list);
}
/**
* 根据ID获取数据
* @param menu
* @return
*/
@PostMapping(value = "/updateByPrimaryKeySelective", produces = "application/json")
public Result updateByPrimaryKeySelective(@RequestBody Menu menu){
return menuService.updateByPrimaryKeySelective(menu);
}
/**
* 获取所有菜单
* @return
*/
@GetMapping("/getAll")
public Result getAll(@RequestParam Integer id){
// System.out.println(id);
List<Menu> menus = menuService.selectList(id);
getMenus(menus,id);
return Result.success("成功", menus);
}
@GetMapping("/selectRoleId")
public Result selectRoleId(Integer id){
return Result.success("成功", menuService.selectRoleId(id));
}
public void getMenus(List<Menu> list, Integer id){
for (Menu menu : list){
List<Menu> menus = menuService.selectByParentId(menu.getId(),id);
menu.setChildren(menus);
getMenus(menus, id);
}
}
}
package com.mailu.ocrCloudPlatformAdmin.controller;
import com.mailu.ocrCloudPlatformAdmin.dto.Page;
import com.mailu.ocrCloudPlatformAdmin.entity.MenuRole;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
import com.mailu.ocrCloudPlatformAdmin.service.MenuRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/menuRole")
public class MenuRoleController {
@Autowired
private MenuRoleService menuRoleService;
@GetMapping("/selectAll")
public Result selectAll(Page page){
return menuRoleService.selectAll(page);
}
/**
* 根据id删除用户
* @param id
* @return
*/
@PostMapping("/deleteByPrimaryKey")
public Result deleteByPrimaryKey(@RequestParam int id){
return menuRoleService.deleteByPrimaryKey(id);
}
/**
* 新增
* @param menuRole
*/
@PostMapping("/insertSelective")
public Result insertSelective(MenuRole menuRole){
return menuRoleService.insertSelective(menuRole);
}
/**
* 根据id获取用户
* @param id
* @return
*/
@PostMapping("/getByPrimaryKey")
public Result getByPrimaryKey(@RequestParam int id){
MenuRole menuRole = menuRoleService.selectByPrimaryKey(id);
return Result.success("成功", menuRole);
}
/**
* 修改
* @param menuRole
*/
@PostMapping("/updateByPrimaryKeySelective")
public Result updateByPrimaryKeySelective(MenuRole menuRole){
return menuRoleService.updateByPrimaryKeySelective(menuRole);
}
}
package com.mailu.ocrCloudPlatformAdmin.controller;
import com.mailu.ocrCloudPlatformAdmin.dto.Page;
import com.mailu.ocrCloudPlatformAdmin.entity.Menu;
import com.mailu.ocrCloudPlatformAdmin.entity.Role;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
import com.mailu.ocrCloudPlatformAdmin.service.MenuService;
import com.mailu.ocrCloudPlatformAdmin.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/role")
public class RoleController {
@Autowired
private RoleService roleService;
@Autowired
private MenuService menuService;
@GetMapping("/selectList")
public Result selectList(){
return roleService.selectAll();
}
@GetMapping("/selectAll")
public Result selectAll(Page page){
return roleService.selectAll(page);
}
/**
* 根据id删除用户
* @param id
* @return
*/
@PostMapping("/deleteByPrimaryKey")
public Result deleteByPrimaryKey(@RequestParam int id){
return roleService.deleteByPrimaryKey(id);
}
/**
* 新增
* @param role
*/
@PostMapping(value = "/insertSelective", produces = "application/json")
public Result insertSelective(@RequestBody Role role){
return roleService.insertSelective(role);
}
/**
* 根据id获取用户
* @param id
* @return
*/
@PostMapping("/getByPrimaryKey")
public Result getByPrimaryKey(@RequestParam int id){
Role role = roleService.selectByPrimaryKey(id);
return Result.success("成功", role);
}
/**
* 修改
* @param role
*/
@PostMapping(value = "/updateByPrimaryKeySelective", produces = "application/json")
public Result updateByPrimaryKeySelective(@RequestBody Role role){
List<Menu> menus = role.getMenus();
return roleService.updateByPrimaryKeySelective(role);
}
/**
* 获取所有菜单
* @return
*/
@GetMapping("/getAll")
public Result getAll(@RequestParam Integer id){
List<Menu> menus = menuService.selectList(id);
getMenus(menus,id);
return Result.success("成功", menus);
}
public void getMenus(List<Menu> list, Integer id){
for (Menu menu : list){
List<Menu> menus = menuService.selectByParentId(menu.getId(),id);
menu.setChildren(menus);
getMenus(menus, id);
}
}
}
package com.mailu.ocrCloudPlatformAdmin.controller;
import com.mailu.ocrCloudPlatformAdmin.dto.Page;
import com.mailu.ocrCloudPlatformAdmin.dto.UserRoleDto;
import com.mailu.ocrCloudPlatformAdmin.entity.UserRole;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
import com.mailu.ocrCloudPlatformAdmin.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/userRole")
public class UserRoleController {
@Autowired
private UserRoleService userRoleService;
@GetMapping("/selectAll")
public Result selectAll(Page page) {
return userRoleService.selectAll(page);
}
@PostMapping("/getList")
public Result getList(@RequestBody UserRoleDto dto) {
return userRoleService.selectList(dto);
}
/**
* 根据id删除用户
*
* @param id
* @return
*/
@PostMapping("/deleteByPrimaryKey")
public Result deleteByPrimaryKey(@RequestParam Integer id) {
return userRoleService.deleteByPrimaryKey(id);
}
/**
* 新增
*
* @param userRole
*/
@PostMapping("/insertSelective")
public Result insertSelective(UserRole userRole) {
return userRoleService.insertSelective(userRole);
}
/**
* 根据id获取用户
*
* @param id
* @return
*/
@PostMapping("/getByPrimaryKey")
public Result getByPrimaryKey(@RequestParam int id) {
UserRole userRole = userRoleService.selectByPrimaryKey(id);
return Result.success("成功", userRole);
}
/**
* 修改
*
* @param userRole
*/
@PostMapping("/updateByPrimaryKeySelective")
public Result updateByPrimaryKeySelective(UserRole userRole) {
return userRoleService.updateByPrimaryKeySelective(userRole);
}
@PostMapping("/update")
public Result update(@RequestBody UserRole userRole) {
return userRoleService.update(userRole);
}
@PutMapping("/add")
public Result add(@RequestBody UserRole userRole){
return userRoleService.add(userRole);
}
}
package com.mailu.ocrCloudPlatformAdmin.dto;
import com.mailu.ocrCloudPlatformAdmin.entity.AppAbilityRecordAll;
import lombok.Data;
import java.util.List;
/**
* @author: HuangHao
* @create: 2023-08-20 18:14
* @Description:
*/
@Data
public class AppAbilityRecordAllDto extends AppAbilityRecordAll {
private Integer page;
private Integer limit;
private Integer courtId;
private Integer network;
private String description;
private List<Integer> courtCodeList;
}
package com.mailu.ocrCloudPlatformAdmin.dto;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
public class AppAbilityRecordDto implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 唯一标识
*/
private Long id;
/**
* 任务ID
*/
private String taskId = "";
/**
* 应用ID
*/
private Long applicationId;
/**
* 用户ID
*/
private Long userId;
/**
* 能力ID
*/
private Long abilityId;
/**
* IP地址
*/
private String ip = "";
/**
* 调用时间
*/
private LocalDateTime callTime;
/**
* 识别状态
*/
private Byte ocrState;
/**
* 客户端传的文件唯一标识
*/
private String fileId = "";
/**
* 待识别文件原始文件名
*/
private String originName = "";
/**
* 待识别文件保存文件名
*/
private String ocrFileName = "";
/**
* 待识别文件url
*/
private String srcUrl = "";
/**
* 文件大小
*/
private Long length;
/**
* 文件CRC32校验码
*/
private Long crc32;
/**
* 文件的CheckSum
*/
private String checksum = "";
/**
* 识别结果
*/
private String result = "";
/**
* 结果类型
*/
private Integer resultType;
/**
* 识别结果保存路径
*/
private String dstUrl = "";
/**
* 识别结果JSON文件url
*/
private String jsons = "";
/**
* 合并后双层PDF文件url
*/
private String pdf = "";
/**
* 是否需要回调通知结果
*/
private Boolean isCallback;
/**
* 回调URL
*/
private String callbackUrl = "";
/**
* 回调参数
*/
private String callbackParams = "";
/**
* 创建时间
*/
private LocalDateTime createdTime;
/**
* 更新时间
*/
private LocalDateTime updatedTime;
private String serverIp = "";
}
package com.mailu.ocrCloudPlatformAdmin.dto;
import lombok.Data;
/**
* @author: HuangHao
* @create: 2023-08-16 17:55
* @Description:
*/
@Data
public class MenuDto {
private String menuName;
private Integer menuType;
private Integer menuStatus;
}
package com.mailu.ocrCloudPlatformAdmin.dto;
import lombok.Data;
import java.io.Serializable;
@Data
public class Page implements Serializable {
private Integer page;
private Integer limit;
private String searchStr;
private Object data;
private String searchString;
private String search;
private Integer offset;
private String ip;
private String name;
private String siteId;
private String functionId;
private String courtCode;
private Integer roleId;
}
package com.mailu.ocrCloudPlatformAdmin.dto;
import com.mailu.ocrCloudPlatformAdmin.entity.UserRole;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Data
public class UserRoleDto extends UserRole {
private Integer page;
private Integer limit;
private String roleName;
private String roleNameZh;
private String userName;
private String email;
}
package com.mailu.ocrCloudPlatformAdmin.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 全部应用调用能力记录
* @TableName app_ability_record_all
*/
@Data
public class AppAbilityRecordAll implements Serializable {
/**
* 唯一标识
*/
private Long id;
/**
* 任务ID
*/
private String taskId;
/**
* 应用ID
*/
private Long applicationId;
/**
* 用户ID
*/
private Long userId;
/**
* 能力ID
*/
private Long abilityId;
/**
* IP地址
*/
private String ip;
/**
* 调用时间
*/
private Date callTime;
/**
* 识别状态
*/
private Byte ocrState;
/**
* 客户端传的文件唯一标识
*/
private String fileId;
/**
* 待识别文件原始文件名
*/
private String originName;
/**
* 待识别文件保存文件名
*/
private String ocrFileName;
/**
* 待识别文件url
*/
private String srcUrl;
/**
* 文件大小
*/
private Long length;
/**
* 文件CRC32校验码
*/
private Long crc32;
/**
* 文件的CheckSum
*/
private String checksum;
/**
* 识别结果
*/
private Object result;
/**
* 结果类型
*/
private Integer resultType;
/**
* 识别结果保存路径
*/
private String dstUrl;
/**
* 识别结果JSON文件url
*/
private Object jsons;
/**
* 合并后双层PDF文件url
*/
private String pdf;
/**
* 是否需要回调通知结果
*/
private Boolean isCallback;
/**
* 回调URL
*/
private String callbackUrl;
/**
* 回调参数
*/
private Object callbackParams;
/**
* 创建时间
*/
private Date createdTime;
/**
* 更新时间
*/
private Date updatedTime;
/**
* 服务器ip
*/
private String serverIp;
private static final long serialVersionUID = 1L;
}
\ No newline at end of file
package com.mailu.ocrCloudPlatformAdmin.entity;
import lombok.Data;
import java.io.Serializable;
/**
* 法庭表
* @TableName court
*/
@Data
public class Court implements Serializable {
/**
*
*/
private Integer id;
/**
* 地区行政代码
*/
private String adcode;
/**
* 全国法院代码
*/
private Integer courtCode;
/**
* 上级全国法院代码
*/
private Integer parentCourtCode;
/**
* 分级码
*/
private String classificationCode;
/**
* 法院名称
*/
private String name;
/**
* 门户ID
*/
private Integer portalId;
/**
* 缩写
*/
private String forSort;
/**
* 法院简称
*/
private String shortName;
/**
* 排序号
*/
private Integer sort;
/**
* IP返回
*/
private String ipScope;
private static final long serialVersionUID = 1L;
}
\ No newline at end of file
package com.mailu.ocrCloudPlatformAdmin.entity;
public class DoorOrg {
private Integer id;
private Integer pxh;
private String cjsj;
private Integer pcft;
private String lxr;
private String gxsj;
private String jglx;
private String bmqz;
private Integer jgbs;
private Integer orgid;
private Integer sftj;
private Integer zhfs;
private String fy;
private String fymc;
private String lxdh;
private Integer parentorgid;
private String mc;
private String dz;
private String cbaj;
private String jc;
private String sm;
private Integer yx;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getPxh() {
return pxh;
}
public void setPxh(Integer pxh) {
this.pxh = pxh;
}
public String getCjsj() {
return cjsj;
}
public void setCjsj(String cjsj) {
this.cjsj = cjsj == null ? null : cjsj.trim();
}
public Integer getPcft() {
return pcft;
}
public void setPcft(Integer pcft) {
this.pcft = pcft;
}
public String getLxr() {
return lxr;
}
public void setLxr(String lxr) {
this.lxr = lxr == null ? null : lxr.trim();
}
public String getGxsj() {
return gxsj;
}
public void setGxsj(String gxsj) {
this.gxsj = gxsj == null ? null : gxsj.trim();
}
public String getJglx() {
return jglx;
}
public void setJglx(String jglx) {
this.jglx = jglx == null ? null : jglx.trim();
}
public String getBmqz() {
return bmqz;
}
public void setBmqz(String bmqz) {
this.bmqz = bmqz == null ? null : bmqz.trim();
}
public Integer getJgbs() {
return jgbs;
}
public void setJgbs(Integer jgbs) {
this.jgbs = jgbs;
}
public Integer getOrgid() {
return orgid;
}
public void setOrgid(Integer orgid) {
this.orgid = orgid;
}
public Integer getSftj() {
return sftj;
}
public void setSftj(Integer sftj) {
this.sftj = sftj;
}
public Integer getZhfs() {
return zhfs;
}
public void setZhfs(Integer zhfs) {
this.zhfs = zhfs;
}
public String getFy() {
return fy;
}
public void setFy(String fy) {
this.fy = fy == null ? null : fy.trim();
}
public String getFymc() {
return fymc;
}
public void setFymc(String fymc) {
this.fymc = fymc == null ? null : fymc.trim();
}
public String getLxdh() {
return lxdh;
}
public void setLxdh(String lxdh) {
this.lxdh = lxdh == null ? null : lxdh.trim();
}
public Integer getParentorgid() {
return parentorgid;
}
public void setParentorgid(Integer parentorgid) {
this.parentorgid = parentorgid;
}
public String getMc() {
return mc;
}
public void setMc(String mc) {
this.mc = mc == null ? null : mc.trim();
}
public String getDz() {
return dz;
}
public void setDz(String dz) {
this.dz = dz == null ? null : dz.trim();
}
public String getCbaj() {
return cbaj;
}
public void setCbaj(String cbaj) {
this.cbaj = cbaj == null ? null : cbaj.trim();
}
public String getJc() {
return jc;
}
public void setJc(String jc) {
this.jc = jc == null ? null : jc.trim();
}
public String getSm() {
return sm;
}
public void setSm(String sm) {
this.sm = sm == null ? null : sm.trim();
}
public Integer getYx() {
return yx;
}
public void setYx(Integer yx) {
this.yx = yx;
}
}
package com.mailu.ocrCloudPlatformAdmin.entity;
import lombok.Data;
@Data
public class DoorResult {
private Integer listId;
private String BS;
private String GXSJ;
private Integer LX;
private Integer CZ;
}
package com.mailu.ocrCloudPlatformAdmin.entity;
public class Home implements Comparable<Home> {
private String name; //名称
private String type; //类型
private Integer azcs; //安装次数
private Integer sycs; //使用次数
private String sc; //时长
@Override
public String toString() {
return "Home{" +
"name='" + name + '\'' +
", type='" + type + '\'' +
", azcs=" + azcs +
", sycs=" + sycs +
", sc='" + sc + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getAzcs() {
return azcs;
}
public void setAzcs(Integer azcs) {
this.azcs = azcs;
}
public Integer getSycs() {
return sycs;
}
public void setSycs(Integer sycs) {
this.sycs = sycs;
}
public String getSc() {
return sc;
}
public void setSc(String sc) {
this.sc = sc;
}
@Override
public int compareTo(Home o) {
return o.getAzcs() - this.azcs;
}
}
package com.mailu.ocrCloudPlatformAdmin.entity;
import java.util.List;
import java.util.Objects;
public class Menu {
private Integer id;
private String url;
private String path;
private String component;
private String name;
private String iconClass;
private String keepAlive;
private String requireAuth;
private Integer parentId;
private List<Role> roles;
private List<Menu> children;
private Integer sort;
@Override
public String toString() {
return "Menu{" +
"id=" + id +
", url='" + url + '\'' +
", path='" + path + '\'' +
", component='" + component + '\'' +
", name='" + name + '\'' +
", iconClass='" + iconClass + '\'' +
", keepAlive='" + keepAlive + '\'' +
", requireAuth='" + requireAuth + '\'' +
", parentId=" + parentId +
", roles=" + roles +
", children=" + children +
", sort=" + sort +
'}';
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public List<Menu> getChildren() {
return children;
}
public void setChildren(List<Menu> children) {
this.children = children;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url == null ? null : url.trim();
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path == null ? null : path.trim();
}
public String getComponent() {
return component;
}
public void setComponent(String component) {
this.component = component == null ? null : component.trim();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getIconClass() {
return iconClass;
}
public void setIconClass(String iconClass) {
this.iconClass = iconClass == null ? null : iconClass.trim();
}
public String getKeepAlive() {
return keepAlive;
}
public void setKeepAlive(String keepAlive) {
this.keepAlive = keepAlive == null ? null : keepAlive.trim();
}
public String getRequireAuth() {
return requireAuth;
}
public void setRequireAuth(String requireAuth) {
this.requireAuth = requireAuth == null ? null : requireAuth.trim();
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public List<Role> getRoles() {
return this.roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Menu)) return false;
Menu menu = (Menu) o;
if (this.path.equals(menu.path)) return true;
return false;
}
@Override
public int hashCode() {
return Objects.hash(id, url, path, component, name, iconClass, keepAlive, requireAuth, parentId, roles, children);
}
}
package com.mailu.ocrCloudPlatformAdmin.entity;
public class MenuRole {
private Integer id;
private Integer menuId;
private Integer roleId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getMenuId() {
return menuId;
}
public void setMenuId(Integer menuId) {
this.menuId = menuId;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
}
package com.mailu.ocrCloudPlatformAdmin.entity;
import java.util.List;
public class Role {
private Integer id;
private String name;
private String nameZh;
private List<Menu> menus;
@Override
public String toString() {
return "Role{" +
"id=" + id +
", name='" + name + '\'' +
", nameZh='" + nameZh + '\'' +
", menus=" + menus +
'}';
}
public List<Menu> getMenus() {
return menus;
}
public void setMenus(List<Menu> menus) {
this.menus = menus;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getNameZh() {
return nameZh;
}
public void setNameZh(String nameZh) {
this.nameZh = nameZh == null ? null : nameZh.trim();
}
}
package com.mailu.ocrCloudPlatformAdmin.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 服务器资源表
* @TableName server_info
*/
@Data
public class ServerInfo implements Serializable {
/**
*
*/
private Integer serverId;
/**
* 服务器名称
*/
private String name;
/**
* 服务器IP
*/
private String ip;
/**
* OCR端口
*/
private Integer ocrPort;
/**
* 服务器登录名
*/
private String username;
/**
* 服务器登录密码
*/
private String password;
/**
* 是否接入服务,1-接入,0-不接入
*/
private Boolean accessService;
/**
* 创建时间
*/
private Date createdTime;
/**
* 创建者
*/
private String createdBy;
/**
* 更新时间
*/
private Date updatedTime;
/**
* 更新者
*/
private String updatedBy;
/**
* 接入网络,0-内网,1-外网
*/
private Integer network;
/**
* 法院代码
*/
private Integer courtCode;
private static final long serialVersionUID = 1L;
}
\ No newline at end of file
package com.mailu.ocrCloudPlatformAdmin.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class User implements UserDetails, Serializable {
private Integer id;
private String username;
private String password;
private String name;
/* private Boolean loginStatus;
private Boolean accountNonExpired;
private Boolean accountNonLocked;
private Boolean credentialsNonExpired;
private Boolean enabled;*/
private Boolean isAccountNonExpired;
private Boolean isAccountNonLocked;
private Boolean isCredentialsNonExpired;
private Boolean isEnabled;
private String classificationCode;
@JsonProperty(value = "RYBS")
private String RYBS;
private String cardId;
private String courtName;
private List<Role> roles;
public String getCourtName() {
return courtName;
}
public void setCourtName(String courtName) {
this.courtName = courtName;
}
public String getClassificationCode() {
return classificationCode;
}
public void setClassificationCode(String classificationCode) {
this.classificationCode = classificationCode;
}
public String getRYBS() {
return RYBS;
}
public void setRYBS(String RYBS) {
this.RYBS = RYBS;
}
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
/* @Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
if (!Objects.isNull(roles)){
authorities = new ArrayList<>(roles.size());
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
}
return authorities;
}*/
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
if (roles!=null){
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
}
//authorities.add(new SimpleGrantedAuthority("admin"));
return authorities;
}
/* private Collection<? extends GrantedAuthority> authorities;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {
this.authorities = authorities;
}*/
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
/* @Override
public int hashCode() {
return username.hashCode();
}
@Override
public boolean equals(Object obj) {
return this.toString().equals(obj.toString());
}
@Override
public String toString() {
return this.username;
}*/
}
package com.mailu.ocrCloudPlatformAdmin.entity;
import lombok.ToString;
@ToString
public class UserRole {
private Integer id;
private Integer userId;
private Integer roleId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
}
package com.mailu.ocrCloudPlatformAdmin.exception;
import org.springframework.security.core.AuthenticationException;
public class UserLoggedInException extends AuthenticationException {
public UserLoggedInException(String msg, Throwable t) {
super(msg, t);
}
public UserLoggedInException(String msg) {
super(msg);
}
}
package com.mailu.ocrCloudPlatformAdmin.filter;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 自定义属性配置类
*/
@Component
@Data
public class CasProperties {
@Value("${cas.server.host.url}")
private String casServerUrl;
@Value("${cas.server.host.login_url}")
private String casServerLoginUrl;
@Value("${cas.server.host.logout_url}")
private String casServerLogoutUrl;
@Value("${app.server.host.url}")
private String appServerUrl;
@Value("${app.server.host.login_url}")
private String appServerLoginUrl;
@Value("${app.server.host.logout_url}")
private String appServerLogoutUrl;
@Value("${server.servlet.context-path}")
private String contentPath;
}
package com.mailu.ocrCloudPlatformAdmin.filter;
import com.mailu.ocrCloudPlatformAdmin.entity.DoorUser;
import com.mailu.ocrCloudPlatformAdmin.utils.IpUtil;
import com.mailu.ocrCloudPlatformAdmin.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Slf4j
public class CustomCasFilter extends CasAuthenticationFilter {
private CasProperties casProperties;
public CustomCasFilter(CasProperties casProperties) {
this.casProperties = casProperties;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
/* HttpServletResponse httpServletResponse = (HttpServletResponse) response;
HttpSession session = httpServletRequest.getSession();*/
String uri = httpServletRequest.getRequestURI();
if (!uri.contains("/layui") && !uri.contains("/js") && !uri.contains("/img") && !uri.contains("/json")
&& !uri.contains("/pdfjs") && !uri.contains("/xls") && !uri.contains("/css") && !uri.contains("/test")) {
DoorUser currentUser = UserUtil.getCurrentUser();
String username = null;
if (currentUser != null) {
username = currentUser.getYouxiang();
}
log.info("IP地址:{},登录用户:{},访问地址:{}", IpUtil.getIpAddr(httpServletRequest), username, uri);
}
super.doFilter(request, response, chain);
}
}
package com.mailu.ocrCloudPlatformAdmin.filter;
import com.mailu.ocrCloudPlatformAdmin.entity.Menu;
import com.mailu.ocrCloudPlatformAdmin.entity.Role;
import com.mailu.ocrCloudPlatformAdmin.service.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import java.util.Collection;
import java.util.List;
/**
* FilterInvocationSecurityMetadataSource(权限资源过滤器接口)继承了 SecurityMetadataSource(权限资源接口)
* Spring Security是通过SecurityMetadataSource来加载访问时所需要的具体权限;Metadata是元数据的意思。
* 自定义权限资源过滤器,实现动态的权限验证
* 它的主要责任就是当访问一个url时,返回这个url所需要的访问权限
**/
@Component
public class SpmsFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
@Autowired
private MenuService menuService;
private AntPathMatcher antPathMatcher = new AntPathMatcher();
private static final Logger log = LoggerFactory.getLogger(SpmsFilterInvocationSecurityMetadataSource.class);
/**
* @Description: 返回本次访问需要的权限,可以有多个权限
**/
@Override
public Collection<ConfigAttribute> getAttributes(Object o) {
String requestUrl = ((FilterInvocation) o).getRequestUrl();
// System.out.println(requestUrl);
//去数据库查询资源
List<Menu> allMenu = menuService.getAllMenu();
for (Menu menu : allMenu) {
if (antPathMatcher.match(menu.getUrl(), requestUrl)
&& menu.getRoles().size() > 0) {
List<Role> roles = menu.getRoles();
int size = roles.size();
String[] values = new String[size];
for (int i = 0; i < size; i++) {
String roleName = roles.get(i).getName();
values[i] = roleName;
}
return SecurityConfig.createList(values);
}
}
return SecurityConfig.createList("ROLE_LOGIN");
}
/**
* @Description: 此处方法如果做了实现,返回了定义的权限资源列表,
* Spring Security会在启动时校验每个ConfigAttribute是否配置正确,
* 如果不需要校验,这里实现方法,方法体直接返回null即可。
**/
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
/**
* @Description: 方法返回类对象是否支持校验,
* web项目一般使用FilterInvocation来判断,或者直接返回true
**/
@Override
public boolean supports(Class<?> aClass) {
return FilterInvocation.class.isAssignableFrom(aClass);
}
}
package com.mailu.ocrCloudPlatformAdmin.handler;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.ResponseErrorHandler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* 自定义RestTemplate异常处理
*/
public class CustomResponseErrorHandler implements ResponseErrorHandler {
private ResponseErrorHandler errorHandler = new DefaultResponseErrorHandler();
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return true;
}
// inputStream 装换为 string
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
package com.mailu.ocrCloudPlatformAdmin.handler;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 此处我们可以自定义403响应的内容,让他返回我们的错误逻辑提示
*/
@Component
public class SpmsAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException e) throws IOException {
//response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//WebMvcWrite.writeToWeb(response,Result.unauthorized("权限不足,请联系管理员!"));
System.out.println("权限不足");
response.sendRedirect("/ocrAdmin/error/403");
}
}
package com.mailu.ocrCloudPlatformAdmin.handler;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
import com.mailu.ocrCloudPlatformAdmin.response.WebMvcWrite;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 认证失败
*/
public class SpmsAuthenticationFailureHandler implements AuthenticationFailureHandler {
private static final Logger log = LoggerFactory.getLogger(SpmsAuthenticationFailureHandler.class);
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
Result result;
if (exception instanceof BadCredentialsException ||
exception instanceof UsernameNotFoundException) {
result = Result.unauthorized("账户名或者密码输入错误!");
} else if (exception instanceof LockedException) {
result = Result.unauthorized("账户被锁定,请联系管理员!");
} else if (exception instanceof CredentialsExpiredException) {
result = Result.unauthorized("密码过期,请联系管理员!");
} else if (exception instanceof AccountExpiredException) {
result = Result.unauthorized("账户过期,请联系管理员!");
} else if (exception instanceof DisabledException) {
result = Result.unauthorized("账户被禁用,请联系管理员!");
}else if(exception instanceof SessionAuthenticationException){
result = Result.unauthorized("账号已经在别的地方登录,当前登录已失效。如果密码遭到泄露,请立即修改密码!");
} else {
result = Result.unauthorized(exception.getMessage());
}
log.warn(result.toString());
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
WebMvcWrite.writeToWeb(response, result);
}
}
package com.mailu.ocrCloudPlatformAdmin.handler;
import com.mailu.ocrCloudPlatformAdmin.entity.User;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
import com.mailu.ocrCloudPlatformAdmin.response.WebMvcWrite;
import com.mailu.ocrCloudPlatformAdmin.utils.IpUtil;
import com.mailu.ocrCloudPlatformAdmin.utils.UserUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
/**
* 认证成功处理
*/
@Component
public class SpmsAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
public SpmsAuthenticationSuccessHandler() {
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
String ipAddr = IpUtil.getIpAddr(request);
System.out.println("IP地址:" + ipAddr);
User currentUser = UserUtil.getCurrentUser();
//String jwt = JwtTokenUtil.createJWT(currentUser, this.jwt);
RequestCache cache = new HttpSessionRequestCache();
SavedRequest savedRequest = cache.getRequest(request, response);
if (Objects.isNull(savedRequest)) {
//WebMvcWrite.writeToWeb(response,Result.success("登录成功","/ocrCloudPlatformAdmin/?token="+jwt));
WebMvcWrite.writeToWeb(response, Result.success("登录成功", "/ocrAdmin/"));
} else {
String url = savedRequest.getRedirectUrl();
String[] tokens = savedRequest.getParameterValues("token");
if (!Objects.isNull(tokens)) {
//String token = tokens[0];
// System.out.println("token:"+token);
//url = url.replace(token, jwt);
// System.out.println(url);
WebMvcWrite.writeToWeb(response, Result.success("登录成功", url));
} else {
//WebMvcWrite.writeToWeb(response,Result.success("登录成功",url+"?token="+jwt));
WebMvcWrite.writeToWeb(response, Result.success("登录成功", url));
}
}
}
}
package com.mailu.ocrCloudPlatformAdmin.handler;
import com.mailu.ocrCloudPlatformAdmin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 退出登录
*/
public class SpmsLogoutSuccessHandler implements LogoutSuccessHandler {
private String logoutPage;
@Autowired
private UserService userService;
public SpmsLogoutSuccessHandler() {
}
public SpmsLogoutSuccessHandler(String logoutUrl) {
this.logoutPage = logoutUrl;
}
@Override
public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
/* User currentUser = UserUtil.getCurrentUser();
System.out.println("当前对出登录的用户:"+currentUser);*/
//WebMvcWrite.writeToWeb(resp, Result.success("注销成功"));
req.getRequestDispatcher(this.logoutPage).forward(req,resp);
}
}
package com.mailu.ocrCloudPlatformAdmin.manager;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Iterator;
/**
* @Author: Galen
* @Date: 2019/3/27-16:59
* @Description: Decision决定的意思。
* 有了权限资源(MyFilterInvocationSecurityMetadataSource),知道了当前访问的url需要的具体权限,接下来就是决策当前的访问是否能通过权限验证了
* MyAccessDecisionManager 自定义权限决策管理器
**/
@Component
public class SpmsAccessDecisionManager implements AccessDecisionManager {
/**
* @Author: Galen
* @Description: 取当前用户的权限与这次请求的这个url需要的权限作对比,决定是否放行
* auth 包含了当前的用户信息,包括拥有的权限,即之前UserDetailsService登录时候存储的用户对象
* object 就是FilterInvocation对象,可以得到request等web资源。
* configAttributes 是本次访问需要的权限。即上一步的 MyFilterInvocationSecurityMetadataSource 中查询核对得到的权限列表
* @Date: 2019/3/27-17:18
* @Param: [auth, object, cas]
* @return: void
**/
@Override
public void decide(Authentication auth, Object object, Collection<ConfigAttribute> cas) {
Iterator<ConfigAttribute> iterator = cas.iterator();
while (iterator.hasNext()) {
if (auth == null) {
throw new AccessDeniedException("当前访问没有权限");
}
ConfigAttribute ca = iterator.next();
//当前请求需要的权限
String needRole = ca.getAttribute();
if ("ROLE_LOGIN".equals(needRole)) {
if (auth instanceof AnonymousAuthenticationToken) {
throw new BadCredentialsException("未登录");
} else
return;
}
//当前用户所具有的权限
Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
for (GrantedAuthority authority : authorities) {
if (authority.getAuthority().equals(needRole)) {
return;
}
}
}
throw new AccessDeniedException("权限不足!");
}
@Override
public boolean supports(ConfigAttribute configAttribute) {
return true;
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
package com.mailu.ocrCloudPlatformAdmin.mapper;
import com.github.pagehelper.Page;
import com.mailu.ocrCloudPlatformAdmin.entity.AppAbilityRecordAll;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @Entity com.mailu.ocrCloudPlatformAdmin.entity.AppAbilityRecordAll
*/
@Mapper
public interface AppAbilityRecordAllMapper {
int deleteByPrimaryKey(Long id);
int insert(AppAbilityRecordAll record);
int insertSelective(AppAbilityRecordAll record);
AppAbilityRecordAll selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(AppAbilityRecordAll record);
int updateByPrimaryKey(AppAbilityRecordAll record);
Page<AppAbilityRecordAll> selectByCondition(List<String> serverIpList);
Page<AppAbilityRecordAll> selectByBusinessCondition(@Param("list") List<String> serverIpList,@Param("description") String description);
}
package com.mailu.ocrCloudPlatformAdmin.mapper;
import com.mailu.ocrCloudPlatformAdmin.entity.Court;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @Entity com.mailu.ocrCloudPlatformAdmin.entity.Court
*/
@Mapper
public interface CourtMapper {
int deleteByPrimaryKey(Long id);
int insert(Court record);
int insertSelective(Court record);
Court selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(Court record);
int updateByPrimaryKey(Court record);
List<Court> selectAll();
List<Court> selectByCourtCode(Integer code);
Court selectOneByCourtCode(Integer courtCode);
}
package com.mailu.ocrCloudPlatformAdmin.mapper;
import com.mailu.ocrCloudPlatformAdmin.entity.DoorOrg;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Mapper
public interface DoorOrgMapper {
int deleteByPrimaryKey(Integer id);
int insert(DoorOrg record);
int insertSelective(DoorOrg record);
DoorOrg selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(DoorOrg record);
int updateByPrimaryKey(DoorOrg record);
int selectCount();
DoorOrg selectByJgbs(Integer jgbs);
List<DoorOrg> selectAll();
}
package com.mailu.ocrCloudPlatformAdmin.mapper;
import com.mailu.ocrCloudPlatformAdmin.entity.DoorUser;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Mapper
public interface DoorUserMapper {
int deleteByPrimaryKey(Integer id);
int insert(DoorUser record);
int insertSelective(DoorUser record);
DoorUser selectByPrimaryKey(Integer id);
List<DoorUser> selectByName(String name);
int updateByPrimaryKeySelective(DoorUser record);
int updateByPrimaryKey(DoorUser record);
int selectCount();
DoorUser selectByEmail(String youxiang);
}
package com.mailu.ocrCloudPlatformAdmin.mapper;
import com.mailu.ocrCloudPlatformAdmin.dto.MenuDto;
import com.mailu.ocrCloudPlatformAdmin.entity.Menu;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Mapper
public interface MenuMapper {
int deleteByPrimaryKey(Integer id);
int deleteById(Integer id);
int insert(Menu record);
int insertSelective(Menu record);
Menu selectByPrimaryKey(Integer id);
List<Menu> selectByParentId(Integer id,Integer id_);
int updateByPrimaryKeySelective(Menu record);
int updateByPrimaryKey(Menu record);
List<Menu> findAll();
List<Menu> getAllMenusWithRole();
List<Menu> selectAll();
List<Menu> selectList(Integer id);
List<Menu> selectRoleId(Integer id);
List<Menu> getAll(MenuDto dto);
}
package com.mailu.ocrCloudPlatformAdmin.mapper;
import com.mailu.ocrCloudPlatformAdmin.entity.MenuRole;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Mapper
public interface MenuRoleMapper {
int deleteByPrimaryKey(Integer id);
int insert(MenuRole record);
int insertSelective(MenuRole record);
MenuRole selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(MenuRole record);
int updateByPrimaryKey(MenuRole record);
List<MenuRole> selectAll(String searchStr);
int deleteByMenuId(Integer id);
int deleteByRoleId(Integer id);
}
package com.mailu.ocrCloudPlatformAdmin.mapper;
import com.mailu.ocrCloudPlatformAdmin.dto.Page;
import com.mailu.ocrCloudPlatformAdmin.entity.Role;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Mapper
public interface RoleMapper {
int deleteByPrimaryKey(Integer id);
int insert(Role record);
int insertSelective(Role record);
Role selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Role record);
int updateByPrimaryKey(Role record);
List<Role> selectAll();
List<Role> selectByPage(Page page);
int getInsertId();
List<Role> selectByMenuId(Integer menuId);
Role selectByNameZH(String nameZh);
List<Role> selectByUserId(Integer userId);
Role selectByName(String roleName);
}
package com.mailu.ocrCloudPlatformAdmin.mapper;
import com.mailu.ocrCloudPlatformAdmin.dto.AppAbilityRecordAllDto;
import com.mailu.ocrCloudPlatformAdmin.entity.ServerInfo;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @Entity com.mailu.ocrCloudPlatformAdmin.entity.ServerInfo
*/
@Mapper
public interface ServerInfoMapper {
int deleteByPrimaryKey(Long id);
int insert(ServerInfo record);
int insertSelective(ServerInfo record);
ServerInfo selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(ServerInfo record);
int updateByPrimaryKey(ServerInfo record);
List<String> selectServerIpList(AppAbilityRecordAllDto dto);
}
package com.mailu.ocrCloudPlatformAdmin.mapper;
import com.mailu.ocrCloudPlatformAdmin.dto.Page;
import com.mailu.ocrCloudPlatformAdmin.entity.Role;
import com.mailu.ocrCloudPlatformAdmin.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Mapper
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
User loadUserByUsername(String username);
List<Role> getUserRolesById(Integer id);
List<User> selectAll(Page page);
List<User> getUserNameList(String username);
int editPwd(User record);
List<User> selectUsers(Integer userId);
User selectByRYBS(User record);
User getUsernameAndPassword(String username, String password);
}
package com.mailu.ocrCloudPlatformAdmin.mapper;
import com.mailu.ocrCloudPlatformAdmin.dto.UserRoleDto;
import com.mailu.ocrCloudPlatformAdmin.entity.UserRole;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Mapper
public interface UserRoleMapper {
int deleteByPrimaryKey(Integer id);
int insert(UserRole record);
int insertSelective(UserRole record);
UserRole selectByPrimaryKey(Integer id);
List<UserRole> selectByUserId(Integer userId);
int updateByPrimaryKeySelective(UserRole record);
int updateByPrimaryKey(UserRole record);
List<UserRole> selectAll(String searchStr);
List<UserRoleDto> selectList(UserRoleDto dto);
int deleteByUserId(Integer id);
int deleteByRoleId(Integer id);
}
package com.mailu.ocrCloudPlatformAdmin.response;
import cn.hutool.core.date.DateUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author HuangHao
* @Date 2023/9/14 10:42
* @Description TODO
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ApiResult {
public static final String ERROR = "500";
public static final String SUCCESS = "000000";
private String code;
private String message;
private Object data;
private Long time;
public static ApiResult success(String msg) {
return new ApiResult(SUCCESS, msg, null, DateUtil.current());
}
public static ApiResult error(String msg) {
return new ApiResult(ERROR, msg, null, DateUtil.current());
}
}
package com.mailu.ocrCloudPlatformAdmin.response;
import javax.servlet.http.HttpServletResponse;
public class Result {
public static final Integer ERROR = -1;
public static final Integer SUCCESS = 200;
private Integer code;
private String msg;
private Long count;
private Object data;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Long getCount() {
return count;
}
public void setCount(Long count) {
this.count = count;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Result(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Result(Integer code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public Result(Integer code, String msg, Long count, Object data) {
this.code = code;
this.msg = msg;
this.count = count;
this.data = data;
}
public static Result error(String msg) {
return new Result(ERROR, msg);
}
public static Result error(Exception e) {
return new Result(ERROR, "出现未知错误,错误信息:" + e.getMessage());
}
public static Result error(String msg, Object data) {
return new Result(ERROR, msg, data);
}
public static Result unauthorized(String msg) {
return new Result(HttpServletResponse.SC_UNAUTHORIZED, msg);
}
public static Result success(String msg) {
return new Result(SUCCESS, msg);
}
public static Result putSuccess() {
return new Result(SUCCESS, "修改成功");
}
public static Result delSuccess() {
return new Result(SUCCESS, "删除成功");
}
public static Result addSuccess() {
return new Result(SUCCESS, "新增成功");
}
public static Result success(String msg, Object data) {
return new Result(SUCCESS, msg, data);
}
public static Result success(String msg, Long count, Object data) {
return new Result(SUCCESS, msg, count, data);
}
public static String unknownError(String msg) {
return "出现未知错误,错误信息:" + msg;
}
@Override
public String toString() {
return "Result{" +
"code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
}
package com.mailu.ocrCloudPlatformAdmin.response;
import com.alibaba.fastjson.JSON;
import java.io.Serializable;
/**
* websocket发送消息对象
*/
public class SendObject implements Serializable {
private String uid;
private String toUid;
private String type;
private String msg;
public SendObject(String toUid, String type, String msg) {
this.toUid = toUid;
this.type = type;
this.msg = msg;
}
public SendObject() {
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getToUid() {
return toUid;
}
public void setToUid(String toUid) {
this.toUid = toUid;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String toJSONStr(){
return JSON.toJSONString(this);
}
}
package com.mailu.ocrCloudPlatformAdmin.response;
import com.alibaba.fastjson.JSON;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class WebMvcWrite {
public static void writeToWeb(HttpServletResponse response, Result result) throws IOException {
//这里直接写自己的处理逻辑,比如下面这段代码
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
out.write(JSON.toJSONString(result));
out.flush();
out.close();
}
}
package com.mailu.ocrCloudPlatformAdmin.service;
import com.mailu.ocrCloudPlatformAdmin.dto.AppAbilityRecordAllDto;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
public interface AppAbilityRecordAllService {
Result getListByPage(AppAbilityRecordAllDto dto);
}
package com.mailu.ocrCloudPlatformAdmin.service;
import com.mailu.ocrCloudPlatformAdmin.entity.Court;
import java.util.List;
public interface CourtService {
List<Court> getAll();
List<Court> getByCode(Integer code);
void clearCourtInfo(String youxiang);
Court getByCourtCode(Integer courtCode);
}
package com.mailu.ocrCloudPlatformAdmin.service;
import com.alibaba.fastjson.JSONObject;
import com.mailu.ocrCloudPlatformAdmin.entity.DoorUser;
import com.mailu.ocrCloudPlatformAdmin.mapper.DoorUserMapper;
import com.mailu.ocrCloudPlatformAdmin.mapper.RoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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;
@Slf4j
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private DoorUserMapper doorUserMapper;
@Autowired
private RoleMapper roleMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
DoorUser user = doorUserMapper.selectByEmail(username);
System.out.println("登录用户:"+JSONObject.toJSONString(user));
int i = username.lastIndexOf("@");
String uname = username;
if (i != -1) {
uname = username.substring(0, i);
}
//.replace("@gxfy.com", "");
/* String userInfoStr = HttpUtil.sendPostOrPut(getUserInfoUrl +uname , "", new HashMap<>(), HttpUtil.POST);
if (StringUtils.isEmpty(userInfoStr)){
throw new UsernameNotFoundException("用户不存在");
}
User user = JSON.parseObject(userInfoStr, User.class);*/
user.setUsername(uname);
user.setName(user.getXm());
user.setRoles(roleMapper.selectByUserId(user.getId()));
/* user.setAccountNonExpired(true);
user.setAccountNonLocked(true);
user.setCredentialsNonExpired(true);
user.setEnabled(true);*/
return user;
}
}
package com.mailu.ocrCloudPlatformAdmin.service;
public interface DoorOrgService {
}
package com.mailu.ocrCloudPlatformAdmin.service;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
public interface DoorUserService {
Result downloadDoorMsg();
Result downloadDoorUserAll();
Result downloadDoorOrgAll();
Result updateOrg();
Result getUserInfoByName(String name);
Result updateUser();
}
package com.mailu.ocrCloudPlatformAdmin.service;
import com.mailu.ocrCloudPlatformAdmin.dto.Page;
import com.mailu.ocrCloudPlatformAdmin.entity.MenuRole;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
public interface MenuRoleService {
Result deleteByPrimaryKey(Integer id);
int insert(MenuRole record);
Result insertSelective(MenuRole record);
MenuRole selectByPrimaryKey(Integer id);
Result updateByPrimaryKeySelective(MenuRole record);
int updateByPrimaryKey(MenuRole record);
Result selectAll(Page page);
int deleteByMenuId(Integer id);
int deleteByRoleId(Integer id);
}
package com.mailu.ocrCloudPlatformAdmin.service;
import com.mailu.ocrCloudPlatformAdmin.dto.MenuDto;
import com.mailu.ocrCloudPlatformAdmin.entity.Menu;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
import java.util.List;
public interface MenuService {
List<Menu> getAllMenu();
Result getList();
Result deleteByPrimaryKey(Integer id);
Menu selectByPrimaryKey(Integer id);
Result insertSelective(Menu record);
Result updateByPrimaryKeySelective(Menu record);
List<Menu> selectByParentId(Integer id,Integer id_);
List<Menu> selectList(Integer id);
List<Menu> selectRoleId(Integer id);
Result getAll(MenuDto dto);
List<Menu> getMenus(Integer roleId);
}
package com.mailu.ocrCloudPlatformAdmin.service;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Service
public class RedisService {
@Autowired
private RedisTemplate redisTemplate;
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存设置时效时间
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime, TimeUnit timeUnit) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, timeUnit);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 读取缓存
*
* @param key
* @return
*/
public <T> T get(final String key, Class<T> clazz) {
Object o = get(key);
if (o != null) {
return JSONUtil.toBean(JSONUtil.parseObj(o), clazz);
}
return null;
}
/**
* 读取缓存
*
* @param key
* @return
*/
public Object get(final String key, Long time, TimeUnit timeUnit) {
Object result = get(key);
if (result != null) {
setExpire(key, time, timeUnit);
}
return result;
}
/**
* 读取缓存
*
* @param key
* @return
*/
public <T> List<T> getList(final String key, Class<T> clazz) {
Object o = get(key);
return BeanUtil.copyToList((Collection<T>) o, clazz);
}
/**
* 读取缓存
*
* @param key
* @return
*/
public <T> List<T> getList(final String key, Class<T> clazz, Long time, TimeUnit timeUnit) {
List<T> result = getList(key, clazz);
if (result != null) {
setExpire(key, time, timeUnit);
}
return result;
}
/**
* 根据前缀获取所有的key
* 例如:pro_*
*/
public Set<String> getListKey(String prefix) {
Set<String> keys = redisTemplate.keys(prefix.concat("*"));
return keys;
}
/**
* 设置过期时间
*/
public Boolean setExpire(String key, Long time, TimeUnit timeUnit) {
return redisTemplate.expire(key, time, timeUnit);
}
/**
* 获取过期时间
*/
public Long getExpire(String key, TimeUnit timeUnit) {
return redisTemplate.getExpire(key, timeUnit);
}
/**
* 删除指定前缀的一系列key
*
* @param pattern 匹配keys的规则
*/
public void deleteKeysByScan(String pattern) {
long start = System.currentTimeMillis();
String param = pattern + "*";
Set<String> keys = this.getValuesForStringByScan(param);
redisTemplate.delete(keys);
}
/**
* 获取匹配的所有key,使用scan避免阻塞
*
* @param patten 匹配keys的规则
* @return 返回获取到的keys
*/
public Set<String> getValuesForStringByScan(String patten) {
return (Set<String>) redisTemplate.execute(connect -> {
Set<String> binaryKeys = new HashSet<>();
Cursor<byte[]> cursor = connect.scan(new ScanOptions.ScanOptionsBuilder().match(patten).count(200000).build());
while (cursor.hasNext() && binaryKeys.size() < 200000) {
binaryKeys.add(new String(cursor.next()));
}
return binaryKeys;
}, true);
}
}
package com.mailu.ocrCloudPlatformAdmin.service;
import com.mailu.ocrCloudPlatformAdmin.dto.Page;
import com.mailu.ocrCloudPlatformAdmin.entity.Role;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
public interface RoleService {
Result deleteByPrimaryKey(Integer id);
int insert(Role role);
Result insertSelective(Role role);
Role selectByPrimaryKey(Integer id);
Result updateByPrimaryKeySelective(Role role);
int updateByPrimaryKey(Role role);
Result selectAll(Page page);
Result selectAll();
Role selectByNameZH(String nameZh);
Role selectByName(String roleName);
}
package com.mailu.ocrCloudPlatformAdmin.service;
import com.mailu.ocrCloudPlatformAdmin.dto.Page;
import com.mailu.ocrCloudPlatformAdmin.dto.UserRoleDto;
import com.mailu.ocrCloudPlatformAdmin.entity.UserRole;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
public interface UserRoleService {
Result deleteByPrimaryKey(Integer id);
int insert(UserRole record);
Result insertSelective(UserRole record);
Result add(UserRole record);
UserRole selectByPrimaryKey(Integer id);
Result updateByPrimaryKeySelective(UserRole record);
Result update(UserRole record);
int updateByPrimaryKey(UserRole record);
Result selectAll(Page page);
Result selectList(UserRoleDto dto);
int deleteByUserId(Integer id);
int deleteByRoleId(Integer id);
}
package com.mailu.ocrCloudPlatformAdmin.service;
import com.mailu.ocrCloudPlatformAdmin.dto.Page;
import com.mailu.ocrCloudPlatformAdmin.entity.Role;
import com.mailu.ocrCloudPlatformAdmin.entity.User;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.List;
public interface UserService {
Result deleteByPrimaryKey(Integer id);
int insert(User record);
Result insertSelective(User record);
User selectByPrimaryKey(Integer id);
Result updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
Result selectAll(Page page);
List<Role> getUserRolesById(Integer id);
UserDetails loadUserByUsername(String username);
void insertUser(User record);
List<User> getUserNameList(String username);
Result editPwd(User record);
Result selectUsers(Integer userId);
User selectByRYBS(User record);
User getUsernameAndPassword(String username, String password);
}
package com.mailu.ocrCloudPlatformAdmin.service.impl;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mailu.ocrCloudPlatformAdmin.dto.AppAbilityRecordAllDto;
import com.mailu.ocrCloudPlatformAdmin.entity.AppAbilityRecordAll;
import com.mailu.ocrCloudPlatformAdmin.mapper.AppAbilityRecordAllMapper;
import com.mailu.ocrCloudPlatformAdmin.mapper.ServerInfoMapper;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
import com.mailu.ocrCloudPlatformAdmin.service.AppAbilityRecordAllService;
import com.mailu.ocrCloudPlatformAdmin.vo.PageVo;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @author: HuangHao
* @create: 2023-08-20 18:12
* @Description:
*/
@Service
public class AppAbilityRecordAllServiceImpl implements AppAbilityRecordAllService {
@Resource
private ServerInfoMapper serverInfoMapper;
@Resource
private AppAbilityRecordAllMapper appAbilityRecordAllMapper;
@Override
public Result getListByPage(AppAbilityRecordAllDto dto) {
List<String> serverIpList = serverInfoMapper.selectServerIpList(dto);
if (serverIpList != null && serverIpList.size() > 0) {
Page<AppAbilityRecordAll> page;
if (StrUtil.isEmpty(dto.getDescription())) {
page = PageHelper.startPage(dto.getPage(), dto.getLimit()).doSelectPage(()
-> appAbilityRecordAllMapper.selectByCondition(serverIpList));
}else {
//业务系统管理员查询
page = PageHelper.startPage(dto.getPage(), dto.getLimit()).doSelectPage(()
-> appAbilityRecordAllMapper.selectByBusinessCondition(serverIpList,dto.getDescription()));
}
PageVo pageVo = new PageVo(page);
return Result.success("", pageVo);
}
return Result.success("", new PageVo());
}
}
package com.mailu.ocrCloudPlatformAdmin.service.impl;
import com.mailu.ocrCloudPlatformAdmin.constant.RedisConstant;
import com.mailu.ocrCloudPlatformAdmin.entity.Court;
import com.mailu.ocrCloudPlatformAdmin.mapper.CourtMapper;
import com.mailu.ocrCloudPlatformAdmin.service.CourtService;
import com.mailu.ocrCloudPlatformAdmin.service.RedisService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
/**
* @author: HuangHao
* @create: 2023-08-18 21:31
* @Description:
*/
@Service
public class CourtServiceImpl implements CourtService {
@Resource
private CourtMapper courtMapper;
@Resource
private RedisService redisService;
@Override
public List<Court> getAll() {
List<Court> courts = courtMapper.selectAll();
return courts;
}
/**
* 获取本院以及下级法院
*
* @param code
* @return
*/
@Override
public List<Court> getByCode(Integer code) {
List<Court> result = new LinkedList<>();
List<Court> courts = courtMapper.selectByCourtCode(code);
getByCode(result, courts, code);
return result;
}
@Override
public void clearCourtInfo(String youxiang) {
String key = RedisConstant.COURT_INFO_USER_PREFIX + youxiang;
redisService.remove(key);
}
@Override
public Court getByCourtCode(Integer courtCode) {
return courtMapper.selectOneByCourtCode(courtCode);
}
//循环获取下级法院
private void getByCode(List<Court> result, List<Court> courts, Integer code) {
if (courts != null && courts.size() > 0) {
for (Court court : courts) {
if (!court.getCourtCode().equals(code)) { //查询下级法院,不查本院
List<Court> courtsList = courtMapper.selectByCourtCode(court.getCourtCode());
getByCode(result, courtsList, court.getCourtCode());
} else {
result.add(court);
}
}
}
}
}
package com.mailu.ocrCloudPlatformAdmin.service.impl;
import com.mailu.ocrCloudPlatformAdmin.service.DoorOrgService;
import org.springframework.stereotype.Service;
@Service
public class DoorOrgServiceImpl implements DoorOrgService {
}
package com.mailu.ocrCloudPlatformAdmin.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mailu.ocrCloudPlatformAdmin.entity.DoorOrg;
import com.mailu.ocrCloudPlatformAdmin.entity.DoorResult;
import com.mailu.ocrCloudPlatformAdmin.entity.DoorUser;
import com.mailu.ocrCloudPlatformAdmin.mapper.DoorOrgMapper;
import com.mailu.ocrCloudPlatformAdmin.mapper.DoorUserMapper;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
import com.mailu.ocrCloudPlatformAdmin.service.DoorUserService;
import com.mailu.ocrCloudPlatformAdmin.utils.DateUtil;
import com.mailu.ocrCloudPlatformAdmin.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;
import java.util.HashMap;
import java.util.List;
@Slf4j
@Service
public class DoorUserServiceImpl implements DoorUserService {
@Autowired
private DoorUserMapper userMapper;
@Autowired
private DoorOrgMapper orgMapper;
@Override
public Result downloadDoorMsg() {
int userCount = userMapper.selectCount();
if (userCount == 0) {
String getAllUserUrl = "http://147.1.6.23/updatelist/getAllUsers";
String s = HttpUtil.sendGetOrDelete(getAllUserUrl, "", new HashMap<>(), HttpUtil.GET);
if (!StringUtils.isEmpty(s)) {
List<DoorUser> doorUsers = JSONArray.parseArray(s, DoorUser.class);
for (DoorUser user : doorUsers) {
try {
String result = HttpUtil.sendGet("http://147.1.6.23/updatelist/getUserInfo/" + user.getYouxiang().replace(" ", "").split("@")[0], "");
user = JSONObject.parseObject(result, DoorUser.class);
if (user != null) {
checkUser(user);
}
} catch (Exception e) {
System.out.println(e);
}
}
} else {
return Result.error("获取门户用户数据为空");
}
}
int orgCount = orgMapper.selectCount();
if (orgCount == 0) {
String getAllOrgUrl = "http://147.1.6.23/updatelist/getAllOrgInfo";
String s = HttpUtil.sendGetOrDelete(getAllOrgUrl, "", new HashMap<>(), HttpUtil.GET);
if (!StringUtils.isEmpty(s)) {
List<DoorOrg> doorUsers = JSONArray.parseArray(s, DoorOrg.class);
for (DoorOrg org : doorUsers) {
checkOrg(org);
}
} else {
return Result.error("获取门户部门数据为空");
}
}
String url = "http://147.1.6.23/updatelist/list/" + DateUtil.getDateStr("yyyyMMddHHmmss");
String s = HttpUtil.sendGetOrDelete(url, "", new HashMap<>(), HttpUtil.GET);
System.out.println(s);
if (!StringUtils.isEmpty(s)) {
List<DoorResult> doorResults = JSONArray.parseArray(s, DoorResult.class);
for (DoorResult result : doorResults) {
switch (result.getLX()) {
case 1://人员标识
updateUser(result);
break;
case 2://部门标识
updateOrg(result);
break;
}
}
} else {
return Result.error("更新门户信息失败");
}
return Result.success("");
}
@Override
public Result downloadDoorUserAll() {
String getAllUserUrl = "http://147.1.6.23/updatelist/getAllUsers";
String s = HttpUtil.sendGetOrDelete(getAllUserUrl, "", new HashMap<>(), HttpUtil.GET);
if (!StringUtils.isEmpty(s)) {
List<DoorUser> doorUsers = JSONArray.parseArray(s, DoorUser.class);
for (DoorUser user : doorUsers) {
try {
String result = HttpUtil.sendGet("http://147.1.6.23/updatelist/getUserInfo/" + user.getYouxiang().replace(" ", "").split("@")[0], "");
user = JSONObject.parseObject(result, DoorUser.class);
if (user != null) {
checkUser(user);
}
} catch (Exception e) {
System.out.println(e);
}
}
return Result.success("");
} else {
return Result.error("获取门户用户数据为空");
}
}
@Override
public Result downloadDoorOrgAll() {
String getAllOrgUrl = "http://147.1.6.23/updatelist/getAllOrgInfo";
String s = HttpUtil.sendGetOrDelete(getAllOrgUrl, "", new HashMap<>(), HttpUtil.GET);
if (!StringUtils.isEmpty(s)) {
List<DoorOrg> doorUsers = JSONArray.parseArray(s, DoorOrg.class);
for (DoorOrg org : doorUsers) {
checkOrg(org);
}
return Result.success("");
} else {
return Result.error("获取门户部门数据为空");
}
}
@Override
public Result updateOrg() {
List<DoorOrg> orgs = orgMapper.selectAll();
for (DoorOrg org : orgs) {
updateOrg(org);
}
return Result.success("");
}
private void updateUser(DoorResult result) {
switch (result.getCZ()) {
case 1://新增
case 2://修改
String url = "http://147.1.6.23/updatelist/getUserInfo/" + result.getBS().split("@")[0];
String s = HttpUtil.sendGetOrDelete(url, "", new HashMap<>(), HttpUtil.GET);
if (s != null) {
DoorUser user = JSONObject.parseObject(s, DoorUser.class);
checkUser(user);
}
break;
}
}
private void updateOrg(DoorResult result) {
switch (result.getCZ()) {
case 1://新增
case 2://修改
String url = "http://147.1.6.23/updatelist/getOrgInfo/" + result.getBS();
String s = HttpUtil.sendGetOrDelete(url, "", new HashMap<>(), HttpUtil.GET);
if (s != null) {
DoorOrg org = JSONObject.parseObject(s, DoorOrg.class);
checkOrg(org);
}
break;
}
}
private void updateOrg(DoorOrg org) {
String url = "http://147.1.6.23/updatelist/getOrgInfo/" + org.getJgbs();
String s = HttpUtil.sendGetOrDelete(url, "", new HashMap<>(), HttpUtil.GET);
if (s != null) {
DoorOrg resultOrg = JSONObject.parseObject(s, DoorOrg.class);
checkOrg(resultOrg);
}
}
private void checkUser(DoorUser user) {
DoorUser dbUser = userMapper.selectByEmail(user.getYouxiang());
if (dbUser != null) {
user.setId(dbUser.getId());
userMapper.updateByPrimaryKeySelective(user);
} else {
userMapper.insertSelective(user);
}
}
private void checkOrg(DoorOrg org) {
DoorOrg dbOrg = orgMapper.selectByJgbs(org.getJgbs());
if (dbOrg != null) {
org.setId(dbOrg.getId());
orgMapper.updateByPrimaryKeySelective(org);
} else {
orgMapper.insertSelective(org);
}
}
@Override
public Result getUserInfoByName(String name) {
try {
if (StringUtils.isEmpty(name)) {
return Result.success("", null);
}
return Result.success("", userMapper.selectByName(name));
} catch (Exception e) {
log.error("通过姓名查询用户信息发生异常!", e);
return Result.error("通过姓名查询用户信息发生异常");
}
}
@Override
public Result updateUser() {
String url = "http://147.1.6.23/updatelist/getUserInfo/hezhuohan";
String s = HttpUtil.sendGetOrDelete(url, "", new HashMap<>(), HttpUtil.GET);
if (s != null) {
DoorUser user = JSONObject.parseObject(s, DoorUser.class);
System.out.println(user);
checkUser(user);
}
return Result.success("");
}
}
package com.mailu.ocrCloudPlatformAdmin.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mailu.ocrCloudPlatformAdmin.dto.Page;
import com.mailu.ocrCloudPlatformAdmin.entity.Menu;
import com.mailu.ocrCloudPlatformAdmin.entity.MenuRole;
import com.mailu.ocrCloudPlatformAdmin.entity.Role;
import com.mailu.ocrCloudPlatformAdmin.mapper.MenuMapper;
import com.mailu.ocrCloudPlatformAdmin.mapper.MenuRoleMapper;
import com.mailu.ocrCloudPlatformAdmin.mapper.RoleMapper;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
import com.mailu.ocrCloudPlatformAdmin.service.MenuRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MenuRoleServiceImpl implements MenuRoleService {
@Autowired
private MenuRoleMapper menuRoleMapper;
@Autowired
private MenuMapper menuMapper;
@Autowired
private RoleMapper roleMapper;
/**
* 根据id删除
* @param id
* @return
*/
@Override
public Result deleteByPrimaryKey(Integer id) {
MenuRole menuRole = selectByPrimaryKey(id);
if(menuRole != null){
int res = menuRoleMapper.deleteByPrimaryKey(id);
if (res > 0) {
return Result.success("删除成功", menuRoleMapper.deleteByPrimaryKey(id));
}else {
return Result.error("删除失败");
}
}else {
return Result.error("菜单角色不存在");
}
}
/**
* 新增
* @param menuRole
* @return
*/
@Override
public int insert(MenuRole menuRole) {
return menuRoleMapper.insert(menuRole);
}
@Override
public Result insertSelective(MenuRole menuRole) {
System.out.println(menuRole);
int menuId = menuRole.getMenuId();
Menu menu = menuMapper.selectByPrimaryKey(menuId);
if(menu == null){
return Result.error("菜单不存在");
}
int roleId = menuRole.getRoleId();
Role role = roleMapper.selectByPrimaryKey(roleId);
if(role == null){
return Result.error("角色不存在");
}
return Result.success("成功", menuRoleMapper.insertSelective(menuRole));
}
@Override
public MenuRole selectByPrimaryKey(Integer id) {
return menuRoleMapper.selectByPrimaryKey(id);
}
/**
* 修改
* @param menuRole
* @return
*/
@Override
public Result updateByPrimaryKeySelective(MenuRole menuRole) {
Integer id = menuRole.getId();
if(id != null) {
MenuRole menuRole_id = menuRoleMapper.selectByPrimaryKey(id);
if (menuRole_id == null) {
return Result.error("菜单角色不存在!");
}
int menuId = menuRole_id.getMenuId();
Menu menu = menuMapper.selectByPrimaryKey(menuId);
if (menu == null) {
return Result.error("菜单不存在");
}
int roleId = menuRole_id.getRoleId();
Role role = roleMapper.selectByPrimaryKey(roleId);
if (role == null) {
return Result.error("角色不存在");
}
System.out.println(menuRole);
return Result.success("成功", menuRoleMapper.updateByPrimaryKeySelective(menuRole));
}else{
return Result.error("菜单角色不存在");
}
}
@Override
public int updateByPrimaryKey(MenuRole menuRole) {
return menuRoleMapper.updateByPrimaryKey(menuRole);
}
/**
* 获取列表
* @param page
* @return
*/
@Override
public Result selectAll(Page page) {
PageHelper.startPage(page.getPage(),page.getLimit());
List<MenuRole> roles = menuRoleMapper.selectAll(page.getSearchStr());
PageInfo pageInfo = new PageInfo(roles);
System.out.println(roles.toString());
return Result.success("获取菜单角色管理列表成功",pageInfo.getTotal(),pageInfo.getList());
}
/**
* 根据菜单ID删除菜单角色
* @param id 菜单ID
* @return
*/
@Override
public int deleteByMenuId(Integer id){
return menuRoleMapper.deleteByMenuId(id);
}
/**
* 根据角色ID删除菜单角色
* @param id 角色ID
* @return
*/
@Override
public int deleteByRoleId(Integer id){
return menuRoleMapper.deleteByRoleId(id);
}
}
package com.mailu.ocrCloudPlatformAdmin.service.impl;
import com.github.pagehelper.PageInfo;
import com.mailu.ocrCloudPlatformAdmin.dto.MenuDto;
import com.mailu.ocrCloudPlatformAdmin.entity.Menu;
import com.mailu.ocrCloudPlatformAdmin.mapper.MenuMapper;
import com.mailu.ocrCloudPlatformAdmin.mapper.MenuRoleMapper;
import com.mailu.ocrCloudPlatformAdmin.mapper.RoleMapper;
import com.mailu.ocrCloudPlatformAdmin.response.Result;
import com.mailu.ocrCloudPlatformAdmin.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
@Service("menuService")
public class MenuServiceImpl implements MenuService {
@Autowired
private MenuMapper menuMapper;
@Autowired
private MenuRoleMapper menuRoleMapper;
@Autowired
private RoleMapper roleMapper;
public List<Menu> getAllMenu() {
return menuMapper.getAllMenusWithRole();
}
@Override
public Result getList() {
List<Menu> menus = menuMapper.selectAll();
System.out.println("menus:" + menus);
List<Menu> list = new ArrayList<>();
subordinate(menus, list);
List resultList = new ArrayList();
// Page page = new Page();
// int pageSize = 10;
// page.setCount(true);
// page.setPageNum(1);
// page.setPageSize(pageSize);
// page.setStartRow(0);
// page.setEndRow(10);
// page.setTotal(list.size());
// if(list.size()%pageSize == 0){
// page.setPages(list.size()/pageSize);
// }else {
// page.setPages(list.size()/pageSize + 1);
// }
// page.setReasonable(true);
// page.setPageSizeZero(true);
// resultList.add(page);
// resultList.add(list);
PageInfo pageInfo = new PageInfo(resultList);
System.out.println(resultList);
return Result.success("成功", pageInfo.getTotal(), pageInfo.getList());
}
@Override
public List<Menu> selectList(Integer id) {
return menuMapper.selectList(id);
}
/**
* 删除
*
* @param id
* @return
*/
@Override
public Result deleteByPrimaryKey(Integer id) {
Menu menu = selectByPrimaryKey(id);
if (menu != null) {
List<Menu> menus = menuMapper.selectByParentId(menu.getId(),-1);
delSon(menus);
menuRoleMapper.deleteByMenuId(menu.getId());
int res = menuMapper.deleteByPrimaryKey(id);
if (res > 0) {
return Result.success("删除成功");
} else {
return Result.error("删除失败");
}
} else {
return Result.error("ID为:[" + id + "] 不存在,可能已经被删除");
}
}
/**
* 根据id查找
*
* @param id
* @return
*/
@Override
public Menu selectByPrimaryKey(Integer id) {
return menuMapper.selectByPrimaryKey(id);
}
/**
* 新增
*
* @param record
* @return
*/
@Override
public Result insertSelective(Menu record) {
System.out.println(record.toString());
return Result.success("成功", menuMapper.insertSelective(record));
}
/**
* 修改
*
* @param record
* @return
*/
@Override
public Result updateByPrimaryKeySelective(Menu record) {
int id = record.getId();
Menu menu = selectByPrimaryKey(id);
if (menu != null) {
int res = menuMapper.updateByPrimaryKeySelective(record);
if (res > 0) {
return Result.success("修改成功");
} else {
return Result.error("修改失败");
}
} else {
return Result.error("ID为:[" + id + "] 不存在,可能已经被删除");
}
}
/**
* 根据父级ID获取数据
*
* @param id
* @return
*/
@Override
public List<Menu> selectByParentId(Integer id,Integer id_) {
return menuMapper.selectByParentId(id,id_);
}
/**
* 根据角色ID获取菜单
*
* @param id
* @return
*/
@Override
public List<Menu> selectRoleId(Integer id) {
return menuMapper.selectRoleId(id);
}
@Override
@Transactional
public Result getAll(MenuDto dto) {
// PageHelper.startPage(dto.getPage(), dto.getLimit());
List<Menu> menus = menuMapper.getAll(dto);
// PageInfo pageInfo = new PageInfo(menus);
if (menus != null && menus.size()>0){
return Result.success("获取菜单列表成功", menus);
}else {
return Result.error("获取菜单列表失败", null);
}
}
@Override
public List<Menu> getMenus(Integer roleId) {
return selectRoleId(roleId);
}
public void subordinate(List<Menu> menus, List<Menu> list){
for (Menu menu : menus) {
List<Menu> list1 = selectByParentId(menu.getId(),-1);
list.add(menu);
subordinate(list1, list);
}
}
public void delSon(List<Menu> list) {
for (Menu menu : list) {
List<Menu> menus = menuMapper.selectByParentId(menu.getId(),-1);
menuRoleMapper.deleteByMenuId(menu.getId());
menuMapper.deleteById(menu.getId());
delSon(menus);
}
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment