I currently have a special service to obtain information about the logged in user. I have an interface
/**
* The service operates on the data of an authorised user.
*/
public interface AuthorizationService {
User getUser();
String getUserId();
String getUsername();
boolean isLogged();
}
and implementation
@Service("authorizationService")
public class AuthorizationServiceImpl implements AuthorizationService {
private final UserSearchService userSearchService;
/**
* {@inheritDoc}
*/
@Override
public User getUser() {
return userSearchService.getUserByUsername(this.getUsername());
}
/**
* {@inheritDoc}
*/
@Override
public String getUserId() {
return userSearchService.getUserByUsername(SecurityContextHolder.getContext().getAuthentication().getName()).getId();
}
...
}
and for example, when I use the method to create messages, I do so
@Override
public String createMessage(
@NotNull @Valid final SendMessageDTO sendMessageDTO
) throws ResourceNotFoundException, ResourceConflictException {
log.info("Called with sendMessageDTO {}", sendMessageDTO);
final UserEntity user = this.findUser(this.authorizationService.getUserId());
final MessageEntity message = this.sendMessageDtoToMessageEntity(sendMessageDTO);
message.setSender(user);
...
}
private UserEntity findUser(final String id) throws ResourceNotFoundException {
return this.userRepository
.findByUniqueIdAndEnabledTrue(id)
.orElseThrow(() -> new ResourceNotFoundException("No user found with id " + id));
}
However, I do not know if this is a good way to obtain information about the logged-in user?
Instead of a DTO
User
object, I could return anentity
(I have a rule that I do not return entity service methods) and then I would not have to use thefindUser ()
method to search for a user. What do you think about it?Is my way of getting a DTO
User
logged in user or ID a safe way?