Skip to content

Commit

Permalink
Merge pull request #134 from Tech-Harbor/Bezsmertnyi
Browse files Browse the repository at this point in the history
Bezsmertnyi
  • Loading branch information
Vladik-gif authored Jun 15, 2024
2 parents 79f93c4 + 070653a commit 30282f0
Show file tree
Hide file tree
Showing 29 changed files with 95 additions and 63 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.example.backend.security.controllers;
package com.example.backend.security.controller;

import com.example.backend.security.models.request.AuthRequest;
import com.example.backend.security.models.request.EmailRequest;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@
@RequiredArgsConstructor
public class JwtAuthFilter extends OncePerRequestFilter {

private final JwtService jwtService;
private final MyUserDetailsService userDetailsService;
private final JwtService jwtService;

@Override
@SneakyThrows
Expand Down Expand Up @@ -60,7 +60,7 @@ private String getExtractUserData(final String jwt) {
}

private void getSecurityContextHolder(final HttpServletRequest request, final String userData, final String jwt) {
if (StringUtils.isNoneEmpty(userData) && SecurityContextHolder.getContext().getAuthentication() == null) {
if (StringUtils.isNoneEmpty(userData) && isNotAuthenticated()) {

final var userDetails = userDetailsService.loadUserByUsername(userData);

Expand All @@ -79,4 +79,8 @@ private void getSecurityContextHolder(final HttpServletRequest request, final St
}
}
}

private boolean isNotAuthenticated() {
return SecurityContextHolder.getContext().getAuthentication() == null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@
import jakarta.validation.constraints.NotNull;
import lombok.Builder;

import static com.example.backend.utils.general.Constants.EMPTY_FIELD;

@Builder
public record EmailRequest(@NotNull @NotBlank @Email String email) { }
public record EmailRequest(@NotNull @NotBlank(message = EMPTY_FIELD) @Email String email) { }
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
import jakarta.validation.constraints.*;
import lombok.Builder;

import static com.example.backend.utils.general.Constants.EMPTY_FIELD;

@Builder
public record PasswordRequest(
@NotNull @NotBlank @Size(min = 7, max = 20) @Pattern(regexp = "^(?=.*\\d)[A-Za-z\\d]+$") String password) { }
@NotNull @NotBlank(message = EMPTY_FIELD)
@Size(min = 7, max = 20)
@Pattern(regexp = "^(?=.*\\d)[A-Za-z\\d]+$",
message = "password має відповідати вказаному формату") String password) { }
15 changes: 9 additions & 6 deletions src/main/java/com/example/backend/security/oauth/AuthGoogle.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

import com.example.backend.security.service.JwtTokenService;
import com.example.backend.utils.general.MyPasswordEncoder;
import com.example.backend.web.User.store.UserEntity;
import com.example.backend.web.User.UserService;
import com.example.backend.web.User.store.UserEntity;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
Expand All @@ -19,9 +19,11 @@
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.example.backend.utils.enums.RegisterAuthStatus.GOOGLE;
import static com.example.backend.utils.enums.Role.USER;
import static com.example.backend.utils.enums.Status.ONLINE;
import static com.example.backend.utils.general.Constants.*;
import static com.example.backend.utils.general.MyPasswordEncoder.generateRandomPassword;

Expand Down Expand Up @@ -50,7 +52,8 @@ public void onAuthenticationSuccess(final HttpServletRequest request,
userService.getByEmail(defaultOAuth2UserEmail)
.ifPresentOrElse(user -> SecurityContextHolder.getContext().setAuthentication(
createOAuth2AuthenticationToken(
createOAuth2User(user.getRole().name(), defaultOAuth2User), user.getRole().name(),
createOAuth2User(user.getRoles().toString(), defaultOAuth2User),
user.getRoles().toString(),
oAuth2AuthenticationToken.getAuthorizedClientRegistrationId()
)
), () -> {
Expand All @@ -60,9 +63,8 @@ public void onAuthenticationSuccess(final HttpServletRequest request,

SecurityContextHolder.getContext().setAuthentication(
createOAuth2AuthenticationToken(
createOAuth2User(saveUser.getRole().name(), defaultOAuth2User),

saveUser.getRole().name(),
createOAuth2User(saveUser.getRoles().toString(), defaultOAuth2User),
saveUser.getRoles().toString(),

oAuth2AuthenticationToken.getAuthorizedClientRegistrationId()
)
Expand Down Expand Up @@ -94,8 +96,9 @@ private UserEntity createUserEntity(final Map<String, Object> attributes, final
.firstname(attributes.getOrDefault("given_name", EMPTY_LINE).toString())
.lastname(attributes.getOrDefault("family_name", EMPTY_LINE).toString())
.registerAuthStatus(GOOGLE)
.role(USER)
.roles(Set.of(USER))
.enabled(true)
.status(ONLINE)
.createData(LocalDateTime.now())
.password(passwordEncoder.passwordEncoder().encode(generateRandomPassword()))
.phone(attributes.getOrDefault("phone", EMPTY_LINE).toString())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Builder
public record MyUserDetails(UserSecurityDTO user) implements UserDetails {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of(new SimpleGrantedAuthority(user.role().name()));
return user.roles().stream()
.map(role -> new SimpleGrantedAuthority(role.name()))
.collect(Collectors.toSet());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public MyUserDetails build(final UserSecurityDTO user) {
.email(user.email())
.password(user.password())
.phone(user.phone())
.role(user.role())
.roles(user.roles())
.status(user.status())
.enabled(user.enabled())
.build())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@
import org.springframework.stereotype.Service;

import java.util.Properties;
import java.util.Set;

import static com.example.backend.utils.enums.RegisterAuthStatus.JWT;
import static com.example.backend.utils.enums.Role.ADMIN;
import static com.example.backend.utils.enums.Role.USER;
import static com.example.backend.utils.enums.Status.OFFLINE;
import static com.example.backend.utils.exception.RequestException.badRequestException;
Expand Down Expand Up @@ -58,7 +60,7 @@ public void signup(final RegisterRequest registerRequest) {
.phone(registerRequest.phone())
.registerAuthStatus(JWT)
.enabled(false)
.role(USER)
.roles(Set.of(USER, ADMIN))
.status(OFFLINE)
.build();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ private String generateJwtPasswordToken(final UserSecurityDTO userData) {
final Map<String, Object> claims = new HashMap<>();

claims.put(PASSWORD, userData.password());
claims.put(ROLE, userData.role());
claims.put(ROLE, userData.roles());

return Jwts
.builder()
Expand All @@ -64,7 +64,7 @@ private String generateJwtPasswordToken(final UserSecurityDTO userData) {
private String generateJwtEmailToken(final UserSecurityDTO userData) {
final Map<String, Object> role = new HashMap<>();

role.put(ROLE, userData.role());
role.put(ROLE, userData.roles());

return Jwts
.builder()
Expand All @@ -84,7 +84,7 @@ private String generateJwtAccessToken(final Map<String, Object> extraClaims, fin
final var userDetails = (MyUserDetails) authentication.getPrincipal();
final Map<String, Object> role = new HashMap<>();

role.put(ROLE, userDetails.user().role().name());
role.put(ROLE, userDetails.user().roles());

return Jwts
.builder()
Expand All @@ -105,7 +105,7 @@ private String generateJwtRefreshToken(final Map<String, Object> extraClaims, fi
final var userDetails = (MyUserDetails) authentication.getPrincipal();
final Map<String, Object> role = new HashMap<>();

role.put(ROLE, userDetails.user().role().name());
role.put(ROLE, userDetails.user().roles());

return Jwts
.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.example.backend.utils.annotations.ApiResponseCreated;
import com.example.backend.utils.annotations.ApiResponseDelete;
import com.example.backend.utils.annotations.ApiResponseOK;
import com.example.backend.web.Advertisement.store.dto.AdvertisementCreateDTO;
import com.example.backend.web.Advertisement.store.dto.AdvertisementDTO;
import com.example.backend.web.Advertisement.store.dto.AdvertisementUpdateDTO;
Expand All @@ -26,7 +27,7 @@ public class AdvertisementController {
private static final String URL_CREATE = "/createAdvertisement";
private static final String URL_EDIT = "/editAdvertisement";
private static final String URL_DELETE = "/deleteAdvertisement";
public static final String ADVERTISEMENT = "/advertisement";
private static final String ADVERTISEMENT = "/advertisement";
private static final String URL_DELETE_ALL = "/deleteAll";

@PostMapping(value = URL_CREATE, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
Expand All @@ -43,11 +44,13 @@ public List<AdvertisementDTO> getAllAdvertisement() {
}

@GetMapping(ADVERTISEMENT)
@ApiResponseOK
public AdvertisementDTO getByAdvertisement(@RequestHeader(AUTHORIZATION) final String jwt) {
return advertisementService.advertisement(jwt);
}

@PatchMapping(URL_EDIT)
@ApiResponseOK
public AdvertisementUpdateDTO editAdvertisement(@RequestHeader(AUTHORIZATION) final String jwt,
@RequestBody final AdvertisementUpdateDTO entity) {
return advertisementService.editAdvertisement(jwt, entity);
Expand All @@ -61,7 +64,7 @@ public void deleteAdvertisement(@RequestHeader(AUTHORIZATION) final String jwt)

@DeleteMapping(URL_DELETE_ALL)
@ApiResponseDelete
public void deleteAllAdvertisement() {
advertisementService.deleteAll();
public void deleteAllAdvertisement(@RequestHeader(AUTHORIZATION) final String jwt) {
advertisementService.deleteAll(jwt);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ public interface AdvertisementService {
AdvertisementDTO advertisement(String jwt);
AdvertisementUpdateDTO editAdvertisement(String jwt, AdvertisementUpdateDTO entity);
void deleteAdvertisement(String jwt);
void deleteAll();
void deleteAll(String jwt);
}
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,8 @@ public void deleteAdvertisement(final String jwt) {

@Override
@Transactional
public void deleteAll() {
public void deleteAll(final String jwt) {
helpers.tokenUserData(jwt);
advertisementRepository.deleteAll();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public class AdvertisementEntity {
@Column(columnDefinition = "TEXT", nullable = false)
private String descriptionAdvertisement;

@Column(columnDefinition = "TEXT", nullable = false)
@Column(columnDefinition = "TEXT")
private String characteristicAdvertisement; //TODO: Поставити поле на обговорення!

@Column(nullable = false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@

import com.example.backend.utils.annotations.ApiResponseCreated;
import com.example.backend.utils.annotations.ApiResponseDelete;
import com.example.backend.utils.annotations.ApiResponseOK;
import com.example.backend.web.Category.store.dto.CategoryCreateDTO;
import com.example.backend.web.Category.store.dto.CategoryDTO;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

Expand All @@ -20,7 +23,7 @@
public class CategoryController {

private final CategoryServiceImpl categoryService;
private static final String URI_CATEGORIES_ID = "/category/{id}";
private static final String URI_CATEGORIES_NAME = "/category/update";
private static final String URI_CATEGORY = "/category";
private static final String URI_CATEGORIES = "/categories";
private static final String URI_CATEGORY_DELETE = "/category/delete";
Expand All @@ -36,16 +39,19 @@ public CategoryDTO getByNameCategory(@Argument final String name) {
return categoryService.getCategoryDTOName(name);
}

@PostMapping(URI_CATEGORY)
@PostMapping(value = URI_CATEGORY, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
@ApiResponseCreated
public CategoryCreateDTO create(@RequestBody @Validated final CategoryCreateDTO categoryDTO) {
return categoryService.create(categoryDTO);
public CategoryCreateDTO create(@RequestPart @Validated final CategoryCreateDTO categoryDTO,
@RequestPart final MultipartFile image) {
return categoryService.create(categoryDTO, image);
}

@PutMapping(URI_CATEGORIES_ID)
public CategoryCreateDTO update(@PathVariable final Long id,
@RequestBody @Validated final CategoryCreateDTO categoryDTO) {
return categoryService.update(id, categoryDTO);
@PatchMapping(value = URI_CATEGORIES_NAME, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
@ApiResponseOK
public CategoryCreateDTO update(@RequestParam final String name,
@RequestPart @Validated final CategoryCreateDTO categoryDTO,
@RequestPart final MultipartFile image) {
return categoryService.update(name, categoryDTO, image);
}

@DeleteMapping(URI_CATEGORY_DELETE)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
import com.example.backend.web.Category.store.CategoryEntity;
import com.example.backend.web.Category.store.dto.CategoryCreateDTO;
import com.example.backend.web.Category.store.dto.CategoryDTO;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

public interface CategoryService {
List<CategoryDTO> getAll();
CategoryEntity getCategoryName(String name);
CategoryDTO getCategoryDTOName(String name);
CategoryCreateDTO create(CategoryCreateDTO categoryDTO);
CategoryCreateDTO update(Long categoryId, CategoryCreateDTO categoryDTO);
CategoryCreateDTO create(CategoryCreateDTO categoryDTO, MultipartFile image);
CategoryCreateDTO update(String name, CategoryCreateDTO categoryDTO, MultipartFile image);
void deleteCategory(CategoryDTO categoryDTO);
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
import com.example.backend.web.File.ImageService;
import jakarta.transaction.Transactional;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -42,28 +44,32 @@ public CategoryDTO getCategoryDTOName(final String name) {

@Override
@Transactional
public CategoryCreateDTO create(final CategoryCreateDTO categoryDTO) {
final var newImage = imageService.getByImage(categoryDTO.image());
public CategoryCreateDTO create(final CategoryCreateDTO categoryDTO, final MultipartFile image) {
final var newImage = imageService.uploadImageEntity(image);

final var newCategory = CategoryEntity.builder()
.name(categoryDTO.name())
.image(newImage)
.color(categoryDTO.color())
.build();

return categoryCreateFactory.apply(categoryRepository.save(newCategory));
}

@Override
@Transactional
public CategoryCreateDTO update(final Long categoryId, final CategoryCreateDTO categoryDTO) {
final var updateImage = imageService.getByImage(categoryDTO.image());

final var category = categoryRepository.getReferenceById(categoryId);

category.setName(categoryDTO.name());
category.setImage(updateImage);
category.setColor(categoryDTO.color());
public CategoryCreateDTO update(final String name,
final CategoryCreateDTO categoryDTO,
final MultipartFile image) {
final var category = getCategoryName(name);
final var uploadImage = imageService.uploadImageEntity(image);

if (StringUtils.isNoneEmpty(categoryDTO.name())) {
category.setName(categoryDTO.name());
}

if (StringUtils.isNoneEmpty(categoryDTO.image())) {
category.setImage(uploadImage);
}

return categoryCreateFactory.apply(categoryRepository.save(category));
}
Expand Down
Loading

0 comments on commit 30282f0

Please sign in to comment.