Skip to content

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
wip
  • Loading branch information
DarioGii committed Dec 10, 2024
1 parent 519e4ff commit 947814a
Show file tree
Hide file tree
Showing 25 changed files with 268 additions and 204 deletions.
2 changes: 1 addition & 1 deletion src/main/java/stirling/software/SPDF/SPdfApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
import stirling.software.SPDF.config.ConfigInitializer;
import stirling.software.SPDF.model.ApplicationProperties;

@SpringBootApplication
@EnableScheduling
@SpringBootApplication
public class SPdfApplication {

private static final Logger logger = LoggerFactory.getLogger(SPdfApplication.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,10 @@

import stirling.software.SPDF.utils.FileInfo;

public interface DatabaseBackupInterface {
public interface DatabaseInterface {
void setAdminUser();

void exportDatabase() throws IOException;

void importDatabase();

boolean hasBackup();

List<FileInfo> getBackupList();
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.interfaces.DatabaseBackupInterface;
import stirling.software.SPDF.config.interfaces.DatabaseInterface;
import stirling.software.SPDF.model.ApplicationProperties;
import stirling.software.SPDF.model.Role;

@Component
@Slf4j
@Component
public class InitialSecuritySetup {

public static final String POSTGRES = "postgres";
Expand All @@ -22,21 +22,26 @@ public class InitialSecuritySetup {

@Autowired private ApplicationProperties applicationProperties;

@Autowired private DatabaseBackupInterface databaseBackupService;
@Autowired private DatabaseInterface databaseService;

@PostConstruct
public void init() throws IllegalArgumentException, IOException {
if (applicationProperties.getSystem().getEnvironmentName().equals(POSTGRES)) {
log.debug("PostgreSQL configuration settings detected. Creating admin user");
databaseBackupService.setAdminUser();
public void init() {
if (applicationProperties.getSystem().getSpringProfilesActive().equals(POSTGRES)) {
log.debug("Postgres configuration settings detected. Creating admin user");
databaseService.setAdminUser();
}

if (!userService.hasUsers()) {
initializeAdminUser();
}
try {
if (!userService.hasUsers()) {
initializeAdminUser();
}

userService.migrateOauth2ToSSO();
initializeInternalApiUser();
userService.migrateOauth2ToSSO();
initializeInternalApiUser();
} catch (IllegalArgumentException | IOException e) {
log.error("Failed to initialize security setup.", e);
System.exit(1);
}
}

private void initializeAdminUser() throws IOException {
Expand All @@ -48,25 +53,22 @@ private void initializeAdminUser() throws IOException {
&& !initialUsername.isEmpty()
&& initialPassword != null
&& !initialPassword.isEmpty()
&& !userService.findByUsernameIgnoreCase(initialUsername).isPresent()) {
try {
userService.saveUser(initialUsername, initialPassword, Role.ADMIN.getRoleId());
log.info("Admin user created: " + initialUsername);
} catch (IllegalArgumentException e) {
log.error("Failed to initialize security setup", e);
System.exit(1);
}
&& userService.findByUsernameIgnoreCase(initialUsername).isEmpty()) {

userService.saveUser(initialUsername, initialPassword, Role.ADMIN.getRoleId());
log.info("Admin user created: {}", initialUsername);
} else {
createDefaultAdminUser();
}
}

private void createDefaultAdminUser() throws IllegalArgumentException, IOException {
private void createDefaultAdminUser() throws IOException {
String defaultUsername = "admin";
String defaultPassword = "stirling";
if (!userService.findByUsernameIgnoreCase(defaultUsername).isPresent()) {

if (userService.findByUsernameIgnoreCase(defaultUsername).isEmpty()) {
userService.saveUser(defaultUsername, defaultPassword, Role.ADMIN.getRoleId(), true);
log.info("Default admin user created: " + defaultUsername);
log.info("Default admin user created: {}", defaultUsername);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import org.springframework.transaction.annotation.Transactional;

import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.interfaces.DatabaseBackupInterface;
import stirling.software.SPDF.config.interfaces.DatabaseInterface;
import stirling.software.SPDF.config.security.saml2.CustomSaml2AuthenticatedPrincipal;
import stirling.software.SPDF.config.security.session.SessionPersistentRegistry;
import stirling.software.SPDF.controller.api.pipeline.UserServiceInterface;
Expand All @@ -47,7 +47,7 @@ public class UserService implements UserServiceInterface {

@Autowired private SessionPersistentRegistry sessionRegistry;

@Autowired DatabaseBackupInterface databaseBackupHelper;
@Autowired DatabaseInterface databaseService;

@Autowired ApplicationProperties applicationProperties;

Expand Down Expand Up @@ -167,7 +167,7 @@ public void saveUser(String username, AuthenticationType authenticationType, Str
user.addAuthority(new Authority(role, user));
user.setAuthenticationType(authenticationType);
userRepository.save(user);
databaseBackupHelper.exportDatabase();
databaseService.exportDatabase();
}

public void saveUser(String username, String password)
Expand All @@ -181,7 +181,7 @@ public void saveUser(String username, String password)
user.setEnabled(true);
user.setAuthenticationType(AuthenticationType.WEB);
userRepository.save(user);
databaseBackupHelper.exportDatabase();
databaseService.exportDatabase();
}

public void saveUser(String username, String password, String role, boolean firstLogin)
Expand All @@ -197,7 +197,7 @@ public void saveUser(String username, String password, String role, boolean firs
user.setAuthenticationType(AuthenticationType.WEB);
user.setFirstLogin(firstLogin);
userRepository.save(user);
databaseBackupHelper.exportDatabase();
databaseService.exportDatabase();
}

public void saveUser(String username, String password, String role)
Expand Down Expand Up @@ -249,7 +249,7 @@ public void updateUserSettings(String username, Map<String, String> updates)
user.setSettings(settingsMap);

userRepository.save(user);
databaseBackupHelper.exportDatabase();
databaseService.exportDatabase();
}
}

Expand All @@ -276,32 +276,32 @@ public void changeUsername(User user, String newUsername)
}
user.setUsername(newUsername);
userRepository.save(user);
databaseBackupHelper.exportDatabase();
databaseService.exportDatabase();
}

public void changePassword(User user, String newPassword) throws IOException {
user.setPassword(passwordEncoder.encode(newPassword));
userRepository.save(user);
databaseBackupHelper.exportDatabase();
databaseService.exportDatabase();
}

public void changeFirstUse(User user, boolean firstUse) throws IOException {
user.setFirstLogin(firstUse);
userRepository.save(user);
databaseBackupHelper.exportDatabase();
databaseService.exportDatabase();
}

public void changeRole(User user, String newRole) throws IOException {
Authority userAuthority = this.findRole(user);
userAuthority.setAuthority(newRole);
authorityRepository.save(userAuthority);
databaseBackupHelper.exportDatabase();
databaseService.exportDatabase();
}

public void changeUserEnabled(User user, Boolean enbeled) throws IOException {
user.setEnabled(enbeled);
userRepository.save(user);
databaseBackupHelper.exportDatabase();
databaseService.exportDatabase();
}

public boolean isPasswordCorrect(User user, String currentPassword) {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,35 +1,51 @@
package stirling.software.SPDF.config.security.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import lombok.Getter;
import stirling.software.SPDF.model.ApplicationProperties;
import stirling.software.SPDF.model.exception.UnsupportedDriverException;

@Getter
@Configuration
public class DatabaseConfig {

@Autowired private DataSourceConfig dataSourceConfig;

@Autowired private JpaConfig jpaConfig;
@Autowired private ApplicationProperties applicationProperties;

@Bean
public DataSource dataSource() {
return dataSourceConfig.dataSource();
public Connection connection() throws SQLException {
ApplicationProperties.Datasource datasource =
applicationProperties.getSystem().getDatasource();

DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName(getDriverClassName(datasource.getDriverClassName()));
dataSourceBuilder.url(datasource.getUrl());
dataSourceBuilder.username(datasource.getUsername());
dataSourceBuilder.password(datasource.getPassword());

return dataSourceBuilder.build().getConnection();
}

@Bean
public Connection connection() throws SQLException {
return DriverManager.getConnection(
dataSourceConfig.getUrl(),
dataSourceConfig.getUsername(),
dataSourceConfig.getPassword());
private String getDriverClassName(ApplicationProperties.Driver driverName) {
switch (driverName) {
case POSTGRESQL -> {
return "org.postgresql.Driver";
}
case ORACLE -> {
return "oracle.jdbc.OracleDriver";
}
case MY_SQL -> {
return "com.mysql.cj.jdbc.Driver";
}
default ->
throw new UnsupportedDriverException(
"The database driver " + driverName + " is not supported.");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.PathResource;
Expand All @@ -27,66 +26,34 @@
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.interfaces.DatabaseBackupInterface;
import stirling.software.SPDF.model.exception.BackupNotFoundException;
import stirling.software.SPDF.config.interfaces.DatabaseInterface;
import stirling.software.SPDF.utils.FileInfo;

@Slf4j
@Service
public class DatabaseBackupService implements DatabaseBackupInterface {
public class DatabaseService implements DatabaseInterface {

public static final String BACKUP_PREFIX = "backup_";
public static final String SQL_SUFFIX = ".sql";
private static final Path BACKUP_PATH = Paths.get("configs/db/backup/");
private static final Path PG_ADMIN_SCRIPT_PATH =
Paths.get("src/main/resources/setup_pg_admin_user.sql");

@Autowired private DatabaseConfig databaseConfig;

@Override
public void setAdminUser() {
String adminScript =
"""
DO
$do$
BEGIN
IF EXISTS (
SELECT FROM pg_catalog.pg_roles
WHERE rolname = 'admin') THEN
RAISE NOTICE 'Role "admin" already exists. Skipping.';
ELSE
CREATE USER admin WITH ENCRYPTED PASSWORD 'stirling';
END IF;
END
$do$;
CREATE SCHEMA IF NOT EXISTS stirling_pdf AUTHORIZATION admin;
GRANT ALL PRIVILEGES ON DATABASE postgres TO admin;
ALTER DATABASE postgres SET search_path TO stirling_pdf;
ALTER USER admin SET search_path TO stirling_pdf;
"""
.trim();

try (Connection connection = databaseConfig.connection();
Statement statement = connection.createStatement()) {
statement.execute(adminScript);
} catch (SQLException e) {
String script = Files.readString(PG_ADMIN_SCRIPT_PATH);
statement.execute(script);
} catch (SQLException | IOException e) {
log.error("Error: Failed to create admin user for database", e);
}

log.info("Created admin user for database");
}

@Override
public boolean hasBackup() {
// Check if there is at least one backup
try (Stream<Path> entries = Files.list(BACKUP_PATH)) {
return entries.findFirst().isPresent();
} catch (IOException e) {
log.error("Error reading backup directory: {}", e.getMessage(), e);
throw new RuntimeException(e);
}
}

@Override
public List<FileInfo> getBackupList() {
List<FileInfo> backupFiles = new ArrayList<>();
Expand Down Expand Up @@ -150,16 +117,6 @@ private void importDatabaseFromUI(Path tempTemplatePath) throws IOException {
Files.deleteIfExists(tempTemplatePath);
}

@Override
public void importDatabase() {
if (!hasBackup()) throw new BackupNotFoundException("No backups found");

List<FileInfo> backupList = getBackupList();
backupList.sort(Comparator.comparing(FileInfo::getModificationDate).reversed());
executeDatabaseScript(Paths.get(backupList.get(0).getFilePath()));
}

// fixMe: Check the type of DB before executing script
@Override
public void exportDatabase() {
// Filter and delete old backups if there are more than 5
Expand Down
Loading

0 comments on commit 947814a

Please sign in to comment.