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

@@ -0,0 +1,26 @@
package com.krylov.refound.service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service
public class AvatarService {
private final Path uploadDir = Paths.get("uploads/avatars");
public String save(MultipartFile file) {
try {
Files.createDirectories(uploadDir);
String filename = UUID.randomUUID() + "_" + file.getOriginalFilename();
Path target = uploadDir.resolve(filename);
file.transferTo(target);
return "/uploads/avatars/" + filename; // или полный URL, если есть статик-сервер/CDN
} catch (IOException e) {
throw new RuntimeException("Failed to save avatar", e);
}
}
}

View File

@@ -36,7 +36,6 @@ public class PostService {
private final ImageRepository imageRepository;
private final NominatimService nominatimService;
@CacheEvict(value = "posts", allEntries = true)
public PostRequest create(PostRequest request, MultipartFile image) {
Post post = mapper.toEntity(request);
@@ -74,15 +73,10 @@ public class PostService {
}
@Cacheable(value = "post", key = "#id")
public PostResponse getById(Long id) {
Post post = repository.findById(id)
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Post not found", HttpStatus.NOT_FOUND));
return mapper.toResponse(post);
public List <PostResponse> getById(Long id) {
return repository.findByUserId(id).stream().map(mapper::toResponse).toList();
}
@CacheEvict(value = {"posts", "post"}, allEntries = true)
public PostResponse update(Long id, PostRequest request, MultipartFile image) {
Post post = repository.findById(id)

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();
}
}