Skip to content

Commit

Permalink
refactor: user controller method, dto classes
Browse files Browse the repository at this point in the history
  • Loading branch information
ShulV committed Nov 10, 2023
1 parent 61c4504 commit f5cff82
Show file tree
Hide file tree
Showing 19 changed files with 274 additions and 333 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.shulpov.spots_app.authentication_management.validators;

import com.shulpov.spots_app.users.UserService;
import com.shulpov.spots_app.users.services.UserService;
import com.shulpov.spots_app.users.models.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package com.shulpov.spots_app.comments;

import com.shulpov.spots_app.comments.utils.CommentDtoConverter;
import com.shulpov.spots_app.users.models.User;
import com.shulpov.spots_app.users.UserService;
import com.shulpov.spots_app.utils.DtoConverter;
import com.shulpov.spots_app.users.services.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
Expand Down Expand Up @@ -30,13 +30,15 @@ public class CommentController {
private final CommentService commentService;
private final UserService userService;
private final Logger logger = LoggerFactory.getLogger(CommentController.class);
private final DtoConverter dtoConverter;

private final CommentDtoConverter commentDtoConverter;

@Autowired
public CommentController(CommentService commentService, @Lazy UserService userService, @Lazy DtoConverter dtoConverter) {
public CommentController(
CommentService commentService, @Lazy UserService userService, CommentDtoConverter commentDtoConverter) {
this.commentService = commentService;
this.userService = userService;
this.dtoConverter = dtoConverter;
this.commentDtoConverter = commentDtoConverter;
}

@Operation(
Expand Down Expand Up @@ -96,6 +98,6 @@ public Map<Object, Object> deleteById(@PathVariable Long commentId, Principal pr
@GetMapping("/get-by-spot-id/{spotId}")
public List<CommentDto> getBySpotId(@PathVariable Long spotId) {
logger.atInfo().log("/get-by-spot-id/{}", spotId);
return commentService.findByCommentedSpotId(spotId).stream().map(dtoConverter::commentToDto).toList();
return commentService.findByCommentedSpotId(spotId).stream().map(commentDtoConverter::commentToDto).toList();
}
}
40 changes: 6 additions & 34 deletions src/main/java/com/shulpov/spots_app/comments/CommentDto.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package com.shulpov.spots_app.comments;

import com.shulpov.spots_app.users.dto.UserWithoutSpotsDto;
import com.shulpov.spots_app.users.dto.MainUserInfoDto;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
import org.apache.logging.log4j.core.config.plugins.validation.constraints.NotBlank;

import java.util.Date;

@Getter
@Setter
public class CommentDto {
private Long id;

Expand All @@ -15,37 +19,5 @@ public class CommentDto {

private Date uploadDate;

private UserWithoutSpotsDto commentatorDto;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getText() {
return text;
}

public void setText(String text) {
this.text = text;
}

public Date getUploadDate() {
return uploadDate;
}

public void setUploadDate(Date uploadDate) {
this.uploadDate = uploadDate;
}

public UserWithoutSpotsDto getCommentatorDto() {
return commentatorDto;
}

public void setCommentatorDto(UserWithoutSpotsDto commentatorDto) {
this.commentatorDto = commentatorDto;
}
private MainUserInfoDto commentatorDto;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.shulpov.spots_app.comments.utils;

import com.shulpov.spots_app.comments.Comment;
import com.shulpov.spots_app.comments.CommentDto;
import com.shulpov.spots_app.users.dto.MainUserInfoDto;
import com.shulpov.spots_app.users.utils.UserDtoConverter;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Component;

@Component
public class CommentDtoConverter {
private final ModelMapper modelMapper;
private final UserDtoConverter userDtoConverter;

public CommentDtoConverter(ModelMapper modelMapper, UserDtoConverter userDtoConverter) {
this.modelMapper = modelMapper;
this.userDtoConverter = userDtoConverter;
}

public CommentDto commentToDto(Comment comment) {
CommentDto dto = modelMapper.map(comment, CommentDto.class);
MainUserInfoDto mainUserInfoDto = userDtoConverter.userToUserMainInfoDto(comment.getCommentator());
dto.setCommentatorDto(mainUserInfoDto);
return dto;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import com.shulpov.spots_app.image_infos.models.ImageInfo;
import com.shulpov.spots_app.users.models.User;
import com.shulpov.spots_app.users.UserService;
import com.shulpov.spots_app.users.services.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package com.shulpov.spots_app.image_infos.dto;

import java.io.Serializable;
import java.util.Date;

public class ImageInfoDto {
public class ImageInfoDto implements Serializable {

private Long id;
private String url;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.shulpov.spots_app.image_infos.utils;

import com.shulpov.spots_app.image_infos.dto.ImageInfoDto;
import com.shulpov.spots_app.image_infos.models.ImageInfo;
import com.shulpov.spots_app.utils.ImageUtil;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Component;

@Component
public class ImageInfoDtoConverter {
private final ModelMapper modelMapper;

public ImageInfoDtoConverter(ModelMapper modelMapper) {
this.modelMapper = modelMapper;
}

/**
* Конвертор класса ImageInfo в класс ImageInfoDto
*/
public ImageInfoDto imageInfoToDto(ImageInfo imageInfo) throws NullPointerException {
ImageInfoDto dto = modelMapper.map(imageInfo, ImageInfoDto.class);

if(imageInfo.getPhotographedUser() != null) {
String url = ImageUtil.getUserImageDownloadUrl(imageInfo.getId());
dto.setUrl(url);
} else if(imageInfo.getPhotographedSpot() != null) {
String url = ImageUtil.getSpotImageDownloadUrl(imageInfo.getId());
dto.setUrl(url);
} else {
throw new NullPointerException("Invalid image info object (user and spot are null)");
}
return dto;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import com.shulpov.spots_app.spots.models.Spot;
import com.shulpov.spots_app.users.models.User;
import com.shulpov.spots_app.spots.SpotService;
import com.shulpov.spots_app.users.UserService;
import com.shulpov.spots_app.users.services.UserService;
import com.shulpov.spots_app.utils.DtoConverter;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import com.shulpov.spots_app.spots.dto.SpotDto;
import com.shulpov.spots_app.spots.models.Spot;
import com.shulpov.spots_app.users.models.User;
import com.shulpov.spots_app.users.UserService;
import com.shulpov.spots_app.users.services.UserService;
import com.shulpov.spots_app.utils.DtoConverter;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
Expand Down
74 changes: 37 additions & 37 deletions src/main/java/com/shulpov/spots_app/users/UserController.java
Original file line number Diff line number Diff line change
@@ -1,78 +1,69 @@
package com.shulpov.spots_app.users;

import com.shulpov.spots_app.users.dto.UserDto;
import com.shulpov.spots_app.responses.ErrorMessageResponse;
import com.shulpov.spots_app.users.dto.MainUserInfoDto;
import com.shulpov.spots_app.users.exception.UserNotFoundException;
import com.shulpov.spots_app.users.models.User;
import com.shulpov.spots_app.utils.DtoConverter;
import com.shulpov.spots_app.users.services.UserService;
import io.jsonwebtoken.JwtException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
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.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/v1")
@RequestMapping("/api/v1/user")
@Tag(name="Контроллер пользователя", description="Позволяет получать информацию о пользователе и удалять аккаунт")
public class UserController {
private final UserService userService;
private final DtoConverter dtoConverter;
private final Logger logger = LoggerFactory.getLogger(UserController.class);
@Autowired
public UserController(UserService userService, @Lazy DtoConverter dtoConverter) {
public UserController(UserService userService) {
this.userService = userService;
this.dtoConverter = dtoConverter;
}

@Operation(
summary = "Получение полной информации о пользователе",
description = "Позволяет получить полную информацию о пользователе",
security = @SecurityRequirement(name = "accessTokenAuth")
security = @SecurityRequirement(name = "accessTokenAuth"),
responses = {
@ApiResponse(responseCode = "200", description = "Данные пользователя успешно получены",
content = { @Content(mediaType = "application/json",
schema = @Schema(implementation = MainUserInfoDto.class)) }
),
@ApiResponse(responseCode = "400", description = "Пользователь не был найден или получены ошибки JWT",
content = { @Content(mediaType = "application/json",
schema = @Schema(implementation = ErrorMessageResponse.class)) }
)}
)
@GetMapping("/user")
public ResponseEntity<UserDto> getAuthUser() {
logger.atInfo().log("GET /user");
String email;
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
email = userDetails.getUsername();
} catch (UsernameNotFoundException e) {
logger.atInfo().log("GET /user email={} not found");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
Optional<User> userOpt = userService.findByEmail(email);

if(userOpt.isPresent()) {
logger.atInfo().log("principle exists");
User user = userOpt.get();

return new ResponseEntity<>(dtoConverter.userToDto(user), HttpStatus.OK);
}

logger.atInfo().log("GET /user email={} not found", email);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
@GetMapping("/info")
public ResponseEntity<MainUserInfoDto> getAuthUser(
@Parameter(description = "access token")
@RequestHeader("Authorization") String accessToken) {
return ResponseEntity.ok(userService.getMainInfoByAccessToken(accessToken));
}

@Operation(
summary = "Удаление своего пользователя",
description = "Позволяет удалить своего пользователя по токену",
security = @SecurityRequirement(name = "accessTokenAuth")
)
@DeleteMapping("/user")
@DeleteMapping("")
public Map<String, Object> deleteUser() {
logger.atInfo().log("DELETE /user");
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Expand Down Expand Up @@ -101,4 +92,13 @@ public Map<String, Object> deleteUser() {
logger.atError().log("email={} not found", email);
return Map.of("error", "Пользователь не найден");
}

/**
* Обработчик ошибки ненайденного пользователя или Jwt
* @param e исключение, содержащее текст ошибки
*/
@ExceptionHandler({UserNotFoundException.class, JwtException.class})
private ResponseEntity<ErrorMessageResponse> handleJwtExceptionException(Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ErrorMessageResponse(e.getMessage()));
}
}
31 changes: 31 additions & 0 deletions src/main/java/com/shulpov/spots_app/users/dto/MainUserInfoDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.shulpov.spots_app.users.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.shulpov.spots_app.image_infos.dto.ImageInfoDto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;

import java.util.Date;
import java.util.List;

@Setter
@Getter
public class MainUserInfoDto {
@Schema(description = "Имя пользователя", example = "Alex")
private String name;

@Schema(description = "Почта пользователя", example = "alex_green@gmail.com")
private String email;

@Schema(description = "Номер телефона пользователя", example = "89005553535")
private String phoneNumber;

@Schema(description = "Дата рождения пользователя", example = "2000-07-15")
private Date birthday;

@Schema(description = "Дата регистрации пользователя", example = "2022-07-15")
private Date regDate;

@JsonProperty("imageInfoList")
private List<ImageInfoDto> imageInfoDtoList;
}
Loading

0 comments on commit f5cff82

Please sign in to comment.