Registering
@Transactional
public UserDto register(RegisterDto dto) {
if (userRepository.findByUsername(dto.username()).isPresent()) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "username taken");
}
AppUser user = new AppUser();
user.setUsername(dto.username());
user.setPasswordHash(passwordEncoder.encode(dto.password()));
user.setRole(userRepository.count() == 0 ? "ADMIN" : "USER");
user = userRepository.save(user);
return new UserDto(user.getId(), user.getUsername(), user.getRole());
}
- The password goes through
encode and nowhere else; the DTO that comes back has no password field
- The first user of an empty table becomes
ADMIN, so that an administrator exists without a hand-written insert; every later user is USER
$ curl -X POST localhost:8088/api/register -d '{"username":"siim","password":"correct horse"}'
HTTP/1.1 201 {"id":1,"username":"siim","role":"ADMIN"}
$ curl -X POST localhost:8088/api/register -d '{"username":"mari","password":"correct horse"}'
HTTP/1.1 201 {"id":2,"username":"mari","role":"USER"}