Skip to content

Commit

Permalink
2270: rebasing from main
Browse files Browse the repository at this point in the history
  • Loading branch information
DarioGii committed Dec 20, 2024
1 parent f072de8 commit d0e3ae9
Show file tree
Hide file tree
Showing 10 changed files with 87 additions and 68 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package stirling.software.SPDF.config.interfaces;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import stirling.software.SPDF.model.provider.UnsupportedProviderException;
import stirling.software.SPDF.utils.FileInfo;

public interface DatabaseInterface {
void exportDatabase() throws IOException;
void exportDatabase() throws SQLException, UnsupportedProviderException;

List<FileInfo> getBackupList();
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package stirling.software.SPDF.config.security;

import java.io.IOException;
import java.sql.SQLException;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -11,6 +11,7 @@
import stirling.software.SPDF.config.interfaces.DatabaseInterface;
import stirling.software.SPDF.model.ApplicationProperties;
import stirling.software.SPDF.model.Role;
import stirling.software.SPDF.model.provider.UnsupportedProviderException;

@Slf4j
@Component
Expand All @@ -31,13 +32,13 @@ public void init() {

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

private void initializeAdminUser() throws IOException {
private void initializeAdminUser() throws SQLException, UnsupportedProviderException {
String initialUsername =
applicationProperties.getSecurity().getInitialLogin().getUsername();
String initialPassword =
Expand All @@ -55,7 +56,7 @@ private void initializeAdminUser() throws IOException {
}
}

private void createDefaultAdminUser() throws IOException {
private void createDefaultAdminUser() throws SQLException, UnsupportedProviderException {
String defaultUsername = "admin";
String defaultPassword = "stirling";

Expand All @@ -65,7 +66,8 @@ private void createDefaultAdminUser() throws IOException {
}
}

private void initializeInternalApiUser() throws IllegalArgumentException, IOException {
private void initializeInternalApiUser()
throws IllegalArgumentException, SQLException, UnsupportedProviderException {
if (!userService.usernameExistsIgnoreCase(Role.INTERNAL_API_USER.getRoleId())) {
userService.saveUser(
Role.INTERNAL_API_USER.getRoleId(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package stirling.software.SPDF.config.security;

import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

Expand All @@ -25,11 +25,8 @@
import stirling.software.SPDF.config.security.saml2.CustomSaml2AuthenticatedPrincipal;
import stirling.software.SPDF.config.security.session.SessionPersistentRegistry;
import stirling.software.SPDF.controller.api.pipeline.UserServiceInterface;
import stirling.software.SPDF.model.ApplicationProperties;
import stirling.software.SPDF.model.AuthenticationType;
import stirling.software.SPDF.model.Authority;
import stirling.software.SPDF.model.Role;
import stirling.software.SPDF.model.User;
import stirling.software.SPDF.model.*;
import stirling.software.SPDF.model.provider.UnsupportedProviderException;
import stirling.software.SPDF.repository.AuthorityRepository;
import stirling.software.SPDF.repository.UserRepository;

Expand Down Expand Up @@ -64,7 +61,7 @@ public void migrateOauth2ToSSO() {

// Handle OAUTH2 login and user auto creation.
public boolean processSSOPostLogin(String username, boolean autoCreateUser)
throws IllegalArgumentException, IOException {
throws IllegalArgumentException, SQLException, UnsupportedProviderException {
if (!isUsernameValid(username)) {
return false;
}
Expand Down Expand Up @@ -151,12 +148,12 @@ public boolean validateApiKeyForUser(String username, String apiKey) {
}

public void saveUser(String username, AuthenticationType authenticationType)
throws IllegalArgumentException, IOException {
throws IllegalArgumentException, SQLException, UnsupportedProviderException {
saveUser(username, authenticationType, Role.USER.getRoleId());
}

public void saveUser(String username, AuthenticationType authenticationType, String role)
throws IllegalArgumentException, IOException {
throws IllegalArgumentException, SQLException, UnsupportedProviderException {
if (!isUsernameValid(username)) {
throw new IllegalArgumentException(getInvalidUsernameMessage());
}
Expand All @@ -171,7 +168,7 @@ public void saveUser(String username, AuthenticationType authenticationType, Str
}

public void saveUser(String username, String password)
throws IllegalArgumentException, IOException {
throws IllegalArgumentException, SQLException, UnsupportedProviderException {
if (!isUsernameValid(username)) {
throw new IllegalArgumentException(getInvalidUsernameMessage());
}
Expand All @@ -185,7 +182,7 @@ public void saveUser(String username, String password)
}

public void saveUser(String username, String password, String role, boolean firstLogin)
throws IllegalArgumentException, IOException {
throws IllegalArgumentException, SQLException, UnsupportedProviderException {
if (!isUsernameValid(username)) {
throw new IllegalArgumentException(getInvalidUsernameMessage());
}
Expand All @@ -201,7 +198,7 @@ public void saveUser(String username, String password, String role, boolean firs
}

public void saveUser(String username, String password, String role)
throws IllegalArgumentException, IOException {
throws IllegalArgumentException, SQLException, UnsupportedProviderException {
saveUser(username, password, role, false);
}

Expand Down Expand Up @@ -235,7 +232,7 @@ public boolean hasUsers() {
}

public void updateUserSettings(String username, Map<String, String> updates)
throws IOException {
throws SQLException, UnsupportedProviderException {
Optional<User> userOpt = findByUsernameIgnoreCaseWithSettings(username);
if (userOpt.isPresent()) {
User user = userOpt.get();
Expand Down Expand Up @@ -270,7 +267,7 @@ public Authority findRole(User user) {
}

public void changeUsername(User user, String newUsername)
throws IllegalArgumentException, IOException {
throws IllegalArgumentException, SQLException, UnsupportedProviderException {
if (!isUsernameValid(newUsername)) {
throw new IllegalArgumentException(getInvalidUsernameMessage());
}
Expand All @@ -279,26 +276,30 @@ public void changeUsername(User user, String newUsername)
databaseService.exportDatabase();
}

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

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

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

public void changeUserEnabled(User user, Boolean enbeled) throws IOException {
public void changeUserEnabled(User user, Boolean enbeled)
throws SQLException, UnsupportedProviderException {
user.setEnabled(enbeled);
userRepository.save(user);
databaseService.exportDatabase();
Expand Down Expand Up @@ -391,7 +392,8 @@ public String getCurrentUsername() {
}

@Transactional
public void syncCustomApiUser(String customApiKey) throws IOException {
public void syncCustomApiUser(String customApiKey)
throws SQLException, UnsupportedProviderException {
if (customApiKey == null || customApiKey.trim().length() == 0) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.interfaces.DatabaseInterface;
import stirling.software.SPDF.model.ApplicationProperties;
import stirling.software.SPDF.model.provider.UnsupportedProviderException;
import stirling.software.SPDF.utils.FileInfo;

Expand Down Expand Up @@ -104,7 +105,7 @@ private void importDatabaseFromUI(Path tempTemplatePath) throws IOException {
}

@Override
public void exportDatabase() {
public void exportDatabase() throws SQLException, UnsupportedProviderException {
// Filter and delete old backups if there are more than 5
List<FileInfo> filteredBackupList =
this.getBackupList().stream()
Expand All @@ -127,8 +128,10 @@ public void exportDatabase() {
log.info("Database export completed: {}", insertOutputFilePath);
} catch (SQLException | UnsupportedProviderException e) {
log.error("Error during database export: {}", e.getMessage(), e);
throw e;
} catch (ScriptException e) {
log.error("Error during database export: File {} not found", insertOutputFilePath);
throw e;
}
}

Expand All @@ -149,17 +152,26 @@ private static void deleteOldestBackup(List<FileInfo> filteredBackupList) {
// Retrieves the H2 database version.
public String getH2Version() {
String version = "Unknown";
try (Connection conn = databaseConfig.connection()) {
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT H2VERSION() AS version")) {
if (rs.next()) {
version = rs.getString("version");
log.info("H2 Database Version: {}", version);

if (databaseConfig
.getApplicationProperties()
.getSystem()
.getDatasource()
.getType()
.equals(ApplicationProperties.Driver.H2.name())) {
try (Connection conn = databaseConfig.connection()) {
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT H2VERSION() AS version")) {
if (rs.next()) {
version = rs.getString("version");
log.info("H2 Database Version: {}", version);
}
}
} catch (SQLException | UnsupportedProviderException e) {
log.error("Error retrieving H2 version: {}", e.getMessage(), e);
}
} catch (SQLException | UnsupportedProviderException e) {
log.error("Error retrieving H2 version: {}", e.getMessage(), e);
}

return version;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
package stirling.software.SPDF.config.security.database;

import java.io.IOException;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import stirling.software.SPDF.model.provider.UnsupportedProviderException;

@Component
public class ScheduledTasks {

@Autowired private DatabaseService databaseService;

@Scheduled(cron = "0 0 0 * * ?")
public void performBackup() throws IOException {
public void performBackup() throws SQLException, UnsupportedProviderException {
databaseService.exportDatabase();
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package stirling.software.SPDF.config.security.oauth2;

import java.io.IOException;
import java.sql.SQLException;

import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.Authentication;
Expand All @@ -18,6 +19,7 @@
import stirling.software.SPDF.model.ApplicationProperties;
import stirling.software.SPDF.model.ApplicationProperties.Security.OAUTH2;
import stirling.software.SPDF.model.AuthenticationType;
import stirling.software.SPDF.model.provider.UnsupportedProviderException;
import stirling.software.SPDF.utils.RequestUriUtils;

public class CustomOAuth2AuthenticationSuccessHandler
Expand Down Expand Up @@ -97,10 +99,8 @@ public void onAuthenticationSuccess(
userService.processSSOPostLogin(username, oAuth.getAutoCreateUser());
}
response.sendRedirect(contextPath + "/");
return;
} catch (IllegalArgumentException e) {
} catch (IllegalArgumentException | SQLException | UnsupportedProviderException e) {
response.sendRedirect(contextPath + "/logout?invalidUsername=true");
return;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package stirling.software.SPDF.config.security.saml2;

import java.io.IOException;
import java.sql.SQLException;

import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.Authentication;
Expand All @@ -18,6 +19,7 @@
import stirling.software.SPDF.model.ApplicationProperties;
import stirling.software.SPDF.model.ApplicationProperties.Security.SAML2;
import stirling.software.SPDF.model.AuthenticationType;
import stirling.software.SPDF.model.provider.UnsupportedProviderException;
import stirling.software.SPDF.utils.RequestUriUtils;

@AllArgsConstructor
Expand Down Expand Up @@ -115,6 +117,9 @@ public void onAuthenticationSuccess(
username);
response.sendRedirect(contextPath + "/logout?invalidUsername=true");
return;
} catch (SQLException | UnsupportedProviderException e) {
log.error("Error, redirecting to logout", e);
response.sendRedirect(contextPath + "/logout?error=true");
}
}
} else {
Expand Down
Loading

0 comments on commit d0e3ae9

Please sign in to comment.