added security and fix edit profile

This commit is contained in:
SlimusMinus
2026-06-18 00:22:50 +03:00
parent 81e3e007e1
commit bafb636cbe
24 changed files with 418 additions and 56 deletions

View File

@@ -1,25 +1,80 @@
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.http.ResponseEntity;
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();
return repository.findByLogin("moscow_city231@rambler.ru")
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.setName(dto.getFirstName());
user.setLogin(dto.getLastName());
user.setPhone(dto.getPhone());
user.setEmail(dto.getEmail());
user.setLogin(dto.getLogin());
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())
.avatar(user.getAvatarUrl())
.build();
}
}