This commit is contained in:
Anthony Stirling 2024-06-06 21:59:13 +01:00
parent a3bf7baf35
commit 03150c6462
4 changed files with 83 additions and 79 deletions

View file

@ -7,7 +7,6 @@ import java.net.URISyntaxException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ApplicationContextInitializer;
@ -45,46 +44,47 @@ public class ConfigInitializer
} }
} }
} else { } else {
// Path templatePath = // Path templatePath =
// Paths.get( // Paths.get(
// getClass() // getClass()
// .getClassLoader() // .getClassLoader()
// .getResource("settings.yml.template") // .getResource("settings.yml.template")
// .toURI()); // .toURI());
// Path userPath = Paths.get("configs", "settings.yml"); // Path userPath = Paths.get("configs", "settings.yml");
// //
// List<String> templateLines = Files.readAllLines(templatePath); // List<String> templateLines = Files.readAllLines(templatePath);
// List<String> userLines = // List<String> userLines =
// Files.exists(userPath) ? Files.readAllLines(userPath) : new ArrayList<>(); // Files.exists(userPath) ? Files.readAllLines(userPath) : new
// // ArrayList<>();
// List<String> resultLines = new ArrayList<>(); //
// int position = 0; // List<String> resultLines = new ArrayList<>();
// for (String templateLine : templateLines) { // int position = 0;
// // Check if the line is a comment // for (String templateLine : templateLines) {
// if (templateLine.trim().startsWith("#")) { // // Check if the line is a comment
// String entry = templateLine.trim().substring(1).trim(); // if (templateLine.trim().startsWith("#")) {
// if (!entry.isEmpty()) { // String entry = templateLine.trim().substring(1).trim();
// // Check if this comment has been uncommented in userLines // if (!entry.isEmpty()) {
// String key = entry.split(":")[0].trim(); // // Check if this comment has been uncommented in userLines
// addLine(resultLines, userLines, templateLine, key, position); // String key = entry.split(":")[0].trim();
// } else { // addLine(resultLines, userLines, templateLine, key, position);
// resultLines.add(templateLine); // } else {
// } // resultLines.add(templateLine);
// } // }
// // Check if the line is a key-value pair // }
// else if (templateLine.contains(":")) { // // Check if the line is a key-value pair
// String key = templateLine.split(":")[0].trim(); // else if (templateLine.contains(":")) {
// addLine(resultLines, userLines, templateLine, key, position); // String key = templateLine.split(":")[0].trim();
// } // addLine(resultLines, userLines, templateLine, key, position);
// // Handle empty lines // }
// else if (templateLine.trim().length() == 0) { // // Handle empty lines
// resultLines.add(""); // else if (templateLine.trim().length() == 0) {
// } // resultLines.add("");
// position++; // }
// } // position++;
// // }
// // Write the result to the user settings file //
// Files.write(userPath, resultLines); // // Write the result to the user settings file
// Files.write(userPath, resultLines);
} }
Path customSettingsPath = Paths.get("configs", "custom_settings.yml"); Path customSettingsPath = Paths.get("configs", "custom_settings.yml");

View file

@ -8,7 +8,6 @@ import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.ResourceLoader;
import org.thymeleaf.IEngineConfiguration; import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.templateresolver.AbstractConfigurableTemplateResolver; import org.thymeleaf.templateresolver.AbstractConfigurableTemplateResolver;
import org.thymeleaf.templateresource.ClassLoaderTemplateResource;
import org.thymeleaf.templateresource.FileTemplateResource; import org.thymeleaf.templateresource.FileTemplateResource;
import org.thymeleaf.templateresource.ITemplateResource; import org.thymeleaf.templateresource.ITemplateResource;
@ -43,7 +42,10 @@ public class FileFallbackTemplateResolver extends AbstractConfigurableTemplateRe
} }
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("templates/" + resourceName); InputStream inputStream =
Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("templates/" + resourceName);
if (inputStream != null) { if (inputStream != null) {
return new InputStreamTemplateResource(inputStream, "UTF-8"); return new InputStreamTemplateResource(inputStream, "UTF-8");
} }

View file

@ -66,46 +66,46 @@ public class UserController {
RedirectAttributes redirectAttributes) { RedirectAttributes redirectAttributes) {
if (!userService.isUsernameValid(newUsername)) { if (!userService.isUsernameValid(newUsername)) {
return new RedirectView("/account?messageType=invalidUsername",true); return new RedirectView("/account?messageType=invalidUsername", true);
} }
if (principal == null) { if (principal == null) {
return new RedirectView("/account?messageType=notAuthenticated",true); return new RedirectView("/account?messageType=notAuthenticated", true);
} }
// The username MUST be unique when renaming // The username MUST be unique when renaming
Optional<User> userOpt = userService.findByUsername(principal.getName()); Optional<User> userOpt = userService.findByUsername(principal.getName());
if (userOpt == null || userOpt.isEmpty()) { if (userOpt == null || userOpt.isEmpty()) {
return new RedirectView("/account?messageType=userNotFound",true); return new RedirectView("/account?messageType=userNotFound", true);
} }
User user = userOpt.get(); User user = userOpt.get();
if (user.getUsername().equals(newUsername)) { if (user.getUsername().equals(newUsername)) {
return new RedirectView("/account?messageType=usernameExists",true); return new RedirectView("/account?messageType=usernameExists", true);
} }
if (!userService.isPasswordCorrect(user, currentPassword)) { if (!userService.isPasswordCorrect(user, currentPassword)) {
return new RedirectView("/account?messageType=incorrectPassword",true); return new RedirectView("/account?messageType=incorrectPassword", true);
} }
if (!user.getUsername().equals(newUsername) && userService.usernameExists(newUsername)) { if (!user.getUsername().equals(newUsername) && userService.usernameExists(newUsername)) {
return new RedirectView("/account?messageType=usernameExists",true); return new RedirectView("/account?messageType=usernameExists", true);
} }
if (newUsername != null && newUsername.length() > 0) { if (newUsername != null && newUsername.length() > 0) {
try { try {
userService.changeUsername(user, newUsername); userService.changeUsername(user, newUsername);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
return new RedirectView("/account?messageType=invalidUsername",true); return new RedirectView("/account?messageType=invalidUsername", true);
} }
} }
// Logout using Spring's utility // Logout using Spring's utility
new SecurityContextLogoutHandler().logout(request, response, null); new SecurityContextLogoutHandler().logout(request, response, null);
return new RedirectView(LOGIN_MESSAGETYPE_CREDSUPDATED,true); return new RedirectView(LOGIN_MESSAGETYPE_CREDSUPDATED, true);
} }
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')") @PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
@ -118,19 +118,19 @@ public class UserController {
HttpServletResponse response, HttpServletResponse response,
RedirectAttributes redirectAttributes) { RedirectAttributes redirectAttributes) {
if (principal == null) { if (principal == null) {
return new RedirectView("/change-creds?messageType=notAuthenticated",true); return new RedirectView("/change-creds?messageType=notAuthenticated", true);
} }
Optional<User> userOpt = userService.findByUsernameIgnoreCase(principal.getName()); Optional<User> userOpt = userService.findByUsernameIgnoreCase(principal.getName());
if (userOpt == null || userOpt.isEmpty()) { if (userOpt == null || userOpt.isEmpty()) {
return new RedirectView("/change-creds?messageType=userNotFound",true); return new RedirectView("/change-creds?messageType=userNotFound", true);
} }
User user = userOpt.get(); User user = userOpt.get();
if (!userService.isPasswordCorrect(user, currentPassword)) { if (!userService.isPasswordCorrect(user, currentPassword)) {
return new RedirectView("/change-creds?messageType=incorrectPassword",true); return new RedirectView("/change-creds?messageType=incorrectPassword", true);
} }
userService.changePassword(user, newPassword); userService.changePassword(user, newPassword);
@ -138,7 +138,7 @@ public class UserController {
// Logout using Spring's utility // Logout using Spring's utility
new SecurityContextLogoutHandler().logout(request, response, null); new SecurityContextLogoutHandler().logout(request, response, null);
return new RedirectView(LOGIN_MESSAGETYPE_CREDSUPDATED,true); return new RedirectView(LOGIN_MESSAGETYPE_CREDSUPDATED, true);
} }
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')") @PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
@ -151,19 +151,19 @@ public class UserController {
HttpServletResponse response, HttpServletResponse response,
RedirectAttributes redirectAttributes) { RedirectAttributes redirectAttributes) {
if (principal == null) { if (principal == null) {
return new RedirectView("/account?messageType=notAuthenticated",true); return new RedirectView("/account?messageType=notAuthenticated", true);
} }
Optional<User> userOpt = userService.findByUsernameIgnoreCase(principal.getName()); Optional<User> userOpt = userService.findByUsernameIgnoreCase(principal.getName());
if (userOpt == null || userOpt.isEmpty()) { if (userOpt == null || userOpt.isEmpty()) {
return new RedirectView("/account?messageType=userNotFound",true); return new RedirectView("/account?messageType=userNotFound", true);
} }
User user = userOpt.get(); User user = userOpt.get();
if (!userService.isPasswordCorrect(user, currentPassword)) { if (!userService.isPasswordCorrect(user, currentPassword)) {
return new RedirectView("/account?messageType=incorrectPassword",true); return new RedirectView("/account?messageType=incorrectPassword", true);
} }
userService.changePassword(user, newPassword); userService.changePassword(user, newPassword);
@ -171,7 +171,7 @@ public class UserController {
// Logout using Spring's utility // Logout using Spring's utility
new SecurityContextLogoutHandler().logout(request, response, null); new SecurityContextLogoutHandler().logout(request, response, null);
return new RedirectView(LOGIN_MESSAGETYPE_CREDSUPDATED,true); return new RedirectView(LOGIN_MESSAGETYPE_CREDSUPDATED, true);
} }
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')") @PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
@ -204,7 +204,7 @@ public class UserController {
boolean forceChange) { boolean forceChange) {
if (!userService.isUsernameValid(username)) { if (!userService.isUsernameValid(username)) {
return new RedirectView("/addUsers?messageType=invalidUsername",true); return new RedirectView("/addUsers?messageType=invalidUsername", true);
} }
Optional<User> userOpt = userService.findByUsernameIgnoreCase(username); Optional<User> userOpt = userService.findByUsernameIgnoreCase(username);
@ -212,26 +212,27 @@ public class UserController {
if (userOpt.isPresent()) { if (userOpt.isPresent()) {
User user = userOpt.get(); User user = userOpt.get();
if (user != null && user.getUsername().equalsIgnoreCase(username)) { if (user != null && user.getUsername().equalsIgnoreCase(username)) {
return new RedirectView("/addUsers?messageType=usernameExists",true); return new RedirectView("/addUsers?messageType=usernameExists", true);
} }
} }
if (userService.usernameExistsIgnoreCase(username)) { if (userService.usernameExistsIgnoreCase(username)) {
return new RedirectView("/addUsers?messageType=usernameExists",true); return new RedirectView("/addUsers?messageType=usernameExists", true);
} }
try { try {
// Validate the role // Validate the role
Role roleEnum = Role.fromString(role); Role roleEnum = Role.fromString(role);
if (roleEnum == Role.INTERNAL_API_USER) { if (roleEnum == Role.INTERNAL_API_USER) {
// If the role is INTERNAL_API_USER, reject the request // If the role is INTERNAL_API_USER, reject the request
return new RedirectView("/addUsers?messageType=invalidRole",true); return new RedirectView("/addUsers?messageType=invalidRole", true);
} }
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
// If the role ID is not valid, redirect with an error message // If the role ID is not valid, redirect with an error message
return new RedirectView("/addUsers?messageType=invalidRole",true); return new RedirectView("/addUsers?messageType=invalidRole", true);
} }
userService.saveUser(username, password, role, forceChange); userService.saveUser(username, password, role, forceChange);
return new RedirectView("/addUsers",true); // Redirect to account page after adding the user return new RedirectView(
"/addUsers", true); // Redirect to account page after adding the user
} }
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@ -244,33 +245,34 @@ public class UserController {
Optional<User> userOpt = userService.findByUsernameIgnoreCase(username); Optional<User> userOpt = userService.findByUsernameIgnoreCase(username);
if (!userOpt.isPresent()) { if (!userOpt.isPresent()) {
return new RedirectView("/addUsers?messageType=userNotFound",true); return new RedirectView("/addUsers?messageType=userNotFound", true);
} }
if (!userService.usernameExistsIgnoreCase(username)) { if (!userService.usernameExistsIgnoreCase(username)) {
return new RedirectView("/addUsers?messageType=userNotFound",true); return new RedirectView("/addUsers?messageType=userNotFound", true);
} }
// Get the currently authenticated username // Get the currently authenticated username
String currentUsername = authentication.getName(); String currentUsername = authentication.getName();
// Check if the provided username matches the current session's username // Check if the provided username matches the current session's username
if (currentUsername.equalsIgnoreCase(username)) { if (currentUsername.equalsIgnoreCase(username)) {
return new RedirectView("/addUsers?messageType=downgradeCurrentUser",true); return new RedirectView("/addUsers?messageType=downgradeCurrentUser", true);
} }
try { try {
// Validate the role // Validate the role
Role roleEnum = Role.fromString(role); Role roleEnum = Role.fromString(role);
if (roleEnum == Role.INTERNAL_API_USER) { if (roleEnum == Role.INTERNAL_API_USER) {
// If the role is INTERNAL_API_USER, reject the request // If the role is INTERNAL_API_USER, reject the request
return new RedirectView("/addUsers?messageType=invalidRole",true); return new RedirectView("/addUsers?messageType=invalidRole", true);
} }
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
// If the role ID is not valid, redirect with an error message // If the role ID is not valid, redirect with an error message
return new RedirectView("/addUsers?messageType=invalidRole",true); return new RedirectView("/addUsers?messageType=invalidRole", true);
} }
User user = userOpt.get(); User user = userOpt.get();
userService.changeRole(user, role); userService.changeRole(user, role);
return new RedirectView("/addUsers",true); // Redirect to account page after adding the user return new RedirectView(
"/addUsers", true); // Redirect to account page after adding the user
} }
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@ -279,7 +281,7 @@ public class UserController {
@PathVariable(name = "username") String username, Authentication authentication) { @PathVariable(name = "username") String username, Authentication authentication) {
if (!userService.usernameExistsIgnoreCase(username)) { if (!userService.usernameExistsIgnoreCase(username)) {
return new RedirectView("/addUsers?messageType=deleteUsernameExists",true); return new RedirectView("/addUsers?messageType=deleteUsernameExists", true);
} }
// Get the currently authenticated username // Get the currently authenticated username
@ -287,11 +289,11 @@ public class UserController {
// Check if the provided username matches the current session's username // Check if the provided username matches the current session's username
if (currentUsername.equalsIgnoreCase(username)) { if (currentUsername.equalsIgnoreCase(username)) {
return new RedirectView("/addUsers?messageType=deleteCurrentUser",true); return new RedirectView("/addUsers?messageType=deleteCurrentUser", true);
} }
invalidateUserSessions(username); invalidateUserSessions(username);
userService.deleteUser(username); userService.deleteUser(username);
return new RedirectView("/addUsers",true); return new RedirectView("/addUsers", true);
} }
@Autowired private SessionRegistry sessionRegistry; @Autowired private SessionRegistry sessionRegistry;

View file

@ -37,9 +37,9 @@ public class InputStreamTemplateResource implements ITemplateResource {
return "streamResource"; return "streamResource";
} }
@Override @Override
public boolean exists() { public boolean exists() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
} }