Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

S2US1 #63

Merged
merged 31 commits into from
Apr 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
9f01f39
Changed db structure
Maslyna Apr 3, 2023
b1e4c3e
Changed DB structure
Maslyna Apr 4, 2023
b28a297
Changed data.sql file
Maslyna Apr 4, 2023
287d89d
fix bug with login (#62)
Maslyna Apr 5, 2023
49b1dfc
bugfix: delete didn`t work
Maslyna Apr 5, 2023
0688e41
DB tried to conected to AWS RDS
Maslyna Apr 5, 2023
fccd208
Delete unused files
LordRenDS Apr 5, 2023
04c857a
Delete cors annotation
LordRenDS Apr 5, 2023
88235c2
Add cors to config, add new endpoint to permitAll
LordRenDS Apr 5, 2023
816c733
Add new table for Proofs
LordRenDS Apr 5, 2023
11153a3
Moved file
LordRenDS Apr 5, 2023
d6a62b5
Delete unused variables
LordRenDS Apr 5, 2023
02a1de9
Create ProofDTO, TalentProofController, TalentProofMapper, TalentProo…
LordRenDS Apr 5, 2023
3b5d686
Add mapstruct dependencies
LordRenDS Apr 6, 2023
131568d
Edit dev.pros - change logging level
LordRenDS Apr 6, 2023
2d56d6a
Edit schema.sql: edit Proof table
LordRenDS Apr 6, 2023
dfb0cd9
Edit ProofDTO: add new fields
LordRenDS Apr 6, 2023
08ab3bf
Comment mapper impl
LordRenDS Apr 6, 2023
3737dbd
Create mappers for Talent and TalentProofs with mapstruct
LordRenDS Apr 6, 2023
18ab270
Create mapper for UserInfo with mapstruct
LordRenDS Apr 6, 2023
e926ee5
Comment UserInfo mapper impl
LordRenDS Apr 6, 2023
b5574fa
Remove unused method
LordRenDS Apr 6, 2023
d78c102
Move mapping from service to controller for Talent
LordRenDS Apr 6, 2023
649805c
Change return type for Talent
LordRenDS Apr 6, 2023
5eb82e7
Edit TalentProof: add new fields to Proof entity
LordRenDS Apr 6, 2023
d93a64c
Add pagination for Proofs
LordRenDS Apr 6, 2023
51a48cb
Edit pagination for Proofs: add custom method to Proof repository
LordRenDS Apr 6, 2023
8625aba
Edit role: change String to Enum
LordRenDS Apr 6, 2023
1699d86
Edit TalentProofController
LordRenDS Apr 6, 2023
272d71b
Change version in pom.xml
LordRenDS Apr 6, 2023
dc93e68
Merge branch 'branch-for-merge' into S2US1
LordRenDS Apr 6, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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