Skip to content

Commit

Permalink
Fixing mapper
Browse files Browse the repository at this point in the history
Problem in maven
  • Loading branch information
iwokonl committed Mar 1, 2024
1 parent ea59076 commit 331fb2c
Show file tree
Hide file tree
Showing 9 changed files with 191 additions and 20 deletions.
55 changes: 41 additions & 14 deletions Back/Spring/backend/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -67,28 +67,42 @@
<artifactId>postgresql</artifactId>
<version>42.7.1</version>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
<scope>provided</scope>
</dependency>
<!-- Spring Boot Starter Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.2.Final</version>
<version>1.5.5.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-jdk8 -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.5.5.Final</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-processor -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.4.2.Final</version>
<scope>provided</scope>
<version>1.5.5.Final</version>
</dependency>

<!-- JSON Web Token Support -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.12.5</version>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.3.0</version>
</dependency>

<!-- Spring Kafka -->
Expand All @@ -109,12 +123,7 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
Expand All @@ -138,7 +147,25 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version> <!-- Upewnij się, że używasz odpowiedniej wersji -->
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.5.Final</version> <!-- Zaktualizuj wersję MapStruct zgodnie z używaną w zależnościach -->
</path>
</annotationProcessorPaths>
</configuration>
</plugin>

</plugins>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package pl.zeto.backend.VMC.config;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@RequiredArgsConstructor
public class JwtAuthFilter extends OncePerRequestFilter {

private final UserAuthProvider userAuthProvider;


@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (header != null) {
String[] authElements = header.split(" ");
if (authElements.length == 2 && "Bearer".equals(authElements[0])) {
try{
SecurityContextHolder.getContext().setAuthentication(userAuthProvider.validateToken(authElements[1]));
} catch (RuntimeException e) {
SecurityContextHolder.clearContext();
throw e;
}
}
}
filterChain.doFilter(request, response);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package pl.zeto.backend.VMC.config;

import jakarta.persistence.Basic;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
Expand All @@ -9,15 +10,18 @@
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

@RequiredArgsConstructor
@Configuration
@EnableWebSecurity
public class SecurityConfig {

private final UserAuthProvider userAuthProvider;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { // Konfiguracja zabezpieczeń

httpSecurity.csrf(AbstractHttpConfigurer::disable) // Ochrona CSRF wyłączona
.addFilterBefore(new JwtAuthFilter(userAuthProvider), BasicAuthenticationFilter.class) // Dodanie filtra autoryzacji
.sessionManagement(customizer -> customizer.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // Wyłączenie zarządzania sesją
.authorizeHttpRequests(request -> // Konfiguracja zabezpieczeń
request.requestMatchers(HttpMethod.POST, "/login", "/register").permitAll() // Pozwala na wykonywanie zapytań POST na adresach: /login, /register
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package pl.zeto.backend.VMC.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import lombok.RequiredArgsConstructor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import pl.zeto.backend.VMC.dto.UserDto;

import java.util.Base64;
import java.util.Collections;
import java.util.Date;

@RequiredArgsConstructor
@Component
public class UserAuthProvider {
@Value("${security.jwt.token.secret-key:secret-key}")
private String secretKey;

@PostConstruct
public void init() {
secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes());

}

public String createToken(UserDto dto) {
Date now = new Date();
Date validity = new Date(now.getTime() + 3600000);
return JWT.create()
.withIssuer(dto.getUsername())
.withIssuedAt(now)
.withExpiresAt(validity)
.withClaim("firstName", dto.getFirstName())
.withClaim("lastName", dto.getLastName())
.sign(Algorithm.HMAC256(secretKey));

}

public Authentication validateToken(String token) {
Algorithm algorithm = Algorithm.HMAC256(secretKey);

JWTVerifier verifier = JWT.require(algorithm).build();

DecodedJWT decodedJWT = verifier.verify(token);

UserDto user = UserDto.builder()
.username(decodedJWT.getIssuer())
.firstName(decodedJWT.getClaim("firstName").asString())
.lastName(decodedJWT.getClaim("lastName").asString())
.build();
return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import pl.zeto.backend.VMC.config.UserAuthProvider;
import pl.zeto.backend.VMC.dto.CredentialsDto;
import pl.zeto.backend.VMC.dto.SignUpDto;
import pl.zeto.backend.VMC.dto.UserDto;
Expand All @@ -16,16 +17,18 @@
@RequiredArgsConstructor
public class AuthController {
private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

private final UserAuthProvider userAuthProvider;
private final UserService userService;
@PostMapping("/login")
public ResponseEntity<UserDto> login(@RequestBody CredentialsDto coridentialsDto) {
UserDto user = userService.login(coridentialsDto);
user.setToken(userAuthProvider.createToken(user));
return ResponseEntity.ok(user);
}
@PostMapping("/register")
public ResponseEntity<UserDto> register(@RequestBody SignUpDto signUpDto) {
UserDto user = userService.register(signUpDto);
user.setToken(userAuthProvider.createToken(user));
return ResponseEntity.created(URI.create("/users/" + user.getId())).body(user);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
package pl.zeto.backend.VMC.dto;

public record SignUpDto (String firstName, String lastName,String email,String username, char[] password){ // Niemutowalna klasa przechowująca dane rejestracji
public record SignUpDto (String firstName, String lastName,String email,String username, char[] password){// Niemutowalna klasa przechowująca dane rejestracji

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,53 @@
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.springframework.stereotype.Component;

import pl.zeto.backend.VMC.dto.SignUpDto;
import pl.zeto.backend.VMC.dto.UserDto;
import pl.zeto.backend.VMC.model.AppUser;
import pl.zeto.backend.VMC.service.UserService;

@Mapper(componentModel="spring", uses= UserService.class)
@Mapper(componentModel="spring")
@Component
public interface UserMapper { // Interfejs mapujący obiekty użytkownika na obiekty DTO
UserDto toUserDto(AppUser appUser);

// Ten mapping może się bugować ponieważ lombok ładuje się później niż mapstruct i mapstruck chce
// pobrać pole password z klasy AppUser, które jest prywatne, a lombok nie generuje gettera dla tego pola w czasie
// uruchomienia aplikacji. Więc dlatego trzeba dodać do pom.xml
/*
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version> <!-- Upewnij się, że używasz odpowiedniej wersji -->
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.5.Final</version> <!-- Zaktualizuj wersję MapStruct zgodnie z używaną w zależnościach -->
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
*/
@Mapping(target = "password", ignore = true)
AppUser signUpToUserr(SignUpDto signUpDto);
AppUser signUpToUser(SignUpDto signUpDto);


}
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,11 @@ public UserDto register(SignUpDto signUpDto) {
if (oUser.isPresent()) {
throw new AppExeption("User already exists", HttpStatus.BAD_REQUEST);
}
AppUser user = userMapper.signUpToUserr(signUpDto);
AppUser user = userMapper.signUpToUser(signUpDto);
user.setPassword(passwordEncoder.encode(CharBuffer.wrap(signUpDto.password())));
user.setRole(Role.USER);
user.setPassword(passwordEncoder.encode(CharBuffer.wrap(signUpDto.password())));

user.setUsername(signUpDto.username());
AppUser savedUser = userRepository.save(user);
AppAccount account = new AppAccount();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ spring.datasource.driver-class-name=org.postgresql.Driver
#spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

logging.level.org.hibernate.type=TRACE
#logging.level.org.hibernate.SQL=DEBUG

Expand Down

0 comments on commit 331fb2c

Please sign in to comment.