Konrad Neitzel 1e1368e519 Add transactional support to CharacterService, ScenarioService, and UserService
- Annotate create, update, and delete methods in CharacterService and ScenarioService with @Transactional to ensure proper transaction management.
- Add @Transactional annotation to the createUser method in UserService for consistency in transaction handling across services.
- Enhance data integrity and consistency during operations involving character, scenario, and user management.
2026-02-22 12:22:41 +01:00

74 lines
2.5 KiB
Java

package de.neitzel.roleplay.business;
import de.neitzel.roleplay.common.CreateUserRequest;
import de.neitzel.roleplay.common.UserSummary;
import de.neitzel.roleplay.data.UserEntity;
import de.neitzel.roleplay.data.UserRepository;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import java.util.List;
import java.util.stream.Collectors;
/**
* Business service for application users. Used by admin-only user management endpoints.
*/
@ApplicationScoped
public class UserService {
private final UserRepository userRepository;
@Inject
public UserService(final UserRepository userRepository) {
this.userRepository = userRepository;
}
/**
* Returns all users as summaries (no password).
*
* @return list of user summaries
*/
public List<UserSummary> listUsers() {
return userRepository.listAll().stream()
.map(UserService::toSummary)
.collect(Collectors.toList());
}
/**
* Creates a new user with the given username, plain password (hashed with bcrypt), and role.
*
* @param request create request (username, password, role)
* @return the created user summary
* @throws IllegalArgumentException if username is blank, password is blank, role is invalid, or username already exists
*/
@Transactional
public UserSummary createUser(final CreateUserRequest request) {
String username = request.getUsername();
String password = request.getPassword();
String role = request.getRole();
if (username == null || username.isBlank()) {
throw new IllegalArgumentException("Username is required");
}
if (password == null || password.isBlank()) {
throw new IllegalArgumentException("Password is required");
}
if (role == null || role.isBlank()) {
throw new IllegalArgumentException("Role is required");
}
if (!"admin".equals(role) && !"user".equals(role)) {
throw new IllegalArgumentException("Role must be 'admin' or 'user'");
}
if (userRepository.findByUsername(username) != null) {
throw new IllegalArgumentException("Username already exists: " + username);
}
UserEntity entity = UserEntity.add(username, password, role);
return toSummary(entity);
}
private static UserSummary toSummary(final UserEntity entity) {
return new UserSummary(entity.getId(), entity.getUsername(), entity.getRole());
}
}