configs and app setup stuff

This commit is contained in:
Anthony Stirling
2023-08-26 17:30:49 +01:00
parent 2053a6950d
commit d749b63549
28 changed files with 875 additions and 179 deletions

View File

@@ -1,34 +1,30 @@
package stirling.software.SPDF.config;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import stirling.software.SPDF.utils.PropertyConfigs;
import stirling.software.SPDF.model.ApplicationProperties;
@Configuration
public class AppConfig {
@Value("${login.enabled:false}")
private boolean defaultLoginEnabled;
@Value("${ui.homeName:Stirling PDF}")
private String defaultAppName;
@Value("${ui.homeDescription:null}")
private String defaultHomeText;
@Value("${ui.navbarName:Stirling PDF}")
private String defaultNavBarText;
@Autowired
ApplicationProperties applicationProperties;
@Bean(name = "loginEnabled")
public boolean loginEnabled() {
return getBooleanValue("login.enabled", defaultLoginEnabled);
System.out.println(applicationProperties.toString());
return applicationProperties.getSecurity().getEnableLogin();
}
@Bean(name = "appName")
public String appName() {
return getStringValue("APP_HOME_NAME", defaultAppName);
return applicationProperties.getUi().getHomeName();
}
@Bean(name = "appVersion")
@@ -39,30 +35,14 @@ public class AppConfig {
@Bean(name = "homeText")
public String homeText() {
return getStringValue("APP_HOME_DESCRIPTION", defaultHomeText);
return applicationProperties.getUi().getHomeDescription();
}
@Bean(name = "navBarText")
public String navBarText() {
String navBarText = getStringValue("APP_NAVBAR_NAME", null);
if (navBarText == null) {
navBarText = getStringValue("APP_HOME_NAME", defaultNavBarText);
}
return navBarText;
}
private boolean getBooleanValue(String key, boolean defaultValue) {
String value = System.getProperty(key);
if (value == null)
value = System.getenv(key);
return (value != null) ? Boolean.valueOf(value) : defaultValue;
}
private String getStringValue(String key, String defaultValue) {
String value = System.getProperty(key);
if (value == null)
value = System.getenv(key);
return (value != null) ? value : defaultValue;
String defaultNavBar = applicationProperties.getUi().getNavbarName() != null ? applicationProperties.getUi().getNavbarName() : applicationProperties.getUi().getHomeName();
return defaultNavBar;
}
@Bean(name = "rateLimit")

View File

@@ -3,6 +3,7 @@ package stirling.software.SPDF.config;
import java.time.Duration;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
@@ -15,10 +16,14 @@ import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Bucket4j;
import io.github.bucket4j.Refill;
import stirling.software.SPDF.model.ApplicationProperties;
@Configuration
public class Beans implements WebMvcConfigurer {
@Autowired
ApplicationProperties applicationProperties;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
@@ -35,10 +40,9 @@ public class Beans implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
String appLocaleEnv = System.getProperty("APP_LOCALE");
if (appLocaleEnv == null)
appLocaleEnv = System.getenv("APP_LOCALE");
String appLocaleEnv = applicationProperties.getSystem().getDefaultLocale();
Locale defaultLocale = Locale.UK; // Fallback to UK locale if environment variable is not set
if (appLocaleEnv != null && !appLocaleEnv.isEmpty()) {

View File

@@ -0,0 +1,43 @@
package stirling.software.SPDF.config;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
public class ConfigInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
try {
ensureConfigExists();
} catch (IOException e) {
throw new RuntimeException("Failed to initialize application configuration", e);
}
}
public void ensureConfigExists() throws IOException {
// Define the path to the external config directory
Path destPath = Paths.get("configs", "application.yml");
// Check if the file already exists
if (Files.notExists(destPath)) {
// Ensure the destination directory exists
Files.createDirectories(destPath.getParent());
// Copy the resource from classpath to the external directory
try (InputStream in = getClass().getClassLoader().getResourceAsStream("application.yml.template")) {
if (in != null) {
Files.copy(in, destPath);
} else {
throw new FileNotFoundException("Resource file not found: application.yml.template");
}
}
}
}
}

View File

@@ -0,0 +1,23 @@
package stirling.software.SPDF.config;
import java.io.IOException;
import java.util.Properties;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource)
throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(encodedResource.getResource());
Properties properties = factory.getObject();
return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
}
}

View File

@@ -6,6 +6,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;
import stirling.software.SPDF.model.ApplicationProperties;
import stirling.software.SPDF.model.Role;
import java.io.FileNotFoundException;
@@ -20,95 +21,60 @@ import org.springframework.core.io.ClassPathResource;
@Component
public class InitialSetup {
@Autowired
private UserService userService;
@Autowired
private UserService userService;
@PostConstruct
public void init() {
if(!userService.hasUsers()) {
String initialUsername = System.getenv("INITIAL_USERNAME");
String initialPassword = System.getenv("INITIAL_PASSWORD");
if(initialUsername != null && initialPassword != null) {
userService.saveUser(initialUsername, initialPassword, Role.ADMIN.getRoleId());
}
}
}
@PostConstruct
public void init() {
if (!userService.hasUsers()) {
String initialUsername = System.getenv("INITIAL_USERNAME");
String initialPassword = System.getenv("INITIAL_PASSWORD");
if (initialUsername != null && initialPassword != null) {
userService.saveUser(initialUsername, initialPassword, Role.ADMIN.getRoleId());
}
@Value("${AutomaticallyGeneratedDoNotEdit.key:}")
private String secretKey;
}
}
@Autowired
private Environment environment;
public void ensureConfigExists() throws IOException {
// Define the path to the external config directory
Path destPath = Paths.get("configs", "application.yml");
@Autowired
ApplicationProperties applicationProperties;
// Check if the file already exists
if (Files.notExists(destPath)) {
// Ensure the destination directory exists
Files.createDirectories(destPath.getParent());
@PostConstruct
public void initSecretKey() throws IOException {
String secretKey = applicationProperties.getAutomaticallyGenerated().getKey();
if (secretKey == null || secretKey.isEmpty()) {
secretKey = UUID.randomUUID().toString(); // Generating a random UUID as the secret key
saveKeyToConfig(secretKey);
}
}
// Copy the resource from classpath to the external directory
try (InputStream in = getClass().getClassLoader().getResourceAsStream("application.yml.template")) {
if (in != null) {
Files.copy(in, destPath);
} else {
throw new FileNotFoundException("Resource file not found: application.yml.template");
}
}
}
}
private void saveKeyToConfig(String key) throws IOException {
Path path = Paths.get("configs", "application.yml"); // Target the configs/application.yml
List<String> lines = Files.readAllLines(path);
boolean keyFound = false;
@PostConstruct
public void initSecretKey() throws IOException {
ensureConfigExists();
if (secretKey == null || secretKey.isEmpty() || "placeholder".equals(secretKey)) {
secretKey = UUID.randomUUID().toString(); // Generating a random UUID as the secret key
saveKeyToConfig(secretKey);
}
}
// Search for the existing key to replace it or place to add it
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).startsWith("AutomaticallyGenerated:")) {
keyFound = true;
if (i + 1 < lines.size() && lines.get(i + 1).trim().startsWith("key:")) {
lines.set(i + 1, " key: " + key);
break;
} else {
lines.add(i + 1, " key: " + key);
break;
}
}
}
private void saveKeyToConfig(String key) throws IOException {
Path path = Paths.get("configs", "application.yml"); // Target the configs/application.yml
List<String> lines = Files.readAllLines(path);
boolean keyFound = false;
// If the section doesn't exist, append it
if (!keyFound) {
lines.add("# Automatically Generated Settings (Do Not Edit Directly)");
lines.add("AutomaticallyGenerated:");
lines.add(" key: " + key);
}
// Search for the existing key to replace it or place to add it
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).startsWith("AutomaticallyGeneratedDoNotEdit:")) {
keyFound = true;
if (i + 1 < lines.size() && lines.get(i + 1).trim().startsWith("key:")) {
lines.set(i + 1, " key: " + key);
break;
} else {
lines.add(i + 1, " key: " + key);
break;
}
}
}
// If the section doesn't exist, append it
if (!keyFound) {
lines.add("AutomaticallyGeneratedDoNotEdit:");
lines.add(" key: " + key);
}
// Add a comment (if not already added)
if (!lines.get(0).startsWith("# Automatically Generated Settings (Do Not Edit Directly)")) {
lines.add(0, "# Automatically Generated Settings (Do Not Edit Directly)");
}
// Write back to the file
Files.write(path, lines);
}
}
// Write back to the file
Files.write(path, lines);
}
}