81 lines
2.6 KiB
Java
81 lines
2.6 KiB
Java
package com.krylov.refound.service;
|
|
|
|
import com.krylov.refound.dto.UserResponseDto;
|
|
import com.krylov.refound.dto.UserUpdateDto;
|
|
import com.krylov.refound.entity.User;
|
|
import com.krylov.refound.enums.ErrorCode;
|
|
import com.krylov.refound.exception.ApiException;
|
|
import com.krylov.refound.repository.UserRepository;
|
|
import jakarta.persistence.EntityNotFoundException;
|
|
import lombok.RequiredArgsConstructor;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.springframework.http.HttpStatus;
|
|
import org.springframework.security.core.Authentication;
|
|
import org.springframework.security.core.context.SecurityContextHolder;
|
|
import org.springframework.stereotype.Service;
|
|
import org.springframework.web.multipart.MultipartFile;
|
|
|
|
@Service
|
|
@Slf4j
|
|
@RequiredArgsConstructor
|
|
public class UserService {
|
|
private final UserRepository repository;
|
|
private final AvatarService avatarService;
|
|
|
|
public User getCurrentUser() {
|
|
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
|
|
|
if (authentication == null || authentication.getPrincipal() == null) {
|
|
throw new ApiException(
|
|
ErrorCode.UNAUTHORIZED,
|
|
"Пользователь не авторизован",
|
|
HttpStatus.UNAUTHORIZED
|
|
);
|
|
}
|
|
|
|
String login = (String) authentication.getPrincipal();
|
|
|
|
return repository.findByLogin(login)
|
|
.orElseThrow(() -> new ApiException(
|
|
ErrorCode.NOT_FOUND,
|
|
"User not found",
|
|
HttpStatus.NOT_FOUND
|
|
));
|
|
}
|
|
|
|
public UserResponseDto updateUser(Long id, UserUpdateDto dto) {
|
|
User user = repository.findById(id)
|
|
.orElseThrow(() -> new EntityNotFoundException("User not found"));
|
|
|
|
user.setLogin(dto.getLogin());
|
|
user.setName(dto.getFirstName());
|
|
user.setLastName(dto.getLastName());
|
|
user.setPhone(dto.getPhone());
|
|
user.setEmail(dto.getEmail());
|
|
|
|
MultipartFile avatar = dto.getAvatar();
|
|
if (avatar != null && !avatar.isEmpty()) {
|
|
String url = avatarService.save(avatar); // сохранение на диск/в S3/Yandex Object Storage
|
|
user.setAvatarUrl(url);
|
|
}
|
|
|
|
repository.save(user);
|
|
|
|
UserResponseDto userResponseDto = getUserResponseDto(user);
|
|
log.info("User updated: {}", userResponseDto);
|
|
return userResponseDto;
|
|
}
|
|
|
|
private static UserResponseDto getUserResponseDto(User user) {
|
|
return UserResponseDto.builder()
|
|
.id(user.getId())
|
|
.login(user.getLogin())
|
|
.name(user.getName())
|
|
.phone(user.getPhone())
|
|
.email(user.getEmail())
|
|
.lastName(user.getLastName())
|
|
.avatar(user.getAvatarUrl())
|
|
.build();
|
|
}
|
|
}
|