Skip to content

Commit

Permalink
S2US1 (#63)
Browse files Browse the repository at this point in the history
* Changed db structure

* Changed DB structure

* Changed data.sql file

* fix bug with login (#62)

Co-authored-by: Denis Boyko <[email protected]>

* bugfix: delete didn`t work

* DB tried to conected to AWS RDS
DB bugfix

* Delete unused files

* Delete cors annotation

* Add cors to config, add new endpoint to permitAll

* Add new table for Proofs

* Moved file

* Delete unused variables

* Create ProofDTO, TalentProofController, TalentProofMapper, TalentProof entity, TalentProofService and TalentProofRepository

* Add mapstruct dependencies

* Edit dev.pros - change logging level

* Edit schema.sql: edit Proof table

* Edit ProofDTO: add new fields

* Comment mapper impl

* Create mappers for Talent and TalentProofs with mapstruct

* Create mapper for UserInfo with mapstruct

* Comment UserInfo mapper impl

* Remove unused method

* Move mapping from service to controller for Talent

* Change return type for Talent

* Edit TalentProof: add new fields to Proof entity

* Add pagination for Proofs

* Edit pagination for Proofs: add custom method to Proof repository

* Edit role: change String to Enum

* Edit TalentProofController

* Change version in pom.xml

---------

Co-authored-by: Maslyna <[email protected]>
Co-authored-by: Mykhailo Ordyntsev <[email protected]>
Co-authored-by: Denis Boyko <[email protected]>
  • Loading branch information
4 people authored Apr 6, 2023
1 parent 0d2a94d commit 2252c60
Show file tree
Hide file tree
Showing 39 changed files with 670 additions and 449 deletions.
45 changes: 32 additions & 13 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,13 @@
</parent>
<groupId>com.provedcode</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<version>0.1.1-SNAPSHOT</version>
<name>ProvedCode</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springdoc/springdoc-openapi-starter-webmvc-ui -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
Expand Down Expand Up @@ -74,20 +68,45 @@
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.6.0</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.3.Final</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<excludes>
<exclude>
<source>17</source> <!-- depending on your project -->
<target>17</target> <!-- depending on your project -->
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
<version>1.18.26</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.3.Final</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>0.2.0</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/provedcode/ProvedCodeApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

@SpringBootApplication
@ConfigurationPropertiesScan
public class ProvedCodeApplication {
public class ProvedCodeApplication {

public static void main(String[] args) {
SpringApplication.run(ProvedCodeApplication.class, args);
Expand Down
62 changes: 52 additions & 10 deletions src/main/java/com/provedcode/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.provedcode.user.mapper.UserInfoMapper;
import com.provedcode.user.repo.UserInfoRepository;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
Expand All @@ -25,6 +28,8 @@
import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint;
import org.springframework.security.oauth2.server.resource.web.access.BearerTokenAccessDeniedHandler;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
Expand All @@ -34,37 +39,74 @@
import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS;
import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher;

@Slf4j
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
//http://localhost:8080/swagger-ui/index.html
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(c -> c
.requestMatchers("/actuator/health").permitAll() // for DevOps
.requestMatchers(antMatcher("/h2/**")).permitAll()
.requestMatchers(antMatcher("/api/talents/**")).permitAll()
.requestMatchers(antMatcher("/v3/api-docs/**")).permitAll() // for openAPI
.requestMatchers(antMatcher("/swagger-ui/**")).permitAll() // for openAPI
.requestMatchers(antMatcher("/swagger-ui.html")).permitAll() // for openAPI
.requestMatchers(antMatcher("/error")).permitAll()
.anyRequest().authenticated()
);

http.exceptionHandling(c -> c
.authenticationEntryPoint((request, response, authException) -> {
log.info("Authentication failed {}, message:{}",
describe(request),
authException.getMessage());
response.sendError(
HttpStatus.UNAUTHORIZED.value(),
authException.getMessage());
}
)
.accessDeniedHandler((request, response, accessDeniedException) -> {
log.info("Authorization failed {},message: {}",
describe(request),
accessDeniedException.getMessage());
response.sendError(HttpStatus.FORBIDDEN.value(),
accessDeniedException.getMessage());
}
)
);

http.httpBasic(Customizer.withDefaults());
http.csrf().disable().headers().disable();
http.cors();


http.sessionManagement().sessionCreationPolicy(STATELESS);

http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
.exceptionHandling(c -> c
.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
.accessDeniedHandler(new BearerTokenAccessDeniedHandler())
);
.exceptionHandling(c -> c
.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
.accessDeniedHandler(new BearerTokenAccessDeniedHandler())
);

return http.build();
}

@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*");
}
};
}

public String describe(HttpServletRequest request) {
return request.getRequestURI();
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
Expand Down Expand Up @@ -93,8 +135,8 @@ UserDetailsService userDetailsService(
UserInfoMapper mapper
) {
return login -> repository.findByLogin(login)
.map(mapper::toUserDetails)
.orElseThrow(() -> new UsernameNotFoundException(login + " not found"));
.map(mapper::toUserDetails)
.orElseThrow(() -> new UsernameNotFoundException(login + " not found"));
}

@Bean
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.provedcode.talent;
package com.provedcode.talent.controller;

import com.provedcode.talent.mapper.TalentMapper;
import com.provedcode.talent.model.dto.FullTalentDTO;
import com.provedcode.talent.model.dto.ShortTalentDTO;
import com.provedcode.talent.service.TalentService;
Expand All @@ -18,31 +19,32 @@
@Slf4j
@RestController
@AllArgsConstructor
@CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT,
RequestMethod.DELETE})
@RequestMapping("/api")
public class TalentController {
TalentService talentService;
TalentMapper talentMapper;

@PreAuthorize("hasRole('TALENT')")
@GetMapping("/talents/{id}")
FullTalentDTO getTalent(@PathVariable("id") long id) {
return talentService.getTalentById(id);
FullTalentDTO getTalent(@PathVariable("id") long id, Authentication authentication) {
log.info("get-talent auth = {}", authentication);
log.info("get-talent auth.name = {}", authentication.getAuthorities());
return talentMapper.talentToFullTalentDTO(talentService.getTalentById(id));
}

@GetMapping("/talents")
@ResponseStatus(HttpStatus.OK)
Page<ShortTalentDTO> getTalents(@RequestParam(value = "page") Optional<Integer> page,
@RequestParam(value = "size") Optional<Integer> size) {
return talentService.getTalentsPage(page, size);
return talentService.getTalentsPage(page, size).map(talentMapper::talentToShortTalentDTO);
}

@PreAuthorize("hasRole('TALENT')")
@PatchMapping("/talents/{talent-id}")
FullTalentDTO editTalent(@PathVariable("talent-id") long id,
@RequestBody @Valid FullTalentDTO fullTalent,
Authentication authentication) {
return talentService.editTalent(id, fullTalent, authentication);
return talentMapper.talentToFullTalentDTO(talentService.editTalent(id, fullTalent, authentication));
}

@PreAuthorize("hasRole('TALENT')")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.provedcode.talent.controller;

import com.provedcode.talent.mapper.TalentProofMapper;
import com.provedcode.talent.model.dto.ProofDTO;
import com.provedcode.talent.service.TalentProofService;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController
@AllArgsConstructor
@RequestMapping("/api/talents")
public class TalentProofController {
TalentProofService talentProofService;
TalentProofMapper talentProofMapper;

@GetMapping("/proofs")
Page<ProofDTO> getAllProofs(@RequestParam(value = "page") Optional<Integer> page,
@RequestParam(value = "size") Optional<Integer> size) {
return talentProofService.getAllProofsPage(page, size).map(talentProofMapper::toProofDTO);
}
}
24 changes: 22 additions & 2 deletions src/main/java/com/provedcode/talent/mapper/TalentMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,30 @@
import com.provedcode.talent.model.dto.FullTalentDTO;
import com.provedcode.talent.model.dto.ShortTalentDTO;
import com.provedcode.talent.model.entity.*;
import org.mapstruct.Mapper;
import org.mapstruct.MappingConstants;
import org.mapstruct.ReportingPolicy;

@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = MappingConstants.ComponentModel.SPRING)
public interface TalentMapper {
default FullTalentDTO talentToFullTalentDTO(Talent talent) {
return FullTalentDTO.builder()
.id(talent.getId())
.firstName(talent.getFirstName())
.lastName(talent.getLastName())
.bio(talent.getTalentDescription() != null ? talent.getTalentDescription().getBio() : null)
.additionalInfo(talent.getTalentDescription() != null ? talent.getTalentDescription()
.getAdditionalInfo() : null)
.image(talent.getImage())
.specialization(talent.getSpecialization())
.links(talent.getTalentLinks().stream().map(TalentLink::getLink).toList())
.contacts(talent.getTalentContacts().stream().map(TalentContact::getContact).toList())
.talents(talent.getTalentTalents().stream().map(TalentTalents::getTalentName).toList())
.attachedFiles(
talent.getTalentAttachedFiles().stream().map(TalentAttachedFile::getAttachedFile)
.toList())
.build();
}

ShortTalentDTO talentToShortTalentDTO(Talent talent);
FullTalentDTO talentToFullTalentDTO(Talent talent);

}
20 changes: 20 additions & 0 deletions src/main/java/com/provedcode/talent/mapper/TalentProofMapper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.provedcode.talent.mapper;

import com.provedcode.talent.model.dto.ProofDTO;
import com.provedcode.talent.model.entity.TalentProof;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingConstants;
import org.mapstruct.ReportingPolicy;

@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = MappingConstants.ComponentModel.SPRING)
public interface TalentProofMapper {
@Mapping(source = "talentId", target = "id")
@Mapping(source = "created", target = "created", dateFormat = "dd-MM-yyyy HH:mm:ss")
ProofDTO toProofDTO(TalentProof talentProof);

@Mapping(source = "id", target = "talentId")
@Mapping(target = "id", ignore = true)
@Mapping(source = "created", target = "created", dateFormat = "dd-MM-yyyy HH:mm:ss")
TalentProof toTalentProof(ProofDTO proofDTO);
}
Loading

0 comments on commit 2252c60

Please sign in to comment.