Stirling-PDF/src/main/java/stirling/software/SPDF/controller/api/UserController.java

253 lines
10 KiB
Java
Raw Normal View History

2023-08-12 03:29:10 +02:00
package stirling.software.SPDF.controller.api;
2023-08-13 02:12:29 +02:00
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
2023-08-15 01:39:13 +02:00
import java.util.Optional;
2023-08-13 02:12:29 +02:00
2023-08-12 03:29:10 +02:00
import org.springframework.beans.factory.annotation.Autowired;
2023-08-13 19:19:15 +02:00
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
2023-08-13 02:12:29 +02:00
import org.springframework.security.access.prepost.PreAuthorize;
2023-08-30 23:52:38 +02:00
import org.springframework.security.core.Authentication;
2023-08-27 01:39:22 +02:00
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
2023-08-12 03:29:10 +02:00
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
2023-08-13 02:12:29 +02:00
import org.springframework.web.bind.annotation.PathVariable;
2023-08-12 03:29:10 +02:00
import org.springframework.web.bind.annotation.PostMapping;
2023-09-12 00:19:50 +02:00
import org.springframework.web.bind.annotation.RequestMapping;
2023-08-12 03:29:10 +02:00
import org.springframework.web.bind.annotation.RequestParam;
2023-09-03 17:40:40 +02:00
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
2023-08-12 03:29:10 +02:00
2023-08-13 02:12:29 +02:00
import jakarta.servlet.http.HttpServletRequest;
2023-08-15 01:39:13 +02:00
import jakarta.servlet.http.HttpServletResponse;
2023-08-12 03:29:10 +02:00
import stirling.software.SPDF.config.security.UserService;
2023-12-25 13:58:49 +01:00
import stirling.software.SPDF.model.Role;
2023-08-13 19:19:15 +02:00
import stirling.software.SPDF.model.User;
2023-08-12 03:29:10 +02:00
@Controller
2023-09-12 00:19:50 +02:00
@RequestMapping("/api/v1/user")
2023-08-12 03:29:10 +02:00
public class UserController {
@Autowired
private UserService userService;
2023-08-15 01:39:13 +02:00
2023-12-27 23:56:51 +01:00
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
2023-08-12 03:29:10 +02:00
@PostMapping("/register")
public String register(@RequestParam String username, @RequestParam String password, Model model) {
if(userService.usernameExists(username)) {
model.addAttribute("error", "Username already exists");
return "register";
}
userService.saveUser(username, password);
return "redirect:/login?registered=true";
}
2023-08-13 02:12:29 +02:00
2023-12-27 23:56:51 +01:00
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
2023-09-03 17:40:40 +02:00
@PostMapping("/change-username-and-password")
public RedirectView changeUsernameAndPassword(Principal principal,
@RequestParam String currentPassword,
@RequestParam String newUsername,
@RequestParam String newPassword,
HttpServletRequest request,
HttpServletResponse response,
RedirectAttributes redirectAttributes) {
2023-09-04 01:12:27 +02:00
if (principal == null) {
return new RedirectView("/change-creds?messageType=notAuthenticated");
}
2023-09-03 17:40:40 +02:00
2023-09-04 01:12:27 +02:00
Optional<User> userOpt = userService.findByUsername(principal.getName());
2023-09-03 17:40:40 +02:00
2023-09-04 01:12:27 +02:00
if (userOpt == null || userOpt.isEmpty()) {
return new RedirectView("/change-creds?messageType=userNotFound");
}
2023-09-03 17:40:40 +02:00
2023-09-04 01:12:27 +02:00
User user = userOpt.get();
if (!userService.isPasswordCorrect(user, currentPassword)) {
return new RedirectView("/change-creds?messageType=incorrectPassword");
}
if (!user.getUsername().equals(newUsername) && userService.usernameExists(newUsername)) {
return new RedirectView("/change-creds?messageType=usernameExists");
}
2023-09-03 17:40:40 +02:00
userService.changePassword(user, newPassword);
2023-09-04 19:42:22 +02:00
if(newUsername != null && newUsername.length() > 0 && !user.getUsername().equals(newUsername)) {
2023-09-03 17:40:40 +02:00
userService.changeUsername(user, newUsername);
}
userService.changeFirstUse(user, false);
// Logout using Spring's utility
new SecurityContextLogoutHandler().logout(request, response, null);
2023-09-04 01:12:27 +02:00
return new RedirectView("/login?messageType=credsUpdated");
2023-09-03 17:40:40 +02:00
}
2023-12-27 23:56:51 +01:00
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
2023-08-15 01:39:13 +02:00
@PostMapping("/change-username")
2023-09-03 17:40:40 +02:00
public RedirectView changeUsername(Principal principal,
@RequestParam String currentPassword,
@RequestParam String newUsername,
HttpServletRequest request,
HttpServletResponse response,
RedirectAttributes redirectAttributes) {
2023-09-04 01:12:27 +02:00
if (principal == null) {
return new RedirectView("/account?messageType=notAuthenticated");
}
2023-09-03 17:40:40 +02:00
2023-09-04 01:12:27 +02:00
Optional<User> userOpt = userService.findByUsername(principal.getName());
2023-09-03 17:40:40 +02:00
2023-09-04 01:12:27 +02:00
if (userOpt == null || userOpt.isEmpty()) {
return new RedirectView("/account?messageType=userNotFound");
}
2023-09-03 17:40:40 +02:00
2023-09-04 01:12:27 +02:00
User user = userOpt.get();
if (!userService.isPasswordCorrect(user, currentPassword)) {
return new RedirectView("/account?messageType=incorrectPassword");
}
if (!user.getUsername().equals(newUsername) && userService.usernameExists(newUsername)) {
return new RedirectView("/account?messageType=usernameExists");
}
2023-09-03 17:40:40 +02:00
2023-09-04 19:42:22 +02:00
if(newUsername != null && newUsername.length() > 0) {
userService.changeUsername(user, newUsername);
}
2023-08-15 01:39:13 +02:00
// Logout using Spring's utility
new SecurityContextLogoutHandler().logout(request, response, null);
2023-09-04 01:12:27 +02:00
return new RedirectView("/login?messageType=credsUpdated");
2023-08-15 01:39:13 +02:00
}
2023-12-27 23:56:51 +01:00
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
2023-08-15 01:39:13 +02:00
@PostMapping("/change-password")
2023-09-03 17:40:40 +02:00
public RedirectView changePassword(Principal principal,
@RequestParam String currentPassword,
@RequestParam String newPassword,
HttpServletRequest request,
HttpServletResponse response,
RedirectAttributes redirectAttributes) {
2023-09-04 01:12:27 +02:00
if (principal == null) {
return new RedirectView("/account?messageType=notAuthenticated");
}
2023-08-15 01:39:13 +02:00
2023-09-04 01:12:27 +02:00
Optional<User> userOpt = userService.findByUsername(principal.getName());
2023-09-03 17:40:40 +02:00
2023-09-04 01:12:27 +02:00
if (userOpt == null || userOpt.isEmpty()) {
return new RedirectView("/account?messageType=userNotFound");
}
2023-09-03 17:40:40 +02:00
2023-09-04 01:12:27 +02:00
User user = userOpt.get();
if (!userService.isPasswordCorrect(user, currentPassword)) {
return new RedirectView("/account?messageType=incorrectPassword");
}
2023-08-15 01:39:13 +02:00
2023-08-19 13:50:49 +02:00
userService.changePassword(user, newPassword);
2023-08-15 01:39:13 +02:00
// Logout using Spring's utility
new SecurityContextLogoutHandler().logout(request, response, null);
2023-09-03 17:40:40 +02:00
2023-09-04 01:12:27 +02:00
return new RedirectView("/login?messageType=credsUpdated");
2023-08-15 01:39:13 +02:00
}
2023-09-03 17:40:40 +02:00
2023-12-27 23:56:51 +01:00
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
2023-08-13 02:12:29 +02:00
@PostMapping("/updateUserSettings")
public String updateUserSettings(HttpServletRequest request, Principal principal) {
Map<String, String[]> paramMap = request.getParameterMap();
Map<String, String> updates = new HashMap<>();
System.out.println("Received parameter map: " + paramMap);
for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
updates.put(entry.getKey(), entry.getValue()[0]);
}
System.out.println("Processed updates: " + updates);
// Assuming you have a method in userService to update the settings for a user
userService.updateUserSettings(principal.getName(), updates);
return "redirect:/account"; // Redirect to a page of your choice after updating
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/admin/saveUser")
2023-09-04 19:42:22 +02:00
public RedirectView saveUser(@RequestParam String username, @RequestParam String password, @RequestParam String role,
@RequestParam(name = "forceChange", required = false, defaultValue = "false") boolean forceChange) {
if(userService.usernameExists(username)) {
return new RedirectView("/addUsers?messageType=usernameExists");
}
2023-12-25 13:58:49 +01:00
try {
// Validate the role
Role roleEnum = Role.fromString(role);
if (roleEnum == Role.INTERNAL_API_USER) {
// If the role is INTERNAL_API_USER, reject the request
return new RedirectView("/addUsers?messageType=invalidRole");
}
} catch (IllegalArgumentException e) {
// If the role ID is not valid, redirect with an error message
return new RedirectView("/addUsers?messageType=invalidRole");
}
2023-09-04 19:42:22 +02:00
userService.saveUser(username, password, role, forceChange);
return new RedirectView("/addUsers"); // Redirect to account page after adding the user
2023-08-13 02:12:29 +02:00
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
2023-08-30 23:52:38 +02:00
@PostMapping("/admin/deleteUser/{username}")
public String deleteUser(@PathVariable String username, Authentication authentication) {
// Get the currently authenticated username
String currentUsername = authentication.getName();
// Check if the provided username matches the current session's username
if (currentUsername.equals(username)) {
throw new IllegalArgumentException("Cannot delete currently logined in user.");
}
2023-08-13 02:12:29 +02:00
userService.deleteUser(username);
return "redirect:/addUsers";
}
2023-08-13 19:19:15 +02:00
2023-12-27 23:56:51 +01:00
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
2023-08-13 19:19:15 +02:00
@PostMapping("/get-api-key")
public ResponseEntity<String> getApiKey(Principal principal) {
if (principal == null) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("User not authenticated.");
}
String username = principal.getName();
String apiKey = userService.getApiKeyForUser(username);
if (apiKey == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("API key not found for user.");
}
return ResponseEntity.ok(apiKey);
}
2023-08-13 02:12:29 +02:00
2023-12-27 23:56:51 +01:00
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
2023-08-13 19:19:15 +02:00
@PostMapping("/update-api-key")
public ResponseEntity<String> updateApiKey(Principal principal) {
if (principal == null) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("User not authenticated.");
}
String username = principal.getName();
User user = userService.refreshApiKeyForUser(username);
String apiKey = user.getApiKey();
if (apiKey == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("API key not found for user.");
}
return ResponseEntity.ok(apiKey);
}
2023-08-13 02:12:29 +02:00
2023-08-12 03:29:10 +02:00
}