同步器增加属性映射管理

This commit is contained in:
llh
2024-09-24 18:38:15 +08:00
711 changed files with 17528 additions and 5084 deletions
@@ -1,194 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.autoconfigure;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.dromara.maxkey.constants.ConstsPersistence;
import org.dromara.maxkey.crypto.keystore.KeyStoreLoader;
import org.dromara.maxkey.crypto.password.LdapShaPasswordEncoder;
import org.dromara.maxkey.crypto.password.Md4PasswordEncoder;
import org.dromara.maxkey.crypto.password.MessageDigestPasswordEncoder;
import org.dromara.maxkey.crypto.password.NoOpPasswordEncoder;
import org.dromara.maxkey.crypto.password.PasswordReciprocal;
import org.dromara.maxkey.crypto.password.SM3PasswordEncoder;
import org.dromara.maxkey.crypto.password.StandardPasswordEncoder;
import org.dromara.maxkey.persistence.cache.InMemoryMomentaryService;
import org.dromara.maxkey.persistence.cache.MomentaryService;
import org.dromara.maxkey.persistence.cache.RedisMomentaryService;
import org.dromara.maxkey.persistence.redis.RedisConnectionFactory;
import org.dromara.maxkey.persistence.repository.InstitutionsRepository;
import org.dromara.maxkey.persistence.repository.LocalizationRepository;
import org.dromara.maxkey.util.IdGenerator;
import org.dromara.maxkey.util.SnowFlakeId;
import org.dromara.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
@AutoConfiguration
public class ApplicationAutoConfiguration {
static final Logger _logger = LoggerFactory.getLogger(ApplicationAutoConfiguration.class);
@Bean
public PasswordReciprocal passwordReciprocal() {
return new PasswordReciprocal();
}
@Bean
public DataSourceTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
public InstitutionsRepository institutionsRepository(JdbcTemplate jdbcTemplate) {
return new InstitutionsRepository(jdbcTemplate);
}
@Bean
public LocalizationRepository localizationRepository(JdbcTemplate jdbcTemplate,
InstitutionsRepository institutionsRepository) {
return new LocalizationRepository(jdbcTemplate,institutionsRepository);
}
/**
* Authentication Password Encoder .
* @return
*/
@Bean
public PasswordEncoder passwordEncoder(
@Value("${maxkey.crypto.password.encoder:bcrypt}") String idForEncode) {
Map<String ,PasswordEncoder > encoders = new HashMap<>();
encoders.put("bcrypt", new BCryptPasswordEncoder());
encoders.put("plain", NoOpPasswordEncoder.getInstance());
encoders.put("pbkdf2", Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8());
encoders.put("scrypt", SCryptPasswordEncoder.defaultsForSpringSecurity_v5_8());
//md
encoders.put("md4", new Md4PasswordEncoder());
encoders.put("md5", new MessageDigestPasswordEncoder("MD5"));
//sha
encoders.put("sha1", new StandardPasswordEncoder("SHA-1",""));
encoders.put("sha256", new StandardPasswordEncoder());
encoders.put("sha384", new StandardPasswordEncoder("SHA-384",""));
encoders.put("sha512", new StandardPasswordEncoder("SHA-512",""));
encoders.put("sm3", new SM3PasswordEncoder());
encoders.put("ldap", new LdapShaPasswordEncoder());
//idForEncode is default for encoder
PasswordEncoder passwordEncoder =
new DelegatingPasswordEncoder(idForEncode, encoders);
if(_logger.isTraceEnabled()) {
_logger.trace("Password Encoders :");
for (Map.Entry<String,PasswordEncoder> entry : encoders.entrySet()) {
_logger.trace("{}= {}" ,String.format("%-10s", entry.getKey()), entry.getValue().getClass().getName());
}
}
_logger.debug("{} is default encoder" , idForEncode);
return passwordEncoder;
}
/**
* keyStoreLoader .
* @return
*/
@Bean
public KeyStoreLoader keyStoreLoader(
@Value("${maxkey.saml.v20.idp.issuing.entity.id}") String entityName,
@Value("${maxkey.saml.v20.idp.keystore.password}") String keystorePassword,
@Value("${maxkey.saml.v20.idp.keystore}") Resource keystoreFile) {
KeyStoreLoader keyStoreLoader = new KeyStoreLoader();
keyStoreLoader.setEntityName(entityName);
keyStoreLoader.setKeystorePassword(keystorePassword);
keyStoreLoader.setKeystoreFile(keystoreFile);
return keyStoreLoader;
}
/**
* spKeyStoreLoader .
* @return
*/
@Bean
public KeyStoreLoader serviceProviderKeyStoreLoader(
@Value("${maxkey.saml.v20.sp.issuing.entity.id}") String entityName,
@Value("${maxkey.saml.v20.sp.keystore.password}") String keystorePassword,
@Value("${maxkey.saml.v20.sp.keystore}") Resource keystoreFile) {
KeyStoreLoader keyStoreLoader = new KeyStoreLoader();
keyStoreLoader.setEntityName(entityName);
keyStoreLoader.setKeystorePassword(keystorePassword);
keyStoreLoader.setKeystoreFile(keystoreFile);
return keyStoreLoader;
}
/**
* spKeyStoreLoader .
* @return
*/
@Bean
public String spIssuingEntityName(
@Value("${maxkey.saml.v20.sp.issuing.entity.id}") String spIssuingEntityName) {
return spIssuingEntityName;
}
/**
* Id Generator .
* @return
*/
@Bean
public IdGenerator idGenerator(
@Value("${maxkey.id.strategy:SnowFlake}") String strategy,
@Value("${maxkey.id.datacenterId:0}") int datacenterId,
@Value("${maxkey.id.machineId:0}") int machineId) {
IdGenerator idGenerator = new IdGenerator(strategy);
SnowFlakeId snowFlakeId = new SnowFlakeId(datacenterId,machineId);
idGenerator.setSnowFlakeId(snowFlakeId);
WebContext.setIdGenerator(idGenerator);
return idGenerator;
}
@Bean
public MomentaryService momentaryService(
RedisConnectionFactory redisConnFactory,
@Value("${maxkey.server.persistence}") int persistence) {
MomentaryService momentaryService;
if (persistence == ConstsPersistence.REDIS) {
momentaryService = new RedisMomentaryService(redisConnFactory);
}else {
momentaryService = new InMemoryMomentaryService();
}
return momentaryService;
}
}
@@ -1,313 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.autoconfigure;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.dromara.maxkey.configuration.ApplicationConfig;
import org.dromara.maxkey.persistence.repository.InstitutionsRepository;
import org.dromara.maxkey.web.WebInstRequestFilter;
import org.dromara.maxkey.web.WebXssRequestFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.endpoint.ApiVersion;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.Filter;
@AutoConfiguration
public class MvcAutoConfiguration implements WebMvcConfigurer {
static final Logger _logger = LoggerFactory.getLogger(MvcAutoConfiguration.class);
@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
private String pattern;
/**
* 消息处理,可以直接使用properties的key值,返回的是对应的value值
* messageSource .
* @return messageSource
*/
@Bean (name = "messageSource")
public ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource(
@Value("${spring.messages.basename:classpath:messages/message}")
String messagesBasename) {
_logger.debug("Basename {}" , messagesBasename);
String passwordPolicyMessagesBasename="classpath:messages/passwordpolicy_message";
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames(messagesBasename,passwordPolicyMessagesBasename);
messageSource.setUseCodeAsDefaultMessage(false);
return messageSource;
}
/**
* Locale Change Interceptor and Resolver definition .
* @return localeChangeInterceptor
*/
//@Primary
@Bean (name = "localeChangeInterceptor")
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("language");
return localeChangeInterceptor;
}
/**
* handlerMapping .
* @return handlerMapping
*/
@Bean (name = "handlerMapping")
public RequestMappingHandlerMapping requestMappingHandlerMapping(
LocaleChangeInterceptor localeChangeInterceptor) {
RequestMappingHandlerMapping requestMappingHandlerMapping = new RequestMappingHandlerMapping();
requestMappingHandlerMapping.setInterceptors(localeChangeInterceptor);
return requestMappingHandlerMapping;
}
/**
* jaxb2Marshaller .
* @return jaxb2Marshaller
*/
@Bean (name = "jaxb2Marshaller")
public Jaxb2Marshaller jaxb2Marshaller() {
Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setClassesToBeBound(org.dromara.maxkey.entity.xml.UserInfoXML.class);;
return jaxb2Marshaller;
}
/**
* marshallingHttpMessageConverter .
* @return marshallingHttpMessageConverter
*/
@Bean (name = "marshallingHttpMessageConverter")
public MarshallingHttpMessageConverter marshallingHttpMessageConverter(
Jaxb2Marshaller jaxb2Marshaller) {
MarshallingHttpMessageConverter marshallingHttpMessageConverter = new MarshallingHttpMessageConverter();
marshallingHttpMessageConverter.setMarshaller(jaxb2Marshaller);
marshallingHttpMessageConverter.setUnmarshaller(jaxb2Marshaller);
ArrayList<MediaType> mediaTypesList = new ArrayList<>();
mediaTypesList.add(MediaType.APPLICATION_XML);
mediaTypesList.add(MediaType.TEXT_XML);
mediaTypesList.add(MediaType.TEXT_PLAIN);
_logger.debug("marshallingHttpMessageConverter MediaTypes {}" , mediaTypesList);
marshallingHttpMessageConverter.setSupportedMediaTypes(mediaTypesList);
return marshallingHttpMessageConverter;
}
/**
* mappingJacksonHttpMessageConverter .
* @return mappingJacksonHttpMessageConverter
*/
@Bean (name = "mappingJacksonHttpMessageConverter")
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
ArrayList<MediaType> mediaTypesList = new ArrayList<>();
mediaTypesList.add(MediaType.APPLICATION_JSON);
mediaTypesList.add(MediaType.valueOf(ApiVersion.V2.getProducedMimeType().toString()));
mediaTypesList.add(MediaType.valueOf(ApiVersion.V3.getProducedMimeType().toString()));
//mediaTypesList.add(MediaType.TEXT_PLAIN);
_logger.debug("mappingJacksonHttpMessageConverter MediaTypes {}" , mediaTypesList);
mappingJacksonHttpMessageConverter.setSupportedMediaTypes(mediaTypesList);
ObjectMapper objectMapper = mappingJacksonHttpMessageConverter.getObjectMapper();
// 时间格式化
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
_logger.debug("DateFormat {}" , pattern);
objectMapper.setDateFormat(new SimpleDateFormat(pattern));
// 设置格式化内容
mappingJacksonHttpMessageConverter.setObjectMapper(objectMapper);
return mappingJacksonHttpMessageConverter;
}
/**
* cookieLocaleResolver .
* @return cookieLocaleResolver
*/
@Bean(name = "cookieLocaleResolver")
public LocaleResolver cookieLocaleResolver(
@Value("${maxkey.server.domain:maxkey.top}")
String domainName
) {
_logger.debug("DomainName {}" , domainName);
CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver("mxk_locale");
cookieLocaleResolver.setCookieDomain(domainName);
cookieLocaleResolver.setCookieMaxAge(Duration.ofDays(14));
return cookieLocaleResolver;
}
/**
* AnnotationMethodHandlerAdapter
* requestMappingHandlerAdapter .
* @return requestMappingHandlerAdapter
*/
@Bean (name = "addConverterRequestMappingHandlerAdapter")
public RequestMappingHandlerAdapter requestMappingHandlerAdapter(
@Qualifier("mappingJacksonHttpMessageConverter")
MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter,
MarshallingHttpMessageConverter marshallingHttpMessageConverter,
StringHttpMessageConverter stringHttpMessageConverter,
RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
List<HttpMessageConverter<?>> httpMessageConverterList = new ArrayList<>();
//需要追加byte,否则springdoc-openapi接口会响应Base64编码内容,导致接口文档显示失败
// https://github.com/springdoc/springdoc-openapi/issues/2143
// 解决方案
httpMessageConverterList.add(new ByteArrayHttpMessageConverter());
httpMessageConverterList.add(mappingJacksonHttpMessageConverter);
httpMessageConverterList.add(marshallingHttpMessageConverter);
httpMessageConverterList.add(stringHttpMessageConverter);
_logger.debug("stringHttpMessageConverter {}",stringHttpMessageConverter.getDefaultCharset());
requestMappingHandlerAdapter.setMessageConverters(httpMessageConverterList);
return requestMappingHandlerAdapter;
}
/**
* restTemplate .
* @return restTemplate
*/
@Bean (name = "restTemplate")
public RestTemplate restTemplate(
@Qualifier("mappingJacksonHttpMessageConverter")
MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter,
MarshallingHttpMessageConverter marshallingHttpMessageConverter) {
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> httpMessageConverterList = new ArrayList<>();
httpMessageConverterList.add(mappingJacksonHttpMessageConverter);
httpMessageConverterList.add(marshallingHttpMessageConverter);
restTemplate.setMessageConverters(httpMessageConverterList);
return restTemplate;
}
/**
* 配置默认错误页面(仅用于内嵌tomcat启动时) 使用这种方式,在打包为war后不起作用.
*
* @return webServerFactoryCustomizer
*/
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
@Override
public void customize(ConfigurableWebServerFactory factory) {
_logger.debug("WebServerFactoryCustomizer ... ");
ErrorPage errorPage400 =
new ErrorPage(HttpStatus.BAD_REQUEST, "/exception/error/400");
ErrorPage errorPage404 =
new ErrorPage(HttpStatus.NOT_FOUND, "/exception/error/404");
ErrorPage errorPage500 =
new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/exception/error/500");
factory.addErrorPages(errorPage400, errorPage404, errorPage500);
}
};
}
@Bean
public SecurityContextHolderAwareRequestFilter securityContextHolderAwareRequestFilter() {
_logger.debug("securityContextHolderAwareRequestFilter init ");
return new SecurityContextHolderAwareRequestFilter();
}
@Bean
public FilterRegistrationBean<CorsFilter> corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedOriginPatterns(Collections.singletonList(CorsConfiguration.ALL));
corsConfiguration.addAllowedHeader(CorsConfiguration.ALL);
corsConfiguration.addAllowedMethod(CorsConfiguration.ALL);
source.registerCorsConfiguration("/**", corsConfiguration);
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>();
bean.setOrder(1);
bean.setFilter(new CorsFilter(source));
bean.addUrlPatterns("/*");
return bean;
}
@Bean
public FilterRegistrationBean<Filter> delegatingFilterProxy() {
_logger.debug("delegatingFilterProxy init for /* ");
FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new DelegatingFilterProxy("securityContextHolderAwareRequestFilter"));
registrationBean.addUrlPatterns("/*");
//registrationBean.
registrationBean.setName("delegatingFilterProxy");
registrationBean.setOrder(2);
return registrationBean;
}
@Bean
public FilterRegistrationBean<Filter> webXssRequestFilter() {
_logger.debug("webXssRequestFilter init for /* ");
FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>(new WebXssRequestFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setName("webXssRequestFilter");
registrationBean.setOrder(3);
return registrationBean;
}
@Bean
public FilterRegistrationBean<Filter> webInstRequestFilter(
InstitutionsRepository institutionsRepository,
ApplicationConfig applicationConfig) {
_logger.debug("WebInstRequestFilter init for /* ");
FilterRegistrationBean<Filter> registrationBean =
new FilterRegistrationBean<>(new WebInstRequestFilter(institutionsRepository,applicationConfig));
registrationBean.addUrlPatterns("/*");
registrationBean.setName("webInstRequestFilter");
registrationBean.setOrder(4);
return registrationBean;
}
}
@@ -1,57 +0,0 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.autoconfigure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@EnableWebMvc
@AutoConfiguration
public class MvcResourceAutoConfiguration implements WebMvcConfigurer {
private static final Logger logger = LoggerFactory.getLogger(MvcResourceAutoConfiguration.class);
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
logger.debug("add Resource Handlers");
logger.debug("add statics");
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
logger.debug("add templates");
registry.addResourceHandler("/templates/**")
.addResourceLocations("classpath:/templates/");
logger.debug("add swagger");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
logger.debug("add knife4j");
registry.addResourceHandler("doc.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
logger.debug("add Resource Handler finished .");
}
}
@@ -1,80 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.autoconfigure;
import org.dromara.maxkey.persistence.redis.RedisConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import redis.clients.jedis.JedisPoolConfig;
@AutoConfiguration
public class RedisAutoConfiguration {
static final Logger _logger = LoggerFactory.getLogger(RedisAutoConfiguration.class);
/**
* RedisConnectionFactory.
* @param host String
* @param port int
* @param timeout int
* @param password String
* @param maxActive int
* @param maxWait int
* @param maxIdle int
* @param minIdle int
* @return RedisConnectionFactory
*/
@Bean
public RedisConnectionFactory redisConnFactory(
@Value("${spring.redis.host}")
String host,
@Value("${spring.redis.port:6379}")
int port,
@Value("${spring.redis.timeout:10000}")
int timeout,
@Value("${spring.redis.password}")
String password,
@Value("${spring.redis.lettuce.pool.max-active:-1}")
int maxActive,
@Value("${spring.redis.jedis.pool.max-wait:1000}")
int maxWait,
@Value("${spring.redis.jedis.pool.max-idle:100}")
int maxIdle,
@Value("${spring.redis.lettuce.pool.min-idle:0}")
int minIdle) {
_logger.debug("redisConnFactory init .");
RedisConnectionFactory factory = new RedisConnectionFactory();
factory.setHostName(host);
factory.setPort(port);
factory.setTimeOut(timeout);
factory.setPassword(password);
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minIdle);
poolConfig.setMaxTotal(maxActive);
poolConfig.setMaxWaitMillis(maxWait);
factory.setPoolConfig(poolConfig);
return factory;
}
}
@@ -1,95 +0,0 @@
package org.dromara.maxkey.autoconfigure;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
@AutoConfiguration
public class SwaggerAutoConfiguration {
static final Logger _logger = LoggerFactory.getLogger(SwaggerAutoConfiguration.class);
@Value("${maxkey.swagger.title}")
String title;
@Value("${maxkey.swagger.description}")
String description;
@Value("${maxkey.swagger.version}")
String version;
@Value("${maxkey.swagger.enable}")
boolean enable;
@Bean
public GlobalOpenApiCustomizer orderGlobalOpenApiCustomizer() {
return openApi -> {
if (openApi.getTags()!=null){
openApi.getTags().forEach(tag -> {
Map<String,Object> map=new HashMap<>();
map.put("x-order",1);
tag.setExtensions(map);
});
}
if(openApi.getPaths()!=null){
openApi.addExtension("x-test123","333");
openApi.getPaths().addExtension("x-abb",1);
}
};
}
@Bean
public GroupedOpenApi userApi(){
String[] paths = {
"/login",
"/logout",
"/login/**",
"/logout/**",
"/authz/**",
"/authz/**/**",
"/metadata/saml20/**" ,
"/onlineticket/validate/**",
"/api/connect/v10/userinfo",
"/api/oauth/v20/me"
};
String[] packagedToMatch = { "org.dromara.maxkey.authz" };
return GroupedOpenApi.builder().group(title)
.pathsToMatch(paths)
.packagesToScan(packagedToMatch).build();
}
@Bean
public OpenAPI docOpenAPI() {
return new OpenAPI()
.info(
new Info()
.title(title)
.description(description)
.version(version)
.termsOfService("https://www.maxkey.top/")
.license(
new License()
.name("Apache License, Version 2.0")
.url("http://www.apache.org/licenses/LICENSE-2.0")
)
).
externalDocs(
new ExternalDocumentation()
.description("MaxKey.top contact support@maxsso.net")
.url("https://www.maxkey.top/")
);
}
}
@@ -17,7 +17,6 @@
package org.dromara.maxkey.configuration;
import org.apache.commons.lang3.StringUtils;
import org.dromara.maxkey.constants.ConstsDatabase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@@ -28,8 +28,8 @@ import jakarta.persistence.Table;
import org.dromara.maxkey.entity.apps.Apps;
@Entity
@Table(name = "mxk_group_permissions")
public class GroupPermissions extends Apps implements Serializable{
@Table(name = "mxk_access")
public class Access extends Apps implements Serializable{
/**
*
@@ -54,7 +54,7 @@ public class GroupPermissions extends Apps implements Serializable{
private String instName;
public GroupPermissions(){
public Access(){
super();
}
@@ -63,7 +63,7 @@ public class GroupPermissions extends Apps implements Serializable{
* @param groupId
* @param appId
*/
public GroupPermissions(String groupId, String appId, String instId) {
public Access(String groupId, String appId, String instId) {
super();
this.groupId = groupId;
this.appId = appId;
@@ -150,7 +150,7 @@ public class GroupPermissions extends Apps implements Serializable{
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("GroupPermissions [id=");
builder.append("Access [id=");
builder.append(id);
builder.append(", groupId=");
builder.append(groupId);
@@ -21,6 +21,7 @@ import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.mybatis.jpa.entity.JpaEntity;
import org.hibernate.validator.constraints.Length;
@@ -19,6 +19,7 @@ package org.dromara.maxkey.entity;
import java.util.Date;
import org.dromara.maxkey.entity.idm.UserInfo;
import org.dromara.mybatis.jpa.entity.JpaEntity;
public class ChangePassword extends JpaEntity{
@@ -34,8 +34,7 @@ import jakarta.persistence.Table;
@Entity
@Table(name = "MXK_FILE_UPLOAD")
public class FileUpload extends JpaEntity {
private static final long serialVersionUID = -4338400992411166457L;
@Id
@Column
@GeneratedValue
@@ -77,9 +77,6 @@ public class Institutions extends JpaEntity implements Serializable {
@Column
private String consoleTitle;
@Column
private String captcha;
@Column
private String defaultUri;
@@ -249,15 +246,6 @@ public class Institutions extends JpaEntity implements Serializable {
this.description = description;
}
public String getCaptcha() {
return captcha;
}
public void setCaptcha(String captcha) {
this.captcha = captcha;
}
public String getDefaultUri() {
return defaultUri;
}
@@ -309,8 +297,6 @@ public class Institutions extends JpaEntity implements Serializable {
builder.append(consoleDomain);
builder.append(", consoleTitle=");
builder.append(consoleTitle);
builder.append(", captcha=");
builder.append(captcha);
builder.append(", defaultUri=");
builder.append(defaultUri);
builder.append("]");
@@ -1,142 +0,0 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.entity;
import java.io.Serializable;
import org.dromara.mybatis.jpa.entity.JpaEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "MXK_LOCALIZATION")
public class Localization extends JpaEntity implements Serializable {
/**
*
*/
private static final long serialVersionUID = -142504964446659847L;
@Id
@Column
@GeneratedValue
private String id;
@Column
private String property;
@Column
private String langZh;
@Column
private String langEn;
@Column
private String description;
@Column
private int status;
@Column
private String instId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public String getLangZh() {
return langZh;
}
public void setLangZh(String langZh) {
this.langZh = langZh;
}
public String getLangEn() {
return langEn;
}
public void setLangEn(String langEn) {
this.langEn = langEn;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getInstId() {
return instId;
}
public void setInstId(String instId) {
this.instId = instId;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Localization [id=");
builder.append(id);
builder.append(", property=");
builder.append(property);
builder.append(", langZh=");
builder.append(langZh);
builder.append(", langEn=");
builder.append(langEn);
builder.append(", description=");
builder.append(description);
builder.append(", status=");
builder.append(status);
builder.append(", instId=");
builder.append(instId);
builder.append("]");
return builder.toString();
}
}
@@ -20,12 +20,6 @@ package org.dromara.maxkey.entity;
import java.io.Serializable;
import org.dromara.mybatis.jpa.entity.JpaEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
/**
* Saml20Metadata.
* @author Crystal.Sea
@@ -15,7 +15,7 @@
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.cnf;
@@ -31,8 +31,8 @@ import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "MXK_EMAIL_SENDERS")
public class EmailSenders extends JpaEntity implements Serializable {
@Table(name = "MXK_CNF_EMAIL_SENDERS")
public class CnfEmailSenders extends JpaEntity implements Serializable {
/**
*
@@ -91,7 +91,7 @@ public class EmailSenders extends JpaEntity implements Serializable {
@Column
private Date modifiedDate;
public EmailSenders() {
public CnfEmailSenders() {
super();
}
@@ -15,7 +15,7 @@
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.cnf;
import java.io.Serializable;
import java.util.Date;
@@ -29,8 +29,8 @@ import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "MXK_LDAP_CONTEXT")
public class LdapContext extends JpaEntity implements Serializable {
@Table(name = "MXK_CNF_LDAP_CONTEXT")
public class CnfLdapContext extends JpaEntity implements Serializable {
/**
@@ -81,7 +81,7 @@ public class LdapContext extends JpaEntity implements Serializable {
private String instName;
public LdapContext() {
public CnfLdapContext() {
}
public String getId() {
@@ -15,7 +15,7 @@
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.cnf;
import org.dromara.mybatis.jpa.entity.JpaEntity;
@@ -39,8 +39,8 @@ import java.util.List;
*/
@Entity
@Table(name = "MXK_PASSWORD_POLICY")
public class PasswordPolicy extends JpaEntity implements java.io.Serializable {
@Table(name = "MXK_CNF_PASSWORD_POLICY")
public class CnfPasswordPolicy extends JpaEntity implements java.io.Serializable {
private static final long serialVersionUID = -4797776994287829182L;
@Id
@@ -15,7 +15,7 @@
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.cnf;
import java.io.Serializable;
import java.util.Date;
@@ -29,8 +29,8 @@ import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "MXK_SMS_PROVIDER")
public class SmsProvider extends JpaEntity implements Serializable {
@Table(name = "MXK_CNF_SMS_PROVIDER")
public class CnfSmsProvider extends JpaEntity implements Serializable {
/**
@@ -75,7 +75,7 @@ public class SmsProvider extends JpaEntity implements Serializable {
private String instName;
public SmsProvider() {
public CnfSmsProvider() {
}
public String getId() {
@@ -0,0 +1,22 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.entity.dto;
public record TimeBasedDto(String displayName,String username,int digits,int period,String sharedSecret,String qrCode,String otpCode) {
}
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.history;
import java.io.Serializable;
import java.util.Date;
@@ -15,7 +15,7 @@
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.history;
import java.io.Serializable;
import java.util.Date;
@@ -15,7 +15,7 @@
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.history;
import java.io.Serializable;
import java.util.Date;
@@ -15,7 +15,7 @@
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.history;
import java.io.Serializable;
import java.util.Date;
@@ -15,7 +15,7 @@
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.history;
import java.io.Serializable;
import java.util.Date;
@@ -15,7 +15,7 @@
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.idm;
import java.io.Serializable;
@@ -15,7 +15,7 @@
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.idm;
import java.io.Serializable;
import java.util.Date;
@@ -65,10 +65,6 @@ public class Groups extends JpaEntity implements Serializable {
@Column
String orgIdsList;
@Column
String resumeTime;
@Column
String suspendTime;
@Column
int isdefault;
@@ -228,22 +224,6 @@ public class Groups extends JpaEntity implements Serializable {
this.orgIdsList = orgIdsList;
}
public String getResumeTime() {
return resumeTime;
}
public void setResumeTime(String resumeTime) {
this.resumeTime = resumeTime;
}
public String getSuspendTime() {
return suspendTime;
}
public void setSuspendTime(String suspendTime) {
this.suspendTime = suspendTime;
}
public String getInstId() {
return instId;
}
@@ -275,10 +255,6 @@ public class Groups extends JpaEntity implements Serializable {
builder.append(filters);
builder.append(", orgIdsList=");
builder.append(orgIdsList);
builder.append(", resumeTime=");
builder.append(resumeTime);
builder.append(", suspendTime=");
builder.append(suspendTime);
builder.append(", isdefault=");
builder.append(isdefault);
builder.append(", description=");
@@ -15,7 +15,7 @@
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.idm;
import java.io.Serializable;
import java.util.Date;
@@ -15,7 +15,7 @@
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.idm;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -31,8 +31,9 @@ import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import org.apache.commons.lang3.StringUtils;
import org.dromara.maxkey.crypto.Base64Utils;
import org.dromara.maxkey.util.StringUtils;
/**
* .
@@ -173,10 +174,12 @@ public class UserInfo extends JpaEntity implements Serializable {
// for work
@Column
protected String workCountry;
// province
@Column
protected String workRegion;// province;
protected String workRegion;
// city
@Column
protected String workLocality;// city;
protected String workLocality;
@Column
protected String workStreetAddress;
@Column
@@ -194,10 +197,12 @@ public class UserInfo extends JpaEntity implements Serializable {
// for home
@Column
protected String homeCountry;
// province
@Column
protected String homeRegion;// province;
protected String homeRegion;
// city
@Column
protected String homeLocality;// city;
protected String homeLocality;
@Column
protected String homeStreetAddress;
@Column
@@ -441,7 +446,7 @@ public class UserInfo extends JpaEntity implements Serializable {
*/
public HashMap<String, String> getProtectedAppsMap() {
if (protectedAppsMap == null) {
protectedAppsMap = new HashMap<String, String>();
protectedAppsMap = new HashMap<>();
}
if (StringUtils.isNotEmpty(protectedApps)) {
String[] apps = protectedApps.split(",");
@@ -15,7 +15,7 @@
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.permissions;
import java.io.Serializable;
import org.dromara.mybatis.jpa.entity.JpaEntity;
@@ -29,8 +29,8 @@ import org.dromara.maxkey.constants.ConstsStatus;
import org.dromara.maxkey.web.WebContext;
@Entity
@Table(name = "MXK_GROUP_PRIVILEGES")
public class GroupPrivileges extends JpaEntity implements Serializable {
@Table(name = "MXK_PERMISSION")
public class Permission extends JpaEntity implements Serializable {
private static final long serialVersionUID = -8783585691243853899L;
@Id
@@ -50,10 +50,10 @@ public class GroupPrivileges extends JpaEntity implements Serializable {
private String instName;
public GroupPrivileges() {
public Permission() {
}
public GroupPrivileges(String appId, String groupId, String instId) {
public Permission(String appId, String groupId, String instId) {
this.appId = appId;
this.groupId = groupId;
this.instId = instId;
@@ -65,7 +65,7 @@ public class GroupPrivileges extends JpaEntity implements Serializable {
* @param groupId String
* @param resourceId String
*/
public GroupPrivileges(String appId, String groupId, String resourceId , String instId) {
public Permission(String appId, String groupId, String resourceId , String instId) {
this.id = WebContext.genId();
this.appId = appId;
this.groupId = groupId;
@@ -0,0 +1,185 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.entity.permissions;
import java.io.Serializable;
import org.dromara.maxkey.constants.ConstsStatus;
import org.dromara.maxkey.web.WebContext;
import org.dromara.mybatis.jpa.entity.JpaEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "MXK_PERMISSION_ROLE")
public class PermissionRole extends JpaEntity implements Serializable {
private static final long serialVersionUID = -8783585691243853899L;
@Id
@Column
@GeneratedValue
String id;
@Column
String appId;
@Column
String roleId;
@Column
String resourceId;
@Column
String createdBy;
@Column
String createdDate;
int status = ConstsStatus.ACTIVE;
@Column
private String instId;
private String instName;
public PermissionRole() {
}
public PermissionRole(String appId, String roleId, String instId) {
this.appId = appId;
this.roleId = roleId;
this.instId = instId;
}
/**
* .
* @param appId String
* @param roleId String
* @param resourceId String
*/
public PermissionRole(String appId, String roleId, String resourceId , String createdBy,String instId) {
this.id = WebContext.genId();
this.appId = appId;
this.roleId = roleId;
this.resourceId = resourceId;
this.createdBy = createdBy;
this.instId = instId;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getResourceId() {
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getUniqueId() {
return appId + "_" + roleId + "_" + resourceId;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getCreatedDate() {
return createdDate;
}
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
public String getInstId() {
return instId;
}
public void setInstId(String instId) {
this.instId = instId;
}
public String getInstName() {
return instName;
}
public void setInstName(String instName) {
this.instName = instName;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("PermissionRole [id=");
builder.append(id);
builder.append(", appId=");
builder.append(appId);
builder.append(", roleId=");
builder.append(roleId);
builder.append(", resourceId=");
builder.append(resourceId);
builder.append(", createdBy=");
builder.append(createdBy);
builder.append(", createdDate=");
builder.append(createdDate);
builder.append(", status=");
builder.append(status);
builder.append(", instId=");
builder.append(instId);
builder.append(", instName=");
builder.append(instName);
builder.append("]");
return builder.toString();
}
}
@@ -15,7 +15,7 @@
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.permissions;
import java.io.Serializable;
import java.util.Date;
@@ -15,11 +15,11 @@
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.permissions;
import java.io.Serializable;
import org.dromara.mybatis.jpa.entity.JpaEntity;
import org.dromara.maxkey.entity.idm.UserInfo;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
@@ -48,6 +48,8 @@ public class RoleMember extends UserInfo implements Serializable{
private String memberName;
@Column
private String type;//User or Group
private String createdBy;
@Column
private String instId;
@@ -73,14 +75,14 @@ public class RoleMember extends UserInfo implements Serializable{
}
public RoleMember(String roleId, String roleName, String memberId,
String memberName, String type , String instId) {
public RoleMember(String roleId, String roleName, String memberId,String memberName, String type , String createdBy, String instId) {
super();
this.roleId = roleId;
this.roleName = roleName;
this.memberId = memberId;
this.memberName = memberName;
this.type = type;
this.createdBy = createdBy;
this.instId = instId;
}
@@ -164,6 +166,13 @@ public class RoleMember extends UserInfo implements Serializable{
this.category = category;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getInstId() {
return instId;
@@ -15,7 +15,7 @@
*/
package org.dromara.maxkey.entity;
package org.dromara.maxkey.entity.permissions;
import java.io.Serializable;
import java.util.Date;
@@ -43,7 +43,6 @@ public class Roles extends JpaEntity implements Serializable {
public static final String APP = "app";
}
@Id
@Column
@GeneratedValue
@@ -65,10 +64,6 @@ public class Roles extends JpaEntity implements Serializable {
@Column
String orgIdsList;
@Column
String resumeTime;
@Column
String suspendTime;
@Column
int isdefault;
@@ -85,6 +80,9 @@ public class Roles extends JpaEntity implements Serializable {
@Column
int status;
@Column
String appId;
@Column
private String instId;
@@ -103,12 +101,13 @@ public class Roles extends JpaEntity implements Serializable {
* @param name String
* @param isdefault int
*/
public Roles(String id,String roleCode, String roleName, int isdefault) {
public Roles(String id,String roleCode, String roleName, int isdefault,String appId) {
super();
this.id = id;
this.roleCode = roleCode;
this.roleName = roleName;
this.isdefault = isdefault;
this.appId = appId;
}
public String getId() {
@@ -198,7 +197,7 @@ public class Roles extends JpaEntity implements Serializable {
* 3, not filters
*/
public void setDefaultAllUser() {
this.category = "dynamic";
this.category = Category.DYNAMIC;
this.orgIdsList ="";
this.filters ="";
}
@@ -227,23 +226,15 @@ public class Roles extends JpaEntity implements Serializable {
this.orgIdsList = orgIdsList;
}
public String getResumeTime() {
return resumeTime;
}
public String getAppId() {
return appId;
}
public void setResumeTime(String resumeTime) {
this.resumeTime = resumeTime;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getSuspendTime() {
return suspendTime;
}
public void setSuspendTime(String suspendTime) {
this.suspendTime = suspendTime;
}
public String getInstId() {
public String getInstId() {
return instId;
}
@@ -274,10 +265,6 @@ public class Roles extends JpaEntity implements Serializable {
builder.append(filters);
builder.append(", orgIdsList=");
builder.append(orgIdsList);
builder.append(", resumeTime=");
builder.append(resumeTime);
builder.append(", suspendTime=");
builder.append(suspendTime);
builder.append(", isdefault=");
builder.append(isdefault);
builder.append(", description=");
@@ -0,0 +1,64 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.exception;
import java.io.Serial;
/**
* @description:
* @author: orangeBabu
* @time: 16/8/2024 PM3:03
*/
public class BusinessException extends RuntimeException {
/**
* 异常编码
*/
private Integer code;
/**
* 异常消息
*/
private String message;
public BusinessException() {
super();
}
public BusinessException(Integer code, String message) {
this.message = message;
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
@@ -1,19 +1,19 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.persistence.redis;
@@ -26,7 +26,7 @@ import redis.clients.jedis.JedisPoolConfig;
public class RedisConnectionFactory {
private static final Logger _logger = LoggerFactory.getLogger(RedisConnectionFactory.class);
public static class DEFAULT_CONFIG {
/**
* Redis默认服务器IP
@@ -95,7 +95,7 @@ public class RedisConnectionFactory {
timeOut = DEFAULT_CONFIG.DEFAULT_TIMEOUT;
}
if (this.password == null || this.password.equals("") || this.password.equalsIgnoreCase("password")) {
if (this.password == null || this.password.equals("")) {
this.password = null;
}
jedisPool = new JedisPool(poolConfig, hostName, port, timeOut, password);
@@ -120,7 +120,7 @@ public class RedisConnectionFactory {
Jedis jedis = jedisPool.getResource();
_logger.trace("return jedisPool Resource .");
return jedis;
}
public void close(Jedis conn) {
@@ -130,7 +130,7 @@ public class RedisConnectionFactory {
_logger.trace("closed conn .");
}
public String getHostName() {
return hostName;
}
@@ -170,5 +170,5 @@ public class RedisConnectionFactory {
public JedisPoolConfig getPoolConfig() {
return poolConfig;
}
}
@@ -1,104 +0,0 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.persistence.repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.dromara.maxkey.entity.Institutions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
public class InstitutionsRepository {
private static Logger _logger = LoggerFactory.getLogger(InstitutionsRepository.class);
private static final String SELECT_STATEMENT =
"select * from mxk_institutions where id = ? or domain = ? or consoledomain = ?" ;
private static final String DEFAULT_INSTID = "1";
protected static final Cache<String, Institutions> institutionsStore =
Caffeine.newBuilder()
.expireAfterWrite(60, TimeUnit.MINUTES)
.build();
//id domain mapping
protected static final ConcurrentHashMap<String,String> mapper = new ConcurrentHashMap<String,String>();
protected JdbcTemplate jdbcTemplate;
public InstitutionsRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public Institutions get(String instIdOrDomain) {
_logger.trace(" instId {}" , instIdOrDomain);
Institutions inst = getByInstIdOrDomain(instIdOrDomain);
if(inst == null) {//use default inst
inst = getByInstIdOrDomain(DEFAULT_INSTID);
institutionsStore.put(instIdOrDomain, inst);
}
return inst;
}
private Institutions getByInstIdOrDomain(String instIdOrDomain) {
_logger.trace(" instId {}" , instIdOrDomain);
Institutions inst = institutionsStore.getIfPresent(mapper.get(instIdOrDomain)==null ? DEFAULT_INSTID : mapper.get(instIdOrDomain) );
if(inst == null) {
List<Institutions> institutions =
jdbcTemplate.query(SELECT_STATEMENT,new InstitutionsRowMapper(),instIdOrDomain,instIdOrDomain,instIdOrDomain);
if (institutions != null && institutions.size() > 0) {
inst = institutions.get(0);
}
if(inst != null ) {
institutionsStore.put(inst.getDomain(), inst);
institutionsStore.put(inst.getConsoleDomain(), inst);
mapper.put(inst.getId(), inst.getDomain());
}
}
return inst;
}
public class InstitutionsRowMapper implements RowMapper<Institutions> {
@Override
public Institutions mapRow(ResultSet rs, int rowNum) throws SQLException {
Institutions institution = new Institutions();
institution.setId(rs.getString("id"));
institution.setName(rs.getString("name"));
institution.setFullName(rs.getString("fullname"));
institution.setLogo(rs.getString("logo"));
institution.setDomain(rs.getString("domain"));
institution.setFrontTitle(rs.getString("fronttitle"));
institution.setConsoleDomain(rs.getString("consoledomain"));
institution.setConsoleTitle(rs.getString("consoletitle"));
institution.setCaptcha(rs.getString("captcha"));
institution.setDefaultUri(rs.getString("defaultUri"));
return institution;
}
}
}
@@ -1,156 +0,0 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.persistence.repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import org.dromara.maxkey.constants.ConstsTimeInterval;
import org.dromara.maxkey.entity.Localization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
public class LocalizationRepository {
private static Logger _logger = LoggerFactory.getLogger(LocalizationRepository.class);
private static final String INSERT_STATEMENT ="insert into mxk_localization (id, property,langzh,langen,status,description,instid)values(?,?,?,?,?,?,?)";
private static final String UPDATE_STATEMENT ="update mxk_localization set langzh = ? , langen =? where id = ?";
private static final String DELETE_STATEMENT ="delete from mxk_localization where id = ?";
private static final String SELECT_STATEMENT ="select * from mxk_localization where ( id = ? ) or (property = ? and instid = ?)";
private static final Pattern PATTERN_HTML = Pattern.compile("<[^>]+>", Pattern.CASE_INSENSITIVE);
protected InstitutionsRepository institutionService;
JdbcTemplate jdbcTemplate;
protected static final Cache<String, String> localizationStore =
Caffeine.newBuilder()
.expireAfterWrite(ConstsTimeInterval.ONE_HOUR, TimeUnit.SECONDS)
.build();
public LocalizationRepository() {
}
public String getLocale(String code,String htmlTag,Locale locale,String inst) {
String message = "";
htmlTag = (htmlTag == null ||htmlTag.equalsIgnoreCase("true")) ? "tag" : "rtag";
if(code.equals("global.logo")) {
message = institutionService.get(inst).getLogo();
}else if(code.equals("global.title")) {
message = getFromStore(code, htmlTag, locale, inst);
if(message == null) {
message = institutionService.get(inst).getFrontTitle();
}
}else if(code.equals("global.consoleTitle")) {
message = getFromStore(code, htmlTag, locale, inst);
if(message == null) {
message = institutionService.get(inst).getConsoleTitle();
}
}else {
message = getFromStore(code, htmlTag, locale, inst);
}
if(htmlTag.equalsIgnoreCase("rtag")) {
message = clearHTMLToString(message);
}
_logger.trace("{} = {}" , code , message);
return message == null ? "" : message;
}
public String clearHTMLToString(String message) {
return PATTERN_HTML.matcher(message).replaceAll("");
}
public String getFromStore(String code,String htmlTag,Locale locale,String inst) {
String message = localizationStore.getIfPresent(code+"_"+locale.getLanguage()+"_"+inst);
if(message != null) return message;
Localization localization = get(code,inst);
if(localization != null) {
localizationStore.put(code+"_en_"+inst, localization.getLangEn());
localizationStore.put(code+"_zh_"+inst, localization.getLangZh());
if(locale.getLanguage().equals("en")) {
message = localization.getLangEn();
}else {
message = localization.getLangZh();
}
if(message != null) return message;
}
return message;
}
public void setInstitutionService(InstitutionsRepository institutionService) {
this.institutionService = institutionService;
}
public boolean insert(Localization localization) {
return jdbcTemplate.update(INSERT_STATEMENT,
new Object[] {localization.getId(),localization.getProperty(),
localization.getLangZh(),localization.getLangEn(),
localization.getStatus(),localization.getDescription(),
localization.getInstId()},
new int[] {Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.INTEGER,
Types.VARCHAR, Types.VARCHAR,}) > 0;
}
public boolean update(Localization localization) {
jdbcTemplate.update(UPDATE_STATEMENT,localization.getLangZh(),localization.getLangEn(),localization.getId());
return true;
}
public boolean remove(String id) {
return jdbcTemplate.update(DELETE_STATEMENT,id) > 0;
}
public Localization get(String property,String instId) {
_logger.debug("load property from database , property {} ,instId {}",property, instId);
List<Localization> localizations =
jdbcTemplate.query(
SELECT_STATEMENT,new LocalizationRowMapper(),property,property,instId);
return (localizations==null || localizations.size()==0) ? null : localizations.get(0);
}
public LocalizationRepository(JdbcTemplate jdbcTemplate,InstitutionsRepository institutionService) {
super();
this.institutionService = institutionService;
this.jdbcTemplate = jdbcTemplate;
}
public class LocalizationRowMapper implements RowMapper<Localization> {
@Override
public Localization mapRow(ResultSet rs, int rowNum) throws SQLException {
Localization localization = new Localization();
localization.setId(rs.getString("id"));
localization.setProperty(rs.getString("property"));
localization.setLangZh(rs.getString("langzh"));
localization.setLangEn(rs.getString("langen"));
localization.setStatus(rs.getInt("status"));
localization.setDescription(rs.getString("description"));
localization.setInstId(rs.getString("instid"));
return localization;
}
}
}
@@ -1,133 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.persistence.repository;
import java.sql.Types;
import org.dromara.maxkey.entity.HistoryLogin;
import org.dromara.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
public class LoginHistoryRepository {
private static Logger logger = LoggerFactory.getLogger(LoginHistoryRepository.class);
private static final String HISTORY_LOGIN_INSERT_STATEMENT = """
insert into mxk_history_login
( id ,
sessionid ,
userid ,
username ,
displayname ,
logintype ,
message ,
code ,
provider ,
sourceip ,
country ,
province ,
city ,
location ,
browser ,
platform ,
application ,
loginurl ,
sessionstatus ,
instid)
values( ? , ? , ? , ? , ? , ? , ? , ? , ?, ? , ? , ? , ?, ?, ? , ? , ?, ? , ? , ?)
""";
protected JdbcTemplate jdbcTemplate;
public LoginHistoryRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void login(HistoryLogin historyLogin) {
historyLogin.setId(WebContext.genId());
historyLogin.setLoginUrl(WebContext.getRequest().getRequestURI());
//Thread insert
new Thread(new HistoryLoginRunnable(jdbcTemplate,historyLogin)).start();
}
public class HistoryLoginRunnable implements Runnable{
JdbcTemplate jdbcTemplate;
HistoryLogin historyLogin;
public HistoryLoginRunnable(JdbcTemplate jdbcTemplate, HistoryLogin historyLogin) {
super();
this.jdbcTemplate = jdbcTemplate;
this.historyLogin = historyLogin;
}
@Override
public void run() {
logger.debug("History Login {}" , historyLogin);
jdbcTemplate.update(HISTORY_LOGIN_INSERT_STATEMENT,
new Object[] {
historyLogin.getId(),
historyLogin.getSessionId(),
historyLogin.getUserId(),
historyLogin.getUsername(),
historyLogin.getDisplayName(),
historyLogin.getLoginType(),
historyLogin.getMessage(),
historyLogin.getCode(),
historyLogin.getProvider(),
historyLogin.getSourceIp(),
historyLogin.getCountry(),
historyLogin.getProvince(),
historyLogin.getCity(),
historyLogin.getLocation(),
historyLogin.getBrowser(),
historyLogin.getPlatform(),
"Browser",
historyLogin.getLoginUrl(),
historyLogin.getSessionStatus(),
historyLogin.getInstId()
},
new int[] {
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.VARCHAR,
Types.INTEGER,
Types.VARCHAR
});
}
}
}
@@ -1,380 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.persistence.repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.dromara.maxkey.constants.ConstsRoles;
import org.dromara.maxkey.constants.ConstsStatus;
import org.dromara.maxkey.entity.Groups;
import org.dromara.maxkey.entity.UserInfo;
import org.dromara.maxkey.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
public class LoginRepository {
private static final Logger _logger = LoggerFactory.getLogger(LoginRepository.class);
private static final String LOCK_USER_UPDATE_STATEMENT = "update mxk_userinfo set islocked = ? , unlocktime = ? where id = ?";
private static final String UNLOCK_USER_UPDATE_STATEMENT = "update mxk_userinfo set islocked = ? , unlocktime = ? where id = ?";
private static final String BADPASSWORDCOUNT_UPDATE_STATEMENT = "update mxk_userinfo set badpasswordcount = ? , badpasswordtime = ? where id = ?";
private static final String BADPASSWORDCOUNT_RESET_UPDATE_STATEMENT = "update mxk_userinfo set badpasswordcount = ? , islocked = ? ,unlocktime = ? where id = ?";
private static final String LOGIN_USERINFO_UPDATE_STATEMENT = "update mxk_userinfo set lastlogintime = ? , lastloginip = ? , logincount = ?, online = "
+ UserInfo.ONLINE.ONLINE + " where id = ?";
private static final String GROUPS_SELECT_STATEMENT = "select distinct g.id,g.groupcode,g.groupname from mxk_userinfo u,mxk_groups g,mxk_group_member gm where u.id = ? and u.id=gm.memberid and gm.groupid=g.id ";
private static final String DEFAULT_USERINFO_SELECT_STATEMENT = "select * from mxk_userinfo where username = ? ";
private static final String DEFAULT_USERINFO_SELECT_STATEMENT_USERNAME_MOBILE = "select * from mxk_userinfo where (username = ? or mobile = ?)";
private static final String DEFAULT_USERINFO_SELECT_STATEMENT_USERNAME_MOBILE_EMAIL = "select * from mxk_userinfo where (username = ? or mobile = ? or email = ?) ";
private static final String DEFAULT_MYAPPS_SELECT_STATEMENT = "select distinct app.id,app.appname from mxk_apps app,mxk_group_permissions gp,mxk_groups g where app.id=gp.appid and app.status = 1 and gp.groupid=g.id and g.id in(%s)";
protected JdbcTemplate jdbcTemplate;
/**
* 1 (USERNAME) 2 (USERNAME | MOBILE) 3 (USERNAME | MOBILE | EMAIL)
*/
public static int LOGIN_ATTRIBUTE_TYPE = 2;
public LoginRepository(){
}
public LoginRepository(JdbcTemplate jdbcTemplate){
this.jdbcTemplate=jdbcTemplate;
}
public UserInfo find(String username, String password) {
List<UserInfo> listUserInfo = null ;
if( LOGIN_ATTRIBUTE_TYPE == 1) {
listUserInfo = findByUsername(username,password);
}else if( LOGIN_ATTRIBUTE_TYPE == 2) {
listUserInfo = findByUsernameOrMobile(username,password);
}else if( LOGIN_ATTRIBUTE_TYPE == 3) {
listUserInfo = findByUsernameOrMobileOrEmail(username,password);
}
_logger.debug("load UserInfo : {}" , listUserInfo);
return (CollectionUtils.isNotEmpty(listUserInfo))? listUserInfo.get(0) : null;
}
public List<UserInfo> findByUsername(String username, String password) {
return jdbcTemplate.query(
DEFAULT_USERINFO_SELECT_STATEMENT,
new UserInfoRowMapper(),
username
);
}
public List<UserInfo> findByUsernameOrMobile(String username, String password) {
return jdbcTemplate.query(
DEFAULT_USERINFO_SELECT_STATEMENT_USERNAME_MOBILE,
new UserInfoRowMapper(),
username,username
);
}
public List<UserInfo> findByUsernameOrMobileOrEmail(String username, String password) {
return jdbcTemplate.query(
DEFAULT_USERINFO_SELECT_STATEMENT_USERNAME_MOBILE_EMAIL,
new UserInfoRowMapper(),
username,username,username
);
}
/**
* 閿佸畾鐢ㄦ埛锛歩slock锛�1 鐢ㄦ埛瑙i攣 2 鐢ㄦ埛閿佸畾
*
* @param userInfo
*/
public void updateLock(UserInfo userInfo) {
try {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
jdbcTemplate.update(LOCK_USER_UPDATE_STATEMENT,
new Object[] { ConstsStatus.LOCK, new Date(), userInfo.getId() },
new int[] { Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR });
userInfo.setIsLocked(ConstsStatus.LOCK);
}
} catch (Exception e) {
_logger.error("lockUser Exception",e);
}
}
/**
* 閿佸畾鐢ㄦ埛锛歩slock锛�1 鐢ㄦ埛瑙i攣 2 鐢ㄦ埛閿佸畾
*
* @param userInfo
*/
public void updateUnlock(UserInfo userInfo) {
try {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
jdbcTemplate.update(UNLOCK_USER_UPDATE_STATEMENT,
new Object[] { ConstsStatus.ACTIVE, new Date(), userInfo.getId() },
new int[] { Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR });
userInfo.setIsLocked(ConstsStatus.ACTIVE);
}
} catch (Exception e) {
_logger.error("unlockUser Exception",e);
}
}
/**
* reset BadPasswordCount And Lockout
*
* @param userInfo
*/
public void updateLockout(UserInfo userInfo) {
try {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
jdbcTemplate.update(BADPASSWORDCOUNT_RESET_UPDATE_STATEMENT,
new Object[] { 0, ConstsStatus.ACTIVE, new Date(), userInfo.getId() },
new int[] { Types.INTEGER, Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR });
userInfo.setIsLocked(ConstsStatus.ACTIVE);
}
} catch (Exception e) {
_logger.error("resetBadPasswordCountAndLockout Exception",e);
}
}
/**
* if login password is error ,BadPasswordCount++ and set bad date
*
* @param userInfo
*/
public void updateBadPasswordCount(UserInfo userInfo) {
try {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
int badPasswordCount = userInfo.getBadPasswordCount() + 1;
userInfo.setBadPasswordCount(badPasswordCount);
jdbcTemplate.update(BADPASSWORDCOUNT_UPDATE_STATEMENT,
new Object[] { badPasswordCount, new Date(), userInfo.getId() },
new int[] { Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR });
}
} catch (Exception e) {
e.printStackTrace();
_logger.error(e.getMessage());
}
}
public List<GrantedAuthority> queryAuthorizedApps(List<GrantedAuthority> grantedAuthoritys) {
String grantedAuthorityString="'ROLE_ALL_USER'";
for(GrantedAuthority grantedAuthority : grantedAuthoritys) {
grantedAuthorityString += ",'"+ grantedAuthority.getAuthority()+"'";
}
ArrayList<GrantedAuthority> listAuthorizedApps = (ArrayList<GrantedAuthority>) jdbcTemplate.query(
String.format(DEFAULT_MYAPPS_SELECT_STATEMENT, grantedAuthorityString),
new RowMapper<GrantedAuthority>() {
public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
return new SimpleGrantedAuthority(rs.getString("id"));
}
});
_logger.debug("list Authorized Apps {}" , listAuthorizedApps);
return listAuthorizedApps;
}
public List<Groups> queryGroups(UserInfo userInfo) {
List<Groups> listRoles = jdbcTemplate.query(GROUPS_SELECT_STATEMENT, new RowMapper<Groups>() {
public Groups mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Groups(rs.getString("id"), rs.getString("groupcode"),rs.getString("groupname"), 0);
}
}, userInfo.getId());
_logger.debug("list Roles {}" , listRoles);
return listRoles;
}
/**
* grant Authority by userinfo
*
* @param userInfo
* @return ArrayList<GrantedAuthority>
*/
public List<GrantedAuthority> grantAuthority(UserInfo userInfo) {
// query Groups for user
List<Groups> listGroups = queryGroups(userInfo);
//set default groups
ArrayList<GrantedAuthority> grantedAuthority = new ArrayList<>();
grantedAuthority.add(ConstsRoles.ROLE_USER);
grantedAuthority.add(ConstsRoles.ROLE_ALL_USER);
grantedAuthority.add(ConstsRoles.ROLE_ORDINARY_USER);
for (Groups group : listGroups) {
grantedAuthority.add(new SimpleGrantedAuthority(group.getId()));
if(group.getGroupCode().startsWith("ROLE_")
&& !grantedAuthority.contains(new SimpleGrantedAuthority(group.getGroupCode()))) {
grantedAuthority.add(new SimpleGrantedAuthority(group.getGroupCode()));
}
}
_logger.debug("Authority : {}" , grantedAuthority);
return grantedAuthority;
}
public void updateLastLogin(UserInfo userInfo) {
jdbcTemplate.update(LOGIN_USERINFO_UPDATE_STATEMENT,
new Object[] {
userInfo.getLastLoginTime(),
userInfo.getLastLoginIp(),
userInfo.getLoginCount() + 1,
userInfo.getId()
},
new int[] { Types.TIMESTAMP, Types.VARCHAR, Types.INTEGER, Types.VARCHAR });
}
public class UserInfoRowMapper implements RowMapper<UserInfo> {
@Override
public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
UserInfo userInfo = new UserInfo();
userInfo.setId(rs.getString("id"));
userInfo.setUsername(rs.getString("username"));
userInfo.setPassword(rs.getString("password"));
userInfo.setSharedSecret(rs.getString("sharedsecret"));
userInfo.setSharedCounter(rs.getString("sharedcounter"));
userInfo.setDecipherable(rs.getString("decipherable"));
userInfo.setWindowsAccount(rs.getString("windowsaccount"));
userInfo.setUserType(rs.getString("usertype"));
userInfo.setDisplayName(rs.getString("displayname"));
userInfo.setNickName(rs.getString("nickname"));
userInfo.setNameZhSpell(rs.getString("namezhspell"));// nameZHSpell
userInfo.setNameZhShortSpell(rs.getString("namezhshortspell"));// nameZHSpell
userInfo.setGivenName(rs.getString("givenname"));
userInfo.setMiddleName(rs.getString("middlename"));
userInfo.setFamilyName(rs.getString("familyname"));
userInfo.setHonorificPrefix(rs.getString("honorificprefix"));
userInfo.setHonorificSuffix(rs.getString("honorificsuffix"));
userInfo.setFormattedName(rs.getString("formattedname"));
userInfo.setGender(rs.getInt("gender"));
userInfo.setBirthDate(rs.getString("birthdate"));
userInfo.setPicture(rs.getBytes("picture"));
userInfo.setMarried(rs.getInt("married"));
userInfo.setIdType(rs.getInt("idtype"));
userInfo.setIdCardNo(rs.getString("idcardno"));
userInfo.setWebSite(rs.getString("website"));
userInfo.setAuthnType(rs.getInt("authntype"));
userInfo.setMobile(rs.getString("mobile"));
userInfo.setMobileVerified(rs.getInt("mobileverified"));
userInfo.setEmail(rs.getString("email"));
userInfo.setEmailVerified(rs.getInt("emailverified"));
userInfo.setPasswordQuestion(rs.getString("passwordquestion"));
userInfo.setPasswordAnswer(rs.getString("passwordanswer"));
userInfo.setAppLoginAuthnType(rs.getInt("apploginauthntype"));
userInfo.setAppLoginPassword(rs.getString("apploginpassword"));
userInfo.setProtectedApps(rs.getString("protectedapps"));
userInfo.setPasswordLastSetTime(rs.getTimestamp("passwordlastsettime"));
userInfo.setPasswordSetType(rs.getInt("passwordsettype"));
userInfo.setBadPasswordCount(rs.getInt("badpasswordcount"));
userInfo.setBadPasswordTime(rs.getTimestamp("badpasswordtime"));
userInfo.setUnLockTime(rs.getTimestamp("unlocktime"));
userInfo.setIsLocked(rs.getInt("islocked"));
userInfo.setLastLoginTime(rs.getTimestamp("lastlogintime"));
userInfo.setLastLoginIp(rs.getString("lastloginip"));
userInfo.setLastLogoffTime(rs.getTimestamp("lastlogofftime"));
userInfo.setLoginCount(rs.getInt("logincount"));
userInfo.setRegionHistory(rs.getString("regionhistory"));
userInfo.setPasswordHistory(rs.getString("passwordhistory"));
userInfo.setTimeZone(rs.getString("timezone"));
userInfo.setLocale(rs.getString("locale"));
userInfo.setPreferredLanguage(rs.getString("preferredlanguage"));
userInfo.setWorkEmail(rs.getString("workemail"));
userInfo.setWorkPhoneNumber(rs.getString("workphonenumber"));
userInfo.setWorkCountry(rs.getString("workcountry"));
userInfo.setWorkRegion(rs.getString("workregion"));
userInfo.setWorkLocality(rs.getString("worklocality"));
userInfo.setWorkStreetAddress(rs.getString("workstreetaddress"));
userInfo.setWorkAddressFormatted(rs.getString("workaddressformatted"));
userInfo.setWorkPostalCode(rs.getString("workpostalcode"));
userInfo.setWorkFax(rs.getString("workfax"));
userInfo.setHomeEmail(rs.getString("homeemail"));
userInfo.setHomePhoneNumber(rs.getString("homephonenumber"));
userInfo.setHomeCountry(rs.getString("homecountry"));
userInfo.setHomeRegion(rs.getString("homeregion"));
userInfo.setHomeLocality(rs.getString("homelocality"));
userInfo.setHomeStreetAddress(rs.getString("homestreetaddress"));
userInfo.setHomeAddressFormatted(rs.getString("homeaddressformatted"));
userInfo.setHomePostalCode(rs.getString("homepostalcode"));
userInfo.setHomeFax(rs.getString("homefax"));
userInfo.setEmployeeNumber(rs.getString("employeenumber"));
userInfo.setDivision(rs.getString("division"));
userInfo.setCostCenter(rs.getString("costcenter"));
userInfo.setOrganization(rs.getString("organization"));
userInfo.setDepartmentId(rs.getString("departmentid"));
userInfo.setDepartment(rs.getString("department"));
userInfo.setJobTitle(rs.getString("jobtitle"));
userInfo.setJobLevel(rs.getString("joblevel"));
userInfo.setManagerId(rs.getString("managerid"));
userInfo.setManager(rs.getString("manager"));
userInfo.setAssistantId(rs.getString("assistantid"));
userInfo.setAssistant(rs.getString("assistant"));
userInfo.setEntryDate(rs.getString("entrydate"));//
userInfo.setQuitDate(rs.getString("quitdate"));
userInfo.setStartWorkDate(rs.getString("startworkdate"));// STARTWORKDATE
userInfo.setExtraAttribute(rs.getString("extraattribute"));
userInfo.setCreatedBy(rs.getString("createdby"));
userInfo.setCreatedDate(rs.getTimestamp("createddate"));
userInfo.setModifiedBy(rs.getString("modifiedby"));
userInfo.setModifiedDate(rs.getTimestamp("modifieddate"));
userInfo.setStatus(rs.getInt("status"));
userInfo.setGridList(rs.getInt("gridlist"));
userInfo.setDescription(rs.getString("description"));
userInfo.setTheme(rs.getString("theme"));
userInfo.setInstId(rs.getString("instid"));
if (userInfo.getTheme() == null || userInfo.getTheme().equalsIgnoreCase("")) {
userInfo.setTheme("default");
}
return userInfo;
}
}
}
@@ -1,72 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.persistence.repository;
import java.util.Locale;
import org.passay.MessageResolver;
import org.passay.PropertiesMessageResolver;
import org.passay.RuleResultDetail;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.MessageSourceAccessor;
public class PasswordPolicyMessageResolver implements MessageResolver{
/** A accessor for Spring's {@link MessageSource} */
private final MessageSourceAccessor messageSourceAccessor;
/** The {@link MessageResolver} for fallback */
private final MessageResolver fallbackMessageResolver = new PropertiesMessageResolver();
/**
* Create a new instance with the locale associated with the current thread.
* @param messageSource a message source managed by spring
*/
public PasswordPolicyMessageResolver(final MessageSource messageSource)
{
this.messageSourceAccessor = new MessageSourceAccessor(messageSource);
}
/**
* Create a new instance with the specified locale.
* @param messageSource a message source managed by spring
* @param locale the locale to use for message access
*/
public PasswordPolicyMessageResolver(final MessageSource messageSource, final Locale locale)
{
this.messageSourceAccessor = new MessageSourceAccessor(messageSource, locale);
}
/**
* Resolves the message for the supplied rule result detail using Spring's {@link MessageSource}.
* (If the message can't retrieve from a {@link MessageSource}, return default message provided by passay)
* @param detail rule result detail
* @return message for the detail error code
*/
@Override
public String resolve(final RuleResultDetail detail)
{
try {
return this.messageSourceAccessor.getMessage("PasswordPolicy."+detail.getErrorCode(), detail.getValues());
} catch (NoSuchMessageException e) {
return this.fallbackMessageResolver.resolve(detail);
}
}
}
@@ -1,186 +0,0 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.persistence.repository;
import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.dromara.maxkey.constants.ConstsProperties;
import org.dromara.maxkey.entity.PasswordPolicy;
import org.passay.CharacterOccurrencesRule;
import org.passay.CharacterRule;
import org.passay.DictionaryRule;
import org.passay.EnglishCharacterData;
import org.passay.EnglishSequenceData;
import org.passay.IllegalSequenceRule;
import org.passay.LengthRule;
import org.passay.Rule;
import org.passay.UsernameRule;
import org.passay.WhitespaceRule;
import org.passay.dictionary.Dictionary;
import org.passay.dictionary.DictionaryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
public class PasswordPolicyRepository {
private static Logger _logger = LoggerFactory.getLogger(PasswordPolicyRepository.class);
//Dictionary topWeakPassword Source
public static final String topWeakPasswordPropertySource =
"classpath:/top_weak_password.txt";
//Cache PasswordPolicy in memory ONE_HOUR
protected static final Cache<String, PasswordPolicy> passwordPolicyStore =
Caffeine.newBuilder()
.expireAfterWrite(60, TimeUnit.MINUTES)
.build();
protected PasswordPolicy passwordPolicy;
protected JdbcTemplate jdbcTemplate;
ArrayList <Rule> passwordPolicyRuleList;
private static final String PASSWORD_POLICY_KEY = "PASSWORD_POLICY_KEY";
private static final String PASSWORD_POLICY_SELECT_STATEMENT = "select * from mxk_password_policy ";
public PasswordPolicyRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* init PasswordPolicy and load Rules
* @return
*/
public PasswordPolicy getPasswordPolicy() {
passwordPolicy = passwordPolicyStore.getIfPresent(PASSWORD_POLICY_KEY);
if (passwordPolicy == null) {
passwordPolicy = jdbcTemplate.queryForObject(PASSWORD_POLICY_SELECT_STATEMENT,
new PasswordPolicyRowMapper());
_logger.debug("query PasswordPolicy : " + passwordPolicy);
passwordPolicyStore.put(PASSWORD_POLICY_KEY,passwordPolicy);
//RandomPasswordLength =(MaxLength +MinLength)/2
passwordPolicy.setRandomPasswordLength(
Math.round(
(
passwordPolicy.getMaxLength() +
passwordPolicy.getMinLength()
)/2
)
);
passwordPolicyRuleList = new ArrayList<Rule>();
passwordPolicyRuleList.add(new WhitespaceRule());
passwordPolicyRuleList.add(new LengthRule(passwordPolicy.getMinLength(), passwordPolicy.getMaxLength()));
if(passwordPolicy.getUpperCase()>0) {
passwordPolicyRuleList.add(new CharacterRule(EnglishCharacterData.UpperCase, passwordPolicy.getUpperCase()));
}
if(passwordPolicy.getLowerCase()>0) {
passwordPolicyRuleList.add(new CharacterRule(EnglishCharacterData.LowerCase, passwordPolicy.getLowerCase()));
}
if(passwordPolicy.getDigits()>0) {
passwordPolicyRuleList.add(new CharacterRule(EnglishCharacterData.Digit, passwordPolicy.getDigits()));
}
if(passwordPolicy.getSpecialChar()>0) {
passwordPolicyRuleList.add(new CharacterRule(EnglishCharacterData.Special, passwordPolicy.getSpecialChar()));
}
if(passwordPolicy.getUsername()>0) {
passwordPolicyRuleList.add(new UsernameRule());
}
if(passwordPolicy.getOccurances()>0) {
passwordPolicyRuleList.add(new CharacterOccurrencesRule(passwordPolicy.getOccurances()));
}
if(passwordPolicy.getAlphabetical()>0) {
passwordPolicyRuleList.add(new IllegalSequenceRule(EnglishSequenceData.Alphabetical, 4, false));
}
if(passwordPolicy.getNumerical()>0) {
passwordPolicyRuleList.add(new IllegalSequenceRule(EnglishSequenceData.Numerical, 4, false));
}
if(passwordPolicy.getQwerty()>0) {
passwordPolicyRuleList.add(new IllegalSequenceRule(EnglishSequenceData.USQwerty, 4, false));
}
if(passwordPolicy.getDictionary()>0 ) {
try {
ClassPathResource dictFile=
new ClassPathResource(
ConstsProperties.classPathResource(topWeakPasswordPropertySource));
Dictionary dictionary =new DictionaryBuilder().addReader(new InputStreamReader(dictFile.getInputStream())).build();
passwordPolicyRuleList.add(new DictionaryRule(dictionary));
}catch(Exception e) {
e.printStackTrace();
}
}
}
return passwordPolicy;
}
public ArrayList<Rule> getPasswordPolicyRuleList() {
getPasswordPolicy();
return passwordPolicyRuleList;
}
public class PasswordPolicyRowMapper implements RowMapper<PasswordPolicy> {
@Override
public PasswordPolicy mapRow(ResultSet rs, int rowNum) throws SQLException {
PasswordPolicy passwordPolicy = new PasswordPolicy();
passwordPolicy.setId(rs.getString("id"));
passwordPolicy.setMinLength(rs.getInt("minlength"));
passwordPolicy.setMaxLength(rs.getInt("maxlength"));
passwordPolicy.setLowerCase(rs.getInt("lowercase"));
passwordPolicy.setUpperCase(rs.getInt("uppercase"));
passwordPolicy.setDigits(rs.getInt("digits"));
passwordPolicy.setSpecialChar(rs.getInt("specialchar"));
passwordPolicy.setAttempts(rs.getInt("attempts"));
passwordPolicy.setDuration(rs.getInt("duration"));
passwordPolicy.setExpiration(rs.getInt("expiration"));
passwordPolicy.setUsername(rs.getInt("username"));
passwordPolicy.setHistory(rs.getInt("history"));
passwordPolicy.setDictionary(rs.getInt("dictionary"));
passwordPolicy.setAlphabetical(rs.getInt("alphabetical"));
passwordPolicy.setNumerical(rs.getInt("numerical"));
passwordPolicy.setQwerty(rs.getInt("qwerty"));
passwordPolicy.setOccurances(rs.getInt("occurances"));
return passwordPolicy;
}
}
}
@@ -1,320 +0,0 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.persistence.repository;
import java.sql.Types;
import java.util.Date;
import org.dromara.maxkey.constants.ConstsPasswordSetType;
import org.dromara.maxkey.constants.ConstsStatus;
import org.dromara.maxkey.crypto.password.PasswordGen;
import org.dromara.maxkey.entity.ChangePassword;
import org.dromara.maxkey.entity.PasswordPolicy;
import org.dromara.maxkey.entity.UserInfo;
import org.dromara.maxkey.util.StringUtils;
import org.dromara.maxkey.web.WebConstants;
import org.dromara.maxkey.web.WebContext;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.BadCredentialsException;
public class PasswordPolicyValidator {
private static Logger _logger = LoggerFactory.getLogger(PasswordPolicyValidator.class);
PasswordPolicyRepository passwordPolicyRepository;
protected JdbcTemplate jdbcTemplate;
MessageSource messageSource;
public static final String PASSWORD_POLICY_VALIDATE_RESULT = "PASSWORD_POLICY_SESSION_VALIDATE_RESULT_KEY";
private static final String LOCK_USER_UPDATE_STATEMENT = "update mxk_userinfo set islocked = ? , unlocktime = ? where id = ?";
private static final String UNLOCK_USER_UPDATE_STATEMENT = "update mxk_userinfo set islocked = ? , unlocktime = ? where id = ?";
private static final String BADPASSWORDCOUNT_UPDATE_STATEMENT = "update mxk_userinfo set badpasswordcount = ? , badpasswordtime = ? where id = ?";
private static final String BADPASSWORDCOUNT_RESET_UPDATE_STATEMENT = "update mxk_userinfo set badpasswordcount = ? , islocked = ? ,unlocktime = ? where id = ?";
public PasswordPolicyValidator() {
}
public PasswordPolicyValidator(JdbcTemplate jdbcTemplate,MessageSource messageSource) {
this.messageSource=messageSource;
this.jdbcTemplate = jdbcTemplate;
this.passwordPolicyRepository = new PasswordPolicyRepository(jdbcTemplate);
}
/**
* static validator .
* @param userInfo
* @return boolean
*/
public boolean validator(ChangePassword changePassword) {
String password = changePassword.getPassword();
String username = changePassword.getUsername();
if(password.equals("") || password==null){
_logger.debug("password is Empty ");
return false;
}
PasswordValidator validator = new PasswordValidator(
new PasswordPolicyMessageResolver(messageSource),passwordPolicyRepository.getPasswordPolicyRuleList());
RuleResult result = validator.validate(new PasswordData(username,password));
if (result.isValid()) {
_logger.debug("Password is valid");
return true;
} else {
_logger.debug("Invalid password:");
String passwordPolicyMessage = "";
for (String msg : validator.getMessages(result)) {
passwordPolicyMessage = passwordPolicyMessage + msg + "<br>";
_logger.debug("Rule Message {}" , msg);
}
WebContext.setAttribute(PasswordPolicyValidator.PASSWORD_POLICY_VALIDATE_RESULT, passwordPolicyMessage);
return false;
}
}
/**
* dynamic passwordPolicy Valid for user login.
* @param userInfo
* @return boolean
*/
public boolean passwordPolicyValid(UserInfo userInfo) {
PasswordPolicy passwordPolicy = passwordPolicyRepository.getPasswordPolicy();
DateTime currentdateTime = new DateTime();
/*
* check login attempts fail times
*/
if (userInfo.getBadPasswordCount() >= passwordPolicy.getAttempts() && userInfo.getBadPasswordTime() != null) {
_logger.debug("login Attempts is {} , bad Password Time {}" , userInfo.getBadPasswordCount(),userInfo.getBadPasswordTime());
Duration duration = new Duration(new DateTime(userInfo.getBadPasswordTime()), currentdateTime);
int intDuration = Integer.parseInt(duration.getStandardMinutes() + "");
_logger.debug("bad Password duration {} , " +
"password policy Duration {} , "+
"validate result {}" ,
intDuration,
passwordPolicy.getDuration(),
(intDuration > passwordPolicy.getDuration())
);
//auto unlock attempts when intDuration >= set Duration
if(intDuration >= passwordPolicy.getDuration()) {
_logger.debug("resetAttempts ...");
resetAttempts(userInfo);
}else {
lockUser(userInfo);
throw new BadCredentialsException(
WebContext.getI18nValue("login.error.attempts",
new Object[]{userInfo.getBadPasswordCount(),passwordPolicy.getDuration()})
);
}
}
//locked
if(userInfo.getIsLocked()==ConstsStatus.LOCK) {
throw new BadCredentialsException(
userInfo.getUsername()+ " "+
WebContext.getI18nValue("login.error.locked")
);
}
// inactive
if(userInfo.getStatus()!=ConstsStatus.ACTIVE) {
throw new BadCredentialsException(
userInfo.getUsername()+
WebContext.getI18nValue("login.error.inactive")
);
}
return true;
}
public void applyPasswordPolicy(UserInfo userInfo) {
PasswordPolicy passwordPolicy = passwordPolicyRepository.getPasswordPolicy();
DateTime currentdateTime = new DateTime();
//initial password need change
if(userInfo.getLoginCount()<=0) {
WebContext.getSession().setAttribute(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE,
ConstsPasswordSetType.INITIAL_PASSWORD);
}
if (userInfo.getPasswordSetType() != ConstsPasswordSetType.PASSWORD_NORMAL) {
WebContext.getSession().setAttribute(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE,
userInfo.getPasswordSetType());
return;
} else {
WebContext.getSession().setAttribute(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE,
ConstsPasswordSetType.PASSWORD_NORMAL);
}
/*
* check password is Expired,Expiration is Expired date ,if Expiration equals 0,not need check
*
*/
if (passwordPolicy.getExpiration() > 0 && userInfo.getPasswordLastSetTime() != null) {
_logger.info("last password set date {}" , userInfo.getPasswordLastSetTime());
Duration duration = new Duration(new DateTime(userInfo.getPasswordLastSetTime()), currentdateTime);
int intDuration = Integer.parseInt(duration.getStandardDays() + "");
_logger.debug("password Last Set duration day {} , " +
"password policy Expiration {} , " +
"validate result {}",
intDuration,
passwordPolicy.getExpiration(),
intDuration <= passwordPolicy.getExpiration()
);
if (intDuration > passwordPolicy.getExpiration()) {
WebContext.getSession().setAttribute(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE,
ConstsPasswordSetType.PASSWORD_EXPIRED);
}
}
resetBadPasswordCount(userInfo);
}
/**
* lockUser
*
* @param userInfo
*/
public void lockUser(UserInfo userInfo) {
try {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
if(userInfo.getIsLocked() == ConstsStatus.ACTIVE) {
jdbcTemplate.update(LOCK_USER_UPDATE_STATEMENT,
new Object[] { ConstsStatus.LOCK, new Date(), userInfo.getId() },
new int[] { Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR });
userInfo.setIsLocked(ConstsStatus.LOCK);
}
}
} catch (Exception e) {
_logger.error("lockUser Exception",e);
}
}
/**
* unlockUser
*
* @param userInfo
*/
public void unlockUser(UserInfo userInfo) {
try {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
jdbcTemplate.update(UNLOCK_USER_UPDATE_STATEMENT,
new Object[] { ConstsStatus.ACTIVE, new Date(), userInfo.getId() },
new int[] { Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR });
userInfo.setIsLocked(ConstsStatus.ACTIVE);
}
} catch (Exception e) {
_logger.error("unlockUser Exception",e);
}
}
/**
* reset BadPasswordCount And Lockout
*
* @param userInfo
*/
public void resetAttempts(UserInfo userInfo) {
try {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
jdbcTemplate.update(BADPASSWORDCOUNT_RESET_UPDATE_STATEMENT,
new Object[] { 0, ConstsStatus.ACTIVE, new Date(), userInfo.getId() },
new int[] { Types.INTEGER, Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR });
userInfo.setIsLocked(ConstsStatus.ACTIVE);
userInfo.setBadPasswordCount(0);
}
} catch (Exception e) {
_logger.error("resetAttempts Exception",e);
}
}
/**
* if login password is error ,BadPasswordCount++ and set bad date
*
* @param userInfo
*/
private void setBadPasswordCount(String userId,int badPasswordCount) {
try {
jdbcTemplate.update(BADPASSWORDCOUNT_UPDATE_STATEMENT,
new Object[] { badPasswordCount, new Date(), userId },
new int[] { Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR });
} catch (Exception e) {
_logger.error("setBadPasswordCount Exception",e);
}
}
public void plusBadPasswordCount(UserInfo userInfo) {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
userInfo.setBadPasswordCount(userInfo.getBadPasswordCount() + 1);
setBadPasswordCount(userInfo.getId(),userInfo.getBadPasswordCount());
PasswordPolicy passwordPolicy = passwordPolicyRepository.getPasswordPolicy();
if(userInfo.getBadPasswordCount() >= passwordPolicy.getAttempts()) {
_logger.debug("Bad Password Count {} , Max Attempts {}",
userInfo.getBadPasswordCount() + 1,passwordPolicy.getAttempts());
this.lockUser(userInfo);
}
}
}
public void resetBadPasswordCount(UserInfo userInfo) {
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getId())) {
if(userInfo.getBadPasswordCount()>0) {
setBadPasswordCount(userInfo.getId(),0);
}
}
}
public String generateRandomPassword() {
PasswordPolicy passwordPolicy = passwordPolicyRepository.getPasswordPolicy();
PasswordGen passwordGen = new PasswordGen(
passwordPolicy.getRandomPasswordLength()
);
return passwordGen.gen(
passwordPolicy.getLowerCase(),
passwordPolicy.getUpperCase(),
passwordPolicy.getDigits(),
passwordPolicy.getSpecialChar());
}
public PasswordPolicyRepository getPasswordPolicyRepository() {
return passwordPolicyRepository;
}
}
@@ -0,0 +1,47 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.schedule;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ScheduleAdapter {
private static final Logger _logger = LoggerFactory.getLogger(ScheduleAdapter.class);
JobExecutionContext context;
protected int jobStatus = JOBSTATUS.STOP;
public static final class JOBSTATUS{
public static final int STOP = 0;
public static final int RUNNING = 1;
public static final int ERROR = 2;
public static final int FINISHED = 3;
}
protected void init(JobExecutionContext context){
this.context = context;
}
@SuppressWarnings("unchecked")
public <T> T getParameter(String name, Class<T> requiredType) {
_logger.trace("requiredType {}",requiredType);
return (T) context.getMergedJobDataMap().get(name);
}
}
@@ -0,0 +1,115 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.schedule;
import org.apache.commons.lang3.StringUtils;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ScheduleAdapterBuilder {
private static final Logger _logger = LoggerFactory.getLogger(ScheduleAdapterBuilder.class);
Scheduler scheduler ;
String cron;
Class <? extends Job> jobClass;
JobDataMap jobDataMap;
String identity ;
public void addListener(
Scheduler scheduler ,
Class <? extends Job> jobClass,
String cronSchedule,
JobDataMap jobDataMap
) throws SchedulerException {
this.cron = cronSchedule;
this.scheduler = scheduler;
this.jobClass = jobClass;
this.jobDataMap = jobDataMap;
this.build();
}
public ScheduleAdapterBuilder setIdentity(String identity) {
this.identity = identity;
return this;
}
public ScheduleAdapterBuilder setScheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
public ScheduleAdapterBuilder setJobDataMap(JobDataMap jobDataMap) {
this.jobDataMap = jobDataMap;
return this;
}
public ScheduleAdapterBuilder setJobData(String key,Object data) {
if(this.jobDataMap == null) {
jobDataMap = new JobDataMap();
}
this.jobDataMap.put(key, data);
return this;
}
public ScheduleAdapterBuilder setCron(String cron) {
this.cron = cron;
return this;
}
public ScheduleAdapterBuilder setJobClass(Class <? extends Job> jobClass) {
this.jobClass = jobClass;
return this;
}
public void build() throws SchedulerException {
if(StringUtils.isBlank(identity)) {
identity = jobClass.getSimpleName();
}
_logger.debug("Job schedule {} ,Cron {} ", identity ,cron);
JobDetail jobDetail =
JobBuilder.newJob(jobClass)
.withIdentity(identity, identity + "Group")
.build();
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
CronTrigger cronTrigger =
TriggerBuilder.newTrigger()
.withIdentity("trigger" + identity, identity + "TriggerGroup")
.usingJobData(jobDataMap)
.withSchedule(scheduleBuilder)
.build();
scheduler.scheduleJob(jobDetail,cronTrigger);
}
}
@@ -0,0 +1,215 @@
/*
* Copyright [2024] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.web;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.UnexpectedTypeException;
import org.dromara.maxkey.entity.Message;
import org.dromara.maxkey.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import java.util.List;
import java.util.Objects;
/**
* @description:
* @author: orangeBabu
* @time: 16/8/2024 PM3:02
*/
/**
* 全局异常处理器
*
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 缺少请求体异常处理器
* @param e 缺少请求体异常 使用get方式请求 而实体使用@RequestBody修饰
*/
@ExceptionHandler(HttpMessageNotReadableException.class)
public Message<Void> parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}',请求体缺失'{}'", requestURI, e.getMessage(),e);
return new Message<>(Message.FAIL, "缺少请求体");
}
// get请求的对象参数校验异常
@ExceptionHandler({MissingServletRequestParameterException.class})
public Message<Void> bindExceptionHandler(MissingServletRequestParameterException e,HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}',get方式请求参数'{}'必传", requestURI, e.getMessage(),e);
return new Message<>(Message.FAIL, "请求的对象参数校验异常");
}
/**
* 请求方式不支持
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Message<Void> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址 '{}',不支持'{}' 请求", requestURI, e.getMethod(),e);
return new Message<>(HttpStatus.METHOD_NOT_ALLOWED.value(),HttpStatus.METHOD_NOT_ALLOWED.getReasonPhrase());
}
/**
* 参数不正确
*/
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public Message<Void> methodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
String error = String.format("%s 应该是 %s 类型", e.getName(), e.getRequiredType().getSimpleName());
log.error("请求地址'{}',{},参数类型不正确", requestURI,error,e);
return new Message<>(Message.FAIL, "参数类型不正确");
}
/**
* 系统异常
*/
@ExceptionHandler(Exception.class)
public Message<Void> handleException(Exception e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}',发生系统异常.", requestURI, e);
return new Message<>(Message.FAIL, HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
/**
* 捕获转换类型异常
* @param e
* @return
*/
@ExceptionHandler(UnexpectedTypeException.class)
public Message<String> unexpectedTypeHandler(UnexpectedTypeException e)
{
log.error("类型转换错误:{}",e.getMessage(), e);
return new Message<>(HttpStatus.INTERNAL_SERVER_ERROR.value(),e.getMessage());
}
/**
* 捕获转换类型异常
* @param e
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Message<String> methodArgumentNotValidException(MethodArgumentNotValidException e)
{
BindingResult bindingResult = e.getBindingResult();
List<ObjectError> errors = bindingResult.getAllErrors();
log.error("参数验证异常:{}",e.getMessage(), e);
if (!errors.isEmpty()) {
// 只显示第一个错误信息
return new Message<>(HttpStatus.BAD_REQUEST.value(), errors.get(0).getDefaultMessage());
}
return new Message<>(HttpStatus.BAD_REQUEST.value(),"MethodArgumentNotValid");
}
// 运行时异常
@ExceptionHandler(RuntimeException.class)
public Message<String> runtimeExceptionHandler(RuntimeException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}',捕获运行时异常'{}'", requestURI, e.getMessage(),e);
return new Message<>(Message.FAIL, e.getMessage());
}
// 系统级别异常
@ExceptionHandler(Throwable.class)
public Message<String> throwableExceptionHandler(Throwable e,HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}',捕获系统级别异常'{}'", requestURI,e.getMessage(),e);
return new Message<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
}
/**
* IllegalArgumentException 捕获转换类型异常
* @param e
* @return
*/
@ExceptionHandler(IllegalArgumentException.class)
public Message<String> illegalArgumentException(IllegalArgumentException e)
{
String message = e.getMessage();
log.error("IllegalArgumentException:{}",e.getMessage(),e);
if (Objects.nonNull(message)) {
//错误信息
return new Message<>(HttpStatus.BAD_REQUEST.value(),message);
}
return new Message<>(HttpStatus.BAD_REQUEST.value(),"error");
}
/**
* InvalidFormatException 捕获转换类型异常
* @param e
* @return
*/
@ExceptionHandler(InvalidFormatException.class)
public Message<String> invalidFormatException(InvalidFormatException e)
{
String message = e.getMessage();
log.error("InvalidFormatException:{}",e.getMessage(),e);
if (Objects.nonNull(message)) {
//错误信息
return new Message<>(HttpStatus.BAD_REQUEST.value(),message);
}
return new Message<>(HttpStatus.BAD_REQUEST.value(),"error");
}
/**
* 自定义验证异常
*/
@ExceptionHandler(BindException.class)
public Message<Void> handleBindException(BindException e) {
BindingResult bindingResult = e.getBindingResult();
List<ObjectError> errors = bindingResult.getAllErrors();
log.error("参数验证异常:{}",e.getMessage(), e);
if (!errors.isEmpty()) {
// 只显示第一个错误信息
return new Message<>(HttpStatus.BAD_REQUEST.value(), errors.get(0).getDefaultMessage());
}
return new Message<>(HttpStatus.BAD_REQUEST.value(),"MethodArgumentNotValid");
}
/**
* 业务异常处理
* 业务自定义code 与 message
*
*/
@ExceptionHandler(BusinessException.class)
public Message<String> handleBusinessException(BusinessException e) {
log.error("业务自定义异常:{},{}",e.getCode(),e.getMessage(),e);
return new Message<>(e.getCode(),e.getMessage());
}
}
@@ -28,10 +28,6 @@ import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.web.context.support.WebApplicationContextUtils;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import java.sql.Connection;
@@ -47,11 +43,13 @@ import java.util.Iterator;
public class InitializeContext extends HttpServlet {
private static final Logger logger = LoggerFactory.getLogger(InitializeContext.class);
private static final long serialVersionUID = -797399138268601444L;
private static final String LOCALE_RESOLVER_BEAN= "localeResolver";
private static final String COOKIE_LOCALE_RESOLVER_BEAN = "cookieLocaleResolver";
ApplicationContext applicationContext;
final ApplicationContext applicationContext;
@Override
public void init(ServletConfig config) throws ServletException {
public void init() {
WebContext.init(applicationContext);
@@ -69,18 +67,13 @@ public class InitializeContext extends HttpServlet {
/**
* InitApplicationContext.
*/
public InitializeContext() {
this.applicationContext =
WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
}
public InitializeContext(ConfigurableApplicationContext applicationContext) {
if(applicationContext.containsBean("localeResolver") &&
applicationContext.containsBean("cookieLocaleResolver")) {
if(applicationContext.containsBean(LOCALE_RESOLVER_BEAN) &&
applicationContext.containsBean(COOKIE_LOCALE_RESOLVER_BEAN)) {
BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry)applicationContext.getBeanFactory();
beanFactory.removeBeanDefinition("localeResolver");
beanFactory.registerBeanDefinition("localeResolver",
beanFactory.getBeanDefinition("cookieLocaleResolver"));
beanFactory.removeBeanDefinition(LOCALE_RESOLVER_BEAN);
beanFactory.registerBeanDefinition(LOCALE_RESOLVER_BEAN,
beanFactory.getBeanDefinition(COOKIE_LOCALE_RESOLVER_BEAN));
logger.debug("cookieLocaleResolver replaced localeResolver.");
}
this.applicationContext = applicationContext;
@@ -98,8 +91,8 @@ public class InitializeContext extends HttpServlet {
DatabaseMetaData databaseMetaData = connection.getMetaData();
ApplicationConfig.setDatabaseProduct(databaseMetaData.getDatabaseProductName());
logger.info("DatabaseProductName : {}", databaseMetaData.getDatabaseProductName());
logger.info("DatabaseProductVersion: {}" ,databaseMetaData.getDatabaseProductVersion());
logger.info("DatabaseProductName : {}", databaseMetaData.getDatabaseProductName());
logger.info("DatabaseProductVersion : {}" ,databaseMetaData.getDatabaseProductVersion());
logger.trace("DatabaseMajorVersion : {}" , databaseMetaData.getDatabaseMajorVersion());
logger.trace("DatabaseMinorVersion : {}" ,databaseMetaData.getDatabaseMinorVersion());
logger.trace("supportsTransactions : {}" , databaseMetaData.supportsTransactions());
@@ -111,8 +104,8 @@ public class InitializeContext extends HttpServlet {
logger.trace("DriverName : {}" ,databaseMetaData.getDriverName());
logger.trace("DriverVersion : {}" ,databaseMetaData.getDriverVersion());
logger.info("");
logger.info("DBMS URL : {}" ,databaseMetaData.getURL());
logger.info("UserName : {}" ,databaseMetaData.getUserName());
logger.info("DBMS URL : {}" ,databaseMetaData.getURL());
logger.info("UserName : {}" ,databaseMetaData.getUserName());
logger.info(WebConstants.DELIMITER);
} catch (SQLException e) {
@@ -32,7 +32,7 @@ public class WebConstants {
public static final String CURRENT_INST = "current_inst";
public final static String INST_COOKIE_NAME = "mxk_inst";
public static final String INST_COOKIE_NAME = "mxk_inst";
// SPRING_SECURITY_SAVED_REQUEST
public static final String FIRST_SAVED_REQUEST_PARAMETER
@@ -456,12 +456,9 @@ public final class WebContext {
* @return
*/
public static boolean captchaValid(String captcha) {
if (captcha == null || !captcha
.equals(WebContext.getSession().getAttribute(
WebConstants.KAPTCHA_SESSION_KEY).toString())) {
return false;
}
return true;
return (captcha != null &&
captcha.equals(WebContext.getSession().getAttribute(
WebConstants.KAPTCHA_SESSION_KEY).toString()));
}
/**
@@ -493,7 +490,7 @@ public final class WebContext {
String message = code;
try {
message = getApplicationContext().getMessage(
code.toString(),
code,
filedValues,
getLocale());
} catch (Exception e) {
@@ -1,90 +0,0 @@
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.web;
import java.io.IOException;
import org.apache.commons.lang3.StringUtils;
import org.dromara.maxkey.configuration.ApplicationConfig;
import org.dromara.maxkey.entity.Institutions;
import org.dromara.maxkey.persistence.repository.InstitutionsRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.GenericFilterBean;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
public class WebInstRequestFilter extends GenericFilterBean {
final static Logger _logger = LoggerFactory.getLogger(GenericFilterBean.class);
public final static String HEADER_HOST = "host";
public final static String HEADER_HOSTNAME = "hostname";
public final static String HEADER_ORIGIN = "Origin";
InstitutionsRepository institutionsRepository;
ApplicationConfig applicationConfig;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
_logger.trace("WebInstRequestFilter");
HttpServletRequest request= ((HttpServletRequest)servletRequest);
if(request.getSession().getAttribute(WebConstants.CURRENT_INST) == null) {
if(_logger.isTraceEnabled()) {WebContext.printRequest(request);}
String host = request.getHeader(HEADER_HOSTNAME);
_logger.trace("hostname {}",host);
if(StringUtils.isEmpty(host)) {
host = request.getHeader(HEADER_HOST);
_logger.trace("host {}",host);
}
if(StringUtils.isEmpty(host)) {
host = applicationConfig.getDomainName();
_logger.trace("config domain {}",host);
}
if(host.indexOf(":")> -1 ) {
host = host.split(":")[0];
_logger.trace("domain split {}",host);
}
Institutions institution = institutionsRepository.get(host);
_logger.trace("{}" ,institution);
request.getSession().setAttribute(WebConstants.CURRENT_INST, institution);
String origin = request.getHeader(HEADER_ORIGIN);
if(StringUtils.isEmpty(origin)) {
origin = applicationConfig.getFrontendUri();
}
}
chain.doFilter(servletRequest, servletResponse);
}
public WebInstRequestFilter(InstitutionsRepository institutionsRepository,ApplicationConfig applicationConfig) {
super();
this.institutionsRepository = institutionsRepository;
this.applicationConfig = applicationConfig;
}
}
@@ -1,103 +0,0 @@
/*
* Copyright [2021] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.maxkey.web;
import java.io.IOException;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.text.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.GenericFilterBean;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
public class WebXssRequestFilter extends GenericFilterBean {
final static Logger _logger = LoggerFactory.getLogger(GenericFilterBean.class);
final static ConcurrentHashMap <String,String> skipUrlMap = new ConcurrentHashMap <String,String>();
final static ConcurrentHashMap <String,String> skipParameterName = new ConcurrentHashMap <String,String>();
static {
//add or update
skipUrlMap.put("/notices/add", "/notices/add");
skipUrlMap.put("/notices/update", "/notices/update");
skipUrlMap.put("/institutions/update","/institutions/update");
skipUrlMap.put("/localization/update","/localization/update");
skipUrlMap.put("/apps/updateExtendAttr","/apps/updateExtendAttr");
//authz
skipUrlMap.put("/authz/cas", "/authz/cas");
skipUrlMap.put("/authz/cas/", "/authz/cas/");
skipUrlMap.put("/authz/cas/login", "/authz/cas/login");
skipUrlMap.put("/authz/oauth/v20/authorize", "/authz/oauth/v20/authorize");
//TENCENT_IOA
skipUrlMap.put("/oauth2/authorize", "/oauth2/authorize");
skipParameterName.put("relatedPassword", "relatedPassword");
skipParameterName.put("oldPassword", "oldPassword");
skipParameterName.put("password", "password");
skipParameterName.put("confirmpassword", "confirmpassword");
skipParameterName.put("credentials", "credentials");
skipParameterName.put("clientSecret", "clientSecret");
skipParameterName.put("appSecret", "appSecret");
skipParameterName.put("sharedSecret", "sharedSecret");
skipParameterName.put("secret", "secret");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
_logger.trace("WebXssRequestFilter");
boolean isWebXss = false;
HttpServletRequest request= ((HttpServletRequest)servletRequest);
if(_logger.isTraceEnabled()) {WebContext.printRequest(request);}
if(skipUrlMap.containsKey(request.getRequestURI().substring(request.getContextPath().length()))) {
isWebXss = false;
}else {
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String key = (String) parameterNames.nextElement();
if(skipParameterName.containsKey(key)) {continue;}
String value = request.getParameter(key);
_logger.trace("parameter name "+key +" , value " + value);
String tempValue = value;
if(!StringEscapeUtils.escapeHtml4(tempValue).equals(value)
||tempValue.toLowerCase().indexOf("script")>-1
||tempValue.toLowerCase().replace(" ", "").indexOf("eval(")>-1) {
isWebXss = true;
_logger.error("parameter name "+key +" , value " + value
+ ", contains dangerous content ! ");
break;
}
}
}
if(!isWebXss) {
chain.doFilter(request, response);
}
}
}
@@ -27,7 +27,6 @@ import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import org.dromara.maxkey.persistence.repository.LocalizationRepository;
import org.dromara.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -51,9 +50,6 @@ public class LocaleTagDirective implements TemplateDirectiveModel {
@Autowired
private HttpServletRequest request;
@Autowired
LocalizationRepository localizationService;
@SuppressWarnings("rawtypes")
@Override
public void execute(Environment env,