Skip to content

Commit

Permalink
2270: WIP - adding postgresql
Browse files Browse the repository at this point in the history
  • Loading branch information
DarioGii committed Dec 4, 2024
1 parent b7da84d commit a4e2b86
Show file tree
Hide file tree
Showing 9 changed files with 103 additions and 29 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ dependencies {

implementation 'com.unboundid.product.scim2:scim2-sdk-client:2.3.5'
// Don't upgrade h2database
runtimeOnly "com.h2database:h2:2.3.232"
runtimeOnly "org.postgresql:postgresql:42.7.4"
constraints {
implementation "org.opensaml:opensaml-core:$openSamlVersion"
implementation "org.opensaml:opensaml-saml-api:$openSamlVersion"
Expand Down
60 changes: 60 additions & 0 deletions src/main/java/stirling/software/SPDF/SPdfApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
Expand Down Expand Up @@ -67,6 +72,61 @@ private static boolean isPortAvailable(int port) {
}
}

@PostConstruct
public void initDB() {
Connection connection = null;
Statement statement = null;
try {
logger.debug("Creating database...");
ApplicationProperties.Datasource datasource =
applicationProperties.getSystem().getDatasource();

if (datasource != null) {
connection =
DriverManager.getConnection(
datasource.getUrl(),
datasource.getUsername(),
datasource.getPassword());
statement = connection.createStatement();
statement.executeQuery(
"SELECT count(*) FROM pg_database WHERE datname = 'database_name'");
ResultSet resultSet = statement.getResultSet();
resultSet.next();
int count = resultSet.getInt(1);

if (count <= 0) {
statement.executeUpdate("CREATE DATABASE stirling-pdf-DB");
statement.executeUpdate(
"CREATE ROLE "
+ datasource.getUsername()
+ " ADMIN WITH PASSWORD '"
+ datasource.getPassword()
+ "'");
statement.executeUpdate("SET ROLE " + datasource.getUsername());
logger.debug("Database created.");
} else {
logger.debug("Database already exists.");
}
}

} catch (SQLException e) {
logger.error(e.toString());
} finally {
try {
if (statement != null) {
statement.close();
logger.debug("Closed Statement.");
}
if (connection != null) {
logger.debug("Closed Connection.");
connection.close();
}
} catch (SQLException e) {
logger.error(e.toString());
}
}
}

@PostConstruct
public void init() {
baseUrlStatic = this.baseUrl;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public class InitialSecuritySetup {

@Autowired private ApplicationProperties applicationProperties;

// todo: wip add Postgres here
@Autowired private DatabaseBackupInterface databaseBackupHelper;

@PostConstruct
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package stirling.software.SPDF.config.security;

import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.*;

Expand All @@ -13,7 +12,6 @@
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.Resource;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
Expand All @@ -32,35 +30,21 @@
import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
import org.springframework.security.saml2.core.Saml2X509Credential;
import org.springframework.security.saml2.core.Saml2X509Credential.Saml2X509CredentialType;
import org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest;
import org.springframework.security.saml2.provider.service.authentication.OpenSaml4AuthenticationProvider;
import org.springframework.security.saml2.provider.service.registration.InMemoryRelyingPartyRegistrationRepository;
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration;
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository;
import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding;
import org.springframework.security.saml2.provider.service.web.HttpSessionSaml2AuthenticationRequestRepository;
import org.springframework.security.saml2.provider.service.web.Saml2AuthenticationRequestRepository;
import org.springframework.security.saml2.provider.service.web.authentication.OpenSaml4AuthenticationRequestResolver;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.web.context.SecurityContextHolderFilter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler;
import org.springframework.security.web.savedrequest.NullRequestCache;
import org.springframework.security.web.session.ForceEagerSessionCreationFilter;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.security.web.session.SessionManagementFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.security.oauth2.CustomOAuth2AuthenticationFailureHandler;
import stirling.software.SPDF.config.security.oauth2.CustomOAuth2AuthenticationSuccessHandler;
Expand Down Expand Up @@ -163,7 +147,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.sessionManagement(
sessionManagement ->
sessionManagement
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.maximumSessions(10)
.maxSessionsPreventsLogin(false)
.sessionRegistry(sessionRegistry)
Expand Down Expand Up @@ -287,7 +271,6 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
relyingPartyRegistrations())
.authenticationManager(
new ProviderManager(authenticationProvider))

.successHandler(
new CustomSaml2AuthenticationSuccessHandler(
loginAttemptService,
Expand Down Expand Up @@ -452,7 +435,7 @@ private Optional<ClientRegistration> oidcClientRegistration() {
.clientName("OIDC")
.build());
}

@Bean
@ConditionalOnProperty(
name = "security.saml2.enabled",
Expand Down Expand Up @@ -506,7 +489,7 @@ public OpenSaml4AuthenticationRequestResolver authenticationRequestResolver(

AuthnRequest authnRequest = customizer.getAuthnRequest();
log.debug("AuthnRequest ID: {}", authnRequest.getID());

if (authnRequest.getID() == null) {
authnRequest.setID("ARQ" + UUID.randomUUID().toString());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ public boolean importDatabase() {
return executeDatabaseScript(Paths.get(backupList.get(0).getFilePath()));
}

// fixMe: Needs to check the type of DB before executing script
@Override
public void exportDatabase() throws IOException {
// Check if the backup directory exists, and create it if it does not
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ public ResponseEntity<byte[]> addStamp(@ModelAttribute AddStampRequest request)
return WebResponseUtils.pdfDocToWebResponse(
document,
Filenames.toSimpleFileName(pdfFile.getOriginalFilename())
.replaceFirst("[.][^.]+$", "")
.replaceFirst("[.][^.]+$", "")
+ "_stamped.pdf");
}

Expand Down Expand Up @@ -191,7 +191,7 @@ private void addTextStamp(
String fileExtension = resourceDir.substring(resourceDir.lastIndexOf("."));
File tempFile = Files.createTempFile("NotoSansFont", fileExtension).toFile();
try (InputStream is = classPathResource.getInputStream();
FileOutputStream os = new FileOutputStream(tempFile)) {
FileOutputStream os = new FileOutputStream(tempFile)) {
IOUtils.copy(is, os);
font = PDType0Font.load(document, tempFile);
} finally {
Expand Down Expand Up @@ -339,4 +339,4 @@ private float calculateTextWidth(String text, PDFont font, float fontSize) throw
private float calculateTextCapHeight(PDFont font, float fontSize) {
return font.getFontDescriptor().getCapHeight() / 1000 * fontSize;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.Driver;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
Expand Down Expand Up @@ -245,6 +246,28 @@ public static class System {
private String tessdataDir;
private Boolean enableAlphaFunctionality;
private String enableAnalytics;
private Datasource datasource;
}

@Data
public static class Datasource {
private String url;
private Driver driver;
private String username;
private String password;
}

public enum Driver {
H2("h2"),
POSTGRESQL("postgresql"),
ORACLE("oracle"),
MY_SQL("mysql");

private final String driverName;

Driver(String driverName) {
this.driverName = driverName;
}
}

@Data
Expand Down
11 changes: 6 additions & 5 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,14 @@ spring.mvc.async.request-timeout=${SYSTEM_CONNECTIONTIMEOUTMILLISECONDS:1200000}
#spring.thymeleaf.prefix=file:/customFiles/templates/,classpath:/templates/
#spring.thymeleaf.cache=false

spring.datasource.url=jdbc:h2:file:./configs/stirling-pdf-DB-2.3.232;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.url=jdbc:postgresql://localhost:5432/stirling-pdf-DB
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.username=postgres
spring.datasource.password=
spring.h2.console.enabled=false
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
server.servlet.session.timeout: 30m
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
server.servlet.session.timeout=30m
# Change the default URL path for OpenAPI JSON
springdoc.api-docs.path=/v1/api-docs

Expand Down
5 changes: 5 additions & 0 deletions src/main/resources/settings.yml.template
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,11 @@ system:
customHTMLFiles: false # enable to have files placed in /customFiles/templates override the existing template HTML files
tessdataDir: /usr/share/tessdata # path to the directory containing the Tessdata files. This setting is relevant for Windows systems. For Windows users, this path should be adjusted to point to the appropriate directory where the Tessdata files are stored.
enableAnalytics: undefined # set to 'true' to enable analytics, set to 'false' to disable analytics; for enterprise users, this is set to true
datasource:
url: jdbc:postgresql://localhost:5432/stirling-pdf-DB
driver: postgresql
username: postgres
password:

ui:
appName: '' # application's visible name
Expand Down

0 comments on commit a4e2b86

Please sign in to comment.