fixed controllers

This commit is contained in:
SlimusMinus
2026-07-31 01:08:53 +03:00
parent 74f7c88843
commit 2468c26b84
32 changed files with 536 additions and 432 deletions

View File

@@ -4,15 +4,12 @@ import com.krylov.refound.dto.AuthRequest;
import com.krylov.refound.dto.AuthResponse;
import com.krylov.refound.dto.CheckLoginDto;
import com.krylov.refound.dto.RegisterRequest;
import com.krylov.refound.dto.UserDto;
import com.krylov.refound.entity.User;
import com.krylov.refound.repository.UserRepository;
import com.krylov.refound.security.JwtService;
import com.krylov.refound.dto.UserRegisterDto;
import com.krylov.refound.service.AuthService;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -24,73 +21,28 @@ import org.springframework.web.bind.annotation.RestController;
@RequiredArgsConstructor
public class AuthController {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final JwtService jwtService;
private final AuthService authService;
@PostMapping("/register")
public ResponseEntity<?> register(@RequestBody RegisterRequest request) {
// Проверка что логин не занят
if (userRepository.findByLogin(request.getLogin()).isPresent()) {
return ResponseEntity
.badRequest()
.body(Map.of("message", "Логин уже занят"));
}
// Создание пользователя
User user = new User();
user.setName(request.getName());
user.setLogin(request.getLogin());
user.setPassword(passwordEncoder.encode(request.getPassword()));
userRepository.save(user);
String token = jwtService.generateToken(user.getLogin());
UserDto userDto = new UserDto(
user.getId(),
user.getName(),
user.getLastName(),
user.getLogin(),
user.getEmail(),
user.getPhone(),
user.getAvatarUrl(),
user.getRole()
);
return ResponseEntity.ok(new AuthResponse(token, userDto));
log.info("register user {}", request);
UserRegisterDto userRegisterDto = authService.registerUser(request);
return ResponseEntity.ok(
new AuthResponse(userRegisterDto.getToken(), userRegisterDto.getUserDto()));
}
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody AuthRequest request) {
User user = userRepository.findByLogin(request.getLogin())
.orElse(null);
if (user == null || !passwordEncoder.matches(request.getPassword(), user.getPassword())) {
return ResponseEntity
.badRequest()
.body(Map.of("message", "Неверный логин или пароль"));
}
String token = jwtService.generateToken(user.getLogin());
UserDto userDto = new UserDto(
user.getId(),
user.getName(),
user.getLastName(),
user.getLogin(),
user.getEmail(),
user.getPhone(),
user.getAvatarUrl(),
user.getRole()
);
return ResponseEntity.ok(new AuthResponse(token, userDto));
log.info("user {} logging", request.getLogin());
UserRegisterDto userRegisterDto = authService.loginUser(request);
return ResponseEntity.ok(
new AuthResponse(userRegisterDto.getToken(), userRegisterDto.getUserDto()));
}
@PostMapping("/check-login")
public ResponseEntity<?> checkLogin(@RequestBody CheckLoginDto request) {
boolean exists = userRepository.existsByLogin(request.getLogin());
log.info("checkLogin for {}", request.getLogin());
boolean exists = authService.existsByLogin(request);
return ResponseEntity.ok(Map.of("exists", exists));
}

View File

@@ -4,11 +4,17 @@ import com.krylov.refound.dto.*;
import com.krylov.refound.service.ChatService;
import com.krylov.refound.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/chats")
@@ -20,40 +26,46 @@ public class ChatController {
// Создать чат с пользователем или получить существующий
@PostMapping("/with/{otherUserId}")
public ChatDto createOrGetChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId, Authentication auth) {
Long currentUserId = extractUserId(auth); // см. ниже как достать id
Long currentUserId = extractUserId(auth);
log.info("createOrGetChat currentUserId {}, otherUserId {}, postId {}", currentUserId, otherUserId, postId);
return chatService.getOrCreateChat(currentUserId, otherUserId, postId);
}
// Список всех чатов текущего пользователя
@GetMapping
public List<ChatDto> getMyChats(Authentication auth) {
return chatService.getUserChats(extractUserId(auth));
Long currentUserId = extractUserId(auth);
log.info("getMyChats for user {}", currentUserId);
return chatService.getUserChats(currentUserId);
}
// История сообщений конкретного чата
// История сообщений конкретного чата, с пагинацией
@GetMapping("/{chatId}/messages")
public List<MessageDto> getMessages(@PathVariable Long chatId) {
return chatService.getMessages(chatId);
}
private Long extractUserId(Authentication auth) {
// Подставь свою логику получения userId из JWT/Authentication
// Например если в токене login, а не id - подтяни через UserService
String login = auth.getName();
return userService.getUserIdByLogin(login);
public Page<MessageDto> getMessages(@PathVariable Long chatId, @PageableDefault(size = 30, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable, Authentication auth) {
Long currentUserId = extractUserId(auth);
log.info("getMessages for chatId {} page {} by user {}", chatId, pageable.getPageNumber(), currentUserId);
return chatService.getMessages(chatId, currentUserId, pageable);
}
@DeleteMapping("/{chatId}")
public void deleteChat(@PathVariable Long chatId, Authentication auth) {
Long currentUserId = extractUserId(auth);
chatService.deleteChat(chatId);
log.info("user {} deleteChat {}", currentUserId, chatId);
chatService.deleteChat(chatId, currentUserId);
}
@PostMapping("/api/v1/chats/{chatId}/read")
public void markAsRead(@PathVariable Long chatId) {
Long userId = (Long) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal(); // или твой способ
chatService.markAsRead(chatId, userId);
@PostMapping("/{chatId}/read")
public void markAsRead(@PathVariable Long chatId, Authentication auth) {
Long currentUserId = extractUserId(auth);
log.info("markAsRead chatId {} by user {}", chatId, currentUserId);
chatService.markAsRead(chatId, currentUserId);
}
private Long extractUserId(Authentication auth) {
// Подставь свою логику получения userId из JWT/Authentication
String login = auth.getName();
log.debug("extractUserId by login {}", login);
return userService.getUserIdByLogin(login);
}
}

View File

@@ -2,21 +2,37 @@ package com.krylov.refound.controller;
import com.krylov.refound.dto.SendMessageRequest;
import com.krylov.refound.service.ChatService;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequiredArgsConstructor
public class ChatWebSocketController {
private final ChatService chatService;
private final SimpMessagingTemplate messagingTemplate;
// Клиент шлёт сюда: /app/chat.send
@MessageMapping("/chat.send")
public void sendMessage(SendMessageRequest request, SimpMessageHeaderAccessor headerAccessor) {
Long senderId = (Long) headerAccessor.getSessionAttributes().get("userId");
chatService.sendMessage(senderId, request.getChatId(), request.getContent());
Long senderId = (Long) Objects.requireNonNull(headerAccessor.getSessionAttributes()).get("userId");
if (senderId == null) {
log.warn("sendMessage: senderId is null, session attrs missing userId");
return; // или отправить ошибку клиенту
}
if (request.getContent() == null || request.getContent().isBlank()) {
return;
}
try {
chatService.sendMessage(senderId, request.getChatId(), request.getContent());
} catch (SecurityException | IllegalArgumentException e) {
messagingTemplate.convertAndSendToUser(senderId.toString(), "/queue/errors", e.getMessage());
}
// ChatService сам отправит сообщение всем подписчикам через messagingTemplate
}
}

View File

@@ -1,34 +1,33 @@
package com.krylov.refound.controller;
import com.krylov.refound.dto.PostResponse;
import com.krylov.refound.mapper.PostMapper;
import com.krylov.refound.service.FavoriteService;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping("/api/v1/favorites")
@RequiredArgsConstructor
public class FavoriteController {
private final FavoriteService service;
private final PostMapper mapper;
@PostMapping("/{postId}/toggle")
public void toggle(@PathVariable Long postId) {
log.info("toggle post {}", postId);
service.toggle(postId);
}
@GetMapping
public List<PostResponse> getAll() {
return service.getFavorites()
.stream()
.map(mapper::toResponse)
.toList();
log.info("get all likes");
return service.getFavorites();
}
}

View File

@@ -2,15 +2,18 @@ package com.krylov.refound.controller;
import com.krylov.refound.service.FileStorageService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;
import java.nio.charset.StandardCharsets;
@Slf4j
@RestController
@RequestMapping("/api/v1/files")
@RequiredArgsConstructor
@@ -19,26 +22,21 @@ public class FileStorageController {
@PostMapping
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
log.info("uploadFile");
String objectName = fileStorageService.uploadFile(file);
return ResponseEntity.ok(objectName); // фронт сохранит objectName как ключ картинки
}
@GetMapping("/{objectName}")
@GetMapping("/{*objectName}")
public ResponseEntity<byte[]> downloadFile(@PathVariable String objectName) {
FileStorageService.DownloadedFile downloadedFile = fileStorageService.downloadFile(objectName);
String encodedFilename = UriUtils.encode(downloadedFile.originalFilename(), StandardCharsets.UTF_8);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFilename);
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.parseMediaType(downloadedFile.contentType()))
.body(downloadedFile.content());
// objectName придёт как "/avatars/cf80aebe-...jpg" — обрежь ведущий слэш
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
return fileStorageService.downloadFile(key);
}
@DeleteMapping("/{objectName}")
public ResponseEntity<Void> deleteFile(@PathVariable String objectName) {
log.info("deleteFile {}", objectName);
fileStorageService.deleteFile(objectName);
return ResponseEntity.noContent().build();
}

View File

@@ -1,22 +1,17 @@
package com.krylov.refound.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.krylov.refound.dto.PostRequest;
import com.krylov.refound.dto.PostResponse;
import com.krylov.refound.dto.StatusUpdateRequest;
import com.krylov.refound.enums.PostType;
import com.krylov.refound.service.PostService;
import java.util.Arrays;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
@@ -27,78 +22,53 @@ import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@Slf4j
@RestController
@RequestMapping("/api/v1/posts")
@RequiredArgsConstructor
@Slf4j
public class PostController {
private final PostService service;
private final ObjectMapper objectMapper;
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public PostRequest create(@ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) {
log.info(request.toString());
log.info("create post {}", request.toString());
return service.create(request, images);
}
@GetMapping
public Page<PostResponse> getFeed(
@RequestParam(required = false) String search,
@PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
public Page<PostResponse> getFeed(@RequestParam(required = false) String search, @PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
log.info("get all feed");
return service.getFeed(search, pageable);
}
@GetMapping("/{id}")
public List<PostResponse> getById(@PathVariable Long id) {
log.info("get feed by id {}", id);
return service.getById(id);
}
@PutMapping(value = "/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public PostResponse update(
@PathVariable Long id,
@RequestParam String type,
@RequestParam String title,
@RequestParam(required = false) String address,
@RequestParam(required = false) Double latitude,
@RequestParam(required = false) Double longitude,
@RequestParam(required = false) String description,
@RequestParam(required = false) String category,
@RequestParam(required = false) String phone,
@RequestParam(value = "images", required = false) List<MultipartFile> images,
@RequestParam(value = "existingImages", required = false) String existingImagesJson) {
PostRequest request = new PostRequest();
request.setType(PostType.from(type));
request.setTitle(title);
request.setDescription(description);
request.setCategory(category);
request.setPhone(phone);
request.setLatitude(latitude);
request.setLongitude(longitude);
request.setAddress(address);
List<String> existingUrls;
try {
existingUrls = existingImagesJson != null ? Arrays.asList(
objectMapper.readValue(existingImagesJson, String[].class)) : List.of();
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
return service.update(id, request, images, existingUrls);
public PostResponse update(@PathVariable Long id, @RequestParam String type, @RequestParam String title, @RequestParam(required = false) String address,
@RequestParam(required = false) Double latitude, @RequestParam(required = false) Double longitude, @RequestParam(required = false) String description,
@RequestParam(required = false) String category, @RequestParam(required = false) String phone,
@RequestParam(value = "images", required = false) List<MultipartFile> images, @RequestParam(value = "existingImages", required = false) String existingImagesJson) {
log.info("update post {}", id);
return service.update(id, type, title, address, latitude, longitude, description, category, phone, images, existingImagesJson);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
log.info("delete feed by id {}", id);
service.delete(id);
}
@PatchMapping("/{id}/status")
public PostResponse updateStatus(@PathVariable Long id,
@RequestBody StatusUpdateRequest request) {
public PostResponse updateStatus(@PathVariable Long id, @RequestBody StatusUpdateRequest request) {
log.info("update feed {} on status {}", id, request.getStatus());
return service.updateStatus(id, request.getStatus());
}
}

View File

@@ -15,25 +15,24 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping("/api/v1/reviews")
@RequiredArgsConstructor
@Slf4j
public class ReviewsController {
private final ReviewService reviewService;
@GetMapping
public List<ReviewResponseDto> getAllReviews() {
List<ReviewResponseDto> allReviews = reviewService.getAllReviews();
log.info("Got all reviews: {}", allReviews);
return allReviews;
log.info("get all reviews");
return reviewService.getAllReviews();
}
@PostMapping
@PreAuthorize("isAuthenticated()")
public ReviewResponseDto createReview(@Valid @RequestBody ReviewRequestDto request, Authentication authentication) {
// Взять имя пользователя из authentication
log.info("user {} create review {}", authentication.getName(), request);
return reviewService.createReview(request, authentication.getName());
}
}

View File

@@ -3,10 +3,12 @@ package com.krylov.refound.controller;
import com.krylov.refound.entity.Statistics;
import com.krylov.refound.service.StatisticsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/statistics")
@@ -15,6 +17,7 @@ public class StatisticsController {
@GetMapping
public Statistics get() {
log.info("get all statistics");
return statisticsService.getStatistics();
}
}

View File

@@ -23,7 +23,7 @@ public class UserController {
@PutMapping("/{id}")
public ResponseEntity<UserResponseDto> updateUser(@PathVariable Long id, @ModelAttribute UserUpdateDto userUpdateDto) {
log.info("updateUser, id={}", id);
UserResponseDto userResponseDto = userService.updateUser(id, userUpdateDto);
UserResponseDto userResponseDto = userService.updateUser(id, userUpdateDto);
return ResponseEntity.ok(userResponseDto);
}