Skip to content

Commit

Permalink
Merge pull request #121 from Tech-Harbor/Bezsmertnyi | Update ProjectAll
Browse files Browse the repository at this point in the history
Bezsmertnyi | Update ProjectAll
  • Loading branch information
Vladik-gif authored May 6, 2024
2 parents df12c29 + 723ff02 commit 82896ff
Show file tree
Hide file tree
Showing 70 changed files with 419 additions and 620 deletions.
5 changes: 0 additions & 5 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,6 @@ dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

//GOOGLE
dependencies {
implementation group: 'com.google.api-client', name: 'google-api-client', version: '2.2.0'
}

tasks.named('test') {
useJUnitPlatform()
}
Expand Down
17 changes: 16 additions & 1 deletion documentation/API.http
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,19 @@ Authorization: Bearer

###Accouth
GET http://localhost:8080/api/accouth
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer
Content-Type: application/json

###GRAPHQL
GRAPHQL http://localhost:8080/graphql

query {
getAllProducts {
name
price
location
images {
imageUrl
}
}
}
1 change: 1 addition & 0 deletions documentation/Requirements.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

1 Архітектура API
1.1 Кожен пакет проекту повинен відноситися лише до одної логіки цього пакету.
1.2 Оновлювати архітектуру API, лише за потребою або в ході розробки API та повідомити про це: Team Lead
2 Класи і методи API
2.1 Класи
2.1.1 Кожна назва класу повинена передати всю логіку цього класу.
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/example/backend/mail/MailService.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package com.example.backend.mail;

import com.example.backend.web.User.UserEntity;
import com.example.backend.web.User.store.dto.UserSecurityDTO;

import java.util.Properties;

public interface MailService {
void sendEmail(UserEntity user, MailType type, Properties params);
void sendEmail(UserSecurityDTO user, MailType type, Properties params);
}
32 changes: 14 additions & 18 deletions src/main/java/com/example/backend/mail/MailServiceImpl.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.example.backend.mail;

import com.example.backend.security.service.JwtTokenService;
import com.example.backend.web.User.UserEntity;
import com.example.backend.web.User.store.dto.UserSecurityDTO;
import freemarker.template.Configuration;
import jakarta.mail.internet.MimeMessage;
import lombok.AllArgsConstructor;
Expand All @@ -27,7 +27,7 @@ public class MailServiceImpl implements MailService {
private JavaMailSender mailSender;

@Override
public void sendEmail(final UserEntity user, final MailType type, final Properties params) {
public void sendEmail(final UserSecurityDTO user, final MailType type, final Properties params) {
switch (type) {
case REGISTRATION -> sendRegistrationEmail(user);
case NEW_PASSWORD -> sendNewPassword(user);
Expand All @@ -36,27 +36,25 @@ public void sendEmail(final UserEntity user, final MailType type, final Properti
}

@SneakyThrows
private void sendRegistrationEmail(final UserEntity user) {
private void sendRegistrationEmail(final UserSecurityDTO user) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
String emailContent = getRegistrationEmailContent(user);

MimeMessageHelper helper = new MimeMessageHelper(
mimeMessage, false, UTF_8
);
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false, UTF_8);

helper.setSubject("???, " + user.getLastname());
helper.setTo(user.getEmail());
helper.setSubject("???, " + user.lastname());
helper.setTo(user.email());
helper.setText(emailContent, true);

mailSender.send(mimeMessage);
}

@SneakyThrows
private String getRegistrationEmailContent(final UserEntity user) {
private String getRegistrationEmailContent(final UserSecurityDTO user) {
StringWriter writer = new StringWriter();
Map<String, Object> model = new HashMap<>();

model.put("username", user.getLastname());
model.put("username", user.lastname());
model.put(JWT, jwtTokenService.generateUserEmailDataToken(user));

configuration.getTemplate("register.ftlh").process(model, writer);
Expand All @@ -65,28 +63,26 @@ private String getRegistrationEmailContent(final UserEntity user) {
}

@SneakyThrows
private void sendNewPassword(final UserEntity user) {
private void sendNewPassword(final UserSecurityDTO user) {
MimeMessage mimePasswordMessage = mailSender.createMimeMessage();
String passwordContent = getNewPasswordContent(user);

MimeMessageHelper helper = new MimeMessageHelper(
mimePasswordMessage, false, UTF_8
);
MimeMessageHelper helper = new MimeMessageHelper(mimePasswordMessage, false, UTF_8);

helper.setSubject("Update Password, " + user.getLastname());
helper.setTo(user.getEmail());
helper.setSubject("Update Password, " + user.lastname());
helper.setTo(user.email());
helper.setText(passwordContent, true);

mailSender.send(mimePasswordMessage);
}

@SneakyThrows
private String getNewPasswordContent(final UserEntity user) {
private String getNewPasswordContent(final UserSecurityDTO user) {
StringWriter writer = new StringWriter();

Map<String, Object> model = new HashMap<>();

model.put("username", user.getLastname());
model.put("username", user.lastname());
model.put(JWT, jwtTokenService.generateUserPasswordDataToken(user));

configuration.getTemplate("newPassword.ftlh").process(model, writer);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
Expand All @@ -19,6 +20,8 @@
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import static com.example.backend.utils.general.Constants.GET_AUTH;
import static com.example.backend.utils.general.Constants.PERMIT_ALL;

@Configuration
@EnableWebSecurity
Expand All @@ -42,8 +45,8 @@ public SecurityFilterChain securityFilterChain(final HttpSecurity http) {
)
.httpBasic(Customizer.withDefaults())
.authorizeHttpRequests(request -> request
.requestMatchers("/api/accouth/**").authenticated()
.requestMatchers("/graphiql").permitAll()
.requestMatchers(HttpMethod.GET, GET_AUTH).authenticated()
.requestMatchers(PERMIT_ALL).permitAll()
.anyRequest()
.permitAll()
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
package com.example.backend.security.controllers;

import com.example.backend.security.models.request.*;
import com.example.backend.security.models.request.AuthRequest;
import com.example.backend.security.models.request.EmailRequest;
import com.example.backend.security.models.request.PasswordRequest;
import com.example.backend.security.models.request.RegisterRequest;
import com.example.backend.security.models.response.AuthResponse;
import com.example.backend.security.service.AuthService;
import com.example.backend.security.service.GoogleService;
import com.example.backend.utils.annotations.*;
import com.example.backend.web.User.UserEntity;
import com.example.backend.web.User.store.dto.UserInfoDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static com.example.backend.utils.general.Constants.BEARER_AUTHENTICATION;
import static org.springframework.http.HttpHeaders.AUTHORIZATION;

@RestController
Expand All @@ -26,32 +27,29 @@
public class AuthController {

private final AuthService authService;
private final GoogleService googleService;

private static final String SIGNUP_URI = "/auth/signup";
private static final String LOGIN_URI = "/auth/login";
private static final String GOOGLE_LOGIN = "/auth/google/login";
private static final String FORM_CHANGE_PASSWORD_URI = "/change-password";
private static final String REQUEST_EMAIL_UPDATE_PASSWORD = "/request/email";
private static final String ACTIVE_USER = "/active";
private static final String INFO = "/accouth";
private static final String SEND_MESSAGE_EMAIL_NOT_ACTIVE = "/sendMessageEmailActive";

@PostMapping(SIGNUP_URI)
@SecurityRequirement(name = "Bearer Authentication")
@SecurityRequirement(name = BEARER_AUTHENTICATION)
@Operation(summary = "Register user")
@ApiResponseOK
@ApiResponseCreated
@ApiResponseBadRequest
public void signup(@RequestBody @Validated final RegisterRequest registerRequest) {
authService.signup(registerRequest);
}

@PostMapping(LOGIN_URI)
@SecurityRequirement(name = "Bearer Authentication")
@SecurityRequirement(name = BEARER_AUTHENTICATION)
@Operation(summary = "Login user")
@ApiResponseOK
@ApiResponseUnauthorized
@ApiResponseNotFound
@ApiResponseForbidden
public AuthResponse login(@RequestBody @Validated final AuthRequest authRequest) {
return authService.login(authRequest);
Expand All @@ -69,10 +67,9 @@ public void updatePassword(@RequestHeader(AUTHORIZATION) final String jwt,

@GetMapping(INFO)
@Operation(summary = "Information about the user who is authorized and logged into the system")
@ApiResponseUnauthorized
@ApiResponseOK
public String info(@AuthenticationPrincipal final UserDetails userDetails) {
return userDetails.getUsername();
@ApiResponseInfoOK
public UserInfoDTO info(@RequestHeader(AUTHORIZATION) final String accessToken) {
return authService.info(accessToken);
}

@PostMapping(REQUEST_EMAIL_UPDATE_PASSWORD)
Expand All @@ -98,11 +95,4 @@ public void activeUser(@RequestHeader(AUTHORIZATION) final String jwt) {
public void sendEmailSecondActive(@RequestBody @Validated final EmailRequest emailRequest) {
authService.sendEmailActive(emailRequest);
}

@PostMapping(GOOGLE_LOGIN)
@Operation(summary = "Google Login (Beta Version)")
@ApiResponseOK
public UserEntity googleLogin(@RequestBody final GoogleTokenRequest token) {
return googleService.googleLogin(token);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ public void handle(final HttpServletRequest httpServletRequest,
httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);

ErrorResponse response = ErrorResponse.builder()
final var response = ErrorResponse.builder()
.status(HttpServletResponse.SC_FORBIDDEN)
.message("You don't have required role to perform this action.")
.build();

final ObjectMapper mapper = new ObjectMapper();
final var mapper = new ObjectMapper();

mapper.writeValue(httpServletResponse.getOutputStream(), response);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ public void commence(final HttpServletRequest httpServletRequest,
httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

ErrorResponse response = ErrorResponse.builder()
.status(HttpServletResponse.SC_FORBIDDEN)
final var response = ErrorResponse.builder()
.status(HttpServletResponse.SC_UNAUTHORIZED)
.message("You need to login first in order to perform this action.")
.build();

final ObjectMapper mapper = new ObjectMapper();
final var mapper = new ObjectMapper();

mapper.writeValue(httpServletResponse.getOutputStream(), response);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import com.example.backend.security.service.JwtTokenService;
import com.example.backend.utils.general.MyPasswordEncoder;
import com.example.backend.web.User.UserEntity;
import com.example.backend.web.User.store.UserEntity;
import com.example.backend.web.User.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
Expand Down Expand Up @@ -56,7 +56,7 @@ public void onAuthenticationSuccess(final HttpServletRequest request,
), () -> {
final var saveUser = createUserEntity(defaultOAuth2User, defaultOAuth2UserEmail);

userService.mySave(saveUser);
userService.mySecuritySave(saveUser);

SecurityContextHolder.getContext().setAuthentication(
createOAuth2AuthenticationToken(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.example.backend.security.models.request.PasswordRequest;
import com.example.backend.security.models.request.RegisterRequest;
import com.example.backend.security.models.response.AuthResponse;
import com.example.backend.web.User.store.dto.UserInfoDTO;

public interface AuthService {
/**
Expand Down Expand Up @@ -54,4 +55,12 @@ public interface AuthService {
* This method sends a letter to the user's mail if he did not have time to activate the account the first time
*/
void sendEmailActive(EmailRequest emailRequest);
/**
* Retrieves user information based on a JWT token.
*
* @param accessToken The JWT token used for identifying and extracting user data
* @return UserInfoDTO containing the user's information
* @throws RuntimeException if a user with the extracted data is not found
*/
UserInfoDTO info(String accessToken);
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.example.backend.security.service;

import com.example.backend.web.User.UserEntity;
import com.example.backend.web.User.store.dto.UserSecurityDTO;
import org.springframework.security.core.Authentication;

public interface JwtTokenService {
Expand All @@ -23,17 +23,17 @@ public interface JwtTokenService {
* The token includes information such as the password and email of the user,
* along with issued-at and expiration times.
*
* @param userData The UserEntity object representing the user for whom the token is being generated.
* @param userData The UserSecurityDTO object representing the user for whom the token is being generated.
* @return The generated JWT token as a String.
*/
String generateUserPasswordDataToken(UserEntity userData);
String generateUserPasswordDataToken(UserSecurityDTO userData);
/**
* Generates a JWT token with the user's email as the subject.
* The token includes details about when it was issued and when it will expire.
* This JWT can be used for authentication or verification purposes.
*
* @param userData The UserEntity object representing the user whose email will be used as the subject.
* @param userData The UserSecurityDTO object representing the user whose email will be used as the subject.
* @return The generated JWT token as a String.
*/
String generateUserEmailDataToken(UserEntity userData);
String generateUserEmailDataToken(UserSecurityDTO userData);
}
Loading

0 comments on commit 82896ff

Please sign in to comment.