Skip to content

Commit

Permalink
Merge pull request #96 from Tech-Harbor/Bezsmertnyi
Browse files Browse the repository at this point in the history
Bezsmertnyi
  • Loading branch information
Vladik-gif authored Apr 7, 2024
2 parents 2067f69 + 5a8451c commit 7769c58
Show file tree
Hide file tree
Showing 22 changed files with 296 additions and 39 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.graphql.execution.RuntimeWiringConfigurer;

import static com.example.backend.web.utils.Constants.LOCAL_TIME_DATE;
import static com.example.backend.web.utils.Constants.LOCAL_TIME_DATE_SCALAR;

@Configuration
public class GraphqlConfig {
@Bean
public GraphQLScalarType localDateTimeScalar() {
return GraphQLScalarType.newScalar()
.name("LocalTimeDate")
.description("LocalTimeDate scalar")
.name(LOCAL_TIME_DATE)
.description(LOCAL_TIME_DATE_SCALAR)
.coercing(new LocalDateTimeScalarConfig())
.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
import java.util.Date;
import java.util.Locale;

import static com.example.backend.web.utils.Constants.DATE_FORMAT;


public class LocalDateTimeScalarConfig implements Coercing<LocalDateTime, String> {

Expand All @@ -24,7 +26,7 @@ public class LocalDateTimeScalarConfig implements Coercing<LocalDateTime, String
@NotNull final GraphQLContext graphQLContext,
@NotNull final Locale locale) {

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH);

return format.format(
Date.from(((LocalDateTime) dataFetcherResult)
Expand Down
9 changes: 6 additions & 3 deletions src/main/java/com/example/backend/mail/MailServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
import java.util.Map;
import java.util.Properties;

import static com.example.backend.web.utils.Constants.UTF_8;

@Service
@AllArgsConstructor
public class MailServiceImpl implements MailService {
Expand All @@ -38,7 +40,7 @@ private void sendRegistrationEmail(final UserEntity user) {
String emailContent = getRegistrationEmailContent(user);

MimeMessageHelper helper = new MimeMessageHelper(
mimeMessage, false, "UTF-8"
mimeMessage, false, UTF_8
);

helper.setSubject("Thank you for registration, " + user.getLastname());
Expand All @@ -54,6 +56,7 @@ private String getRegistrationEmailContent(final UserEntity user) {
Map<String, Object> model = new HashMap<>();

model.put("username", user.getLastname());
model.put("jwt", jwtService.generateNewPasswordTokenAndActiveUser(user.getEmail()));

configuration.getTemplate("register.ftlh").process(model, writer);

Expand All @@ -66,7 +69,7 @@ private void sendNewPassword(final UserEntity user) {
String passwordContent = getNewPasswordContent(user);

MimeMessageHelper helper = new MimeMessageHelper(
mimePasswordMessage, false, "UTF-8"
mimePasswordMessage, false, UTF_8
);

helper.setSubject("Account activation, " + user.getLastname());
Expand All @@ -83,7 +86,7 @@ private String getNewPasswordContent(final UserEntity user) {
Map<String, Object> model = new HashMap<>();

model.put("username", user.getLastname());
model.put("jwt", jwtService.generateNewPasswordToken(user.getEmail()));
model.put("jwt", jwtService.generateNewPasswordTokenAndActiveUser(user.getEmail()));

configuration.getTemplate("newPassword.ftlh").process(model, writer);

Expand Down
13 changes: 11 additions & 2 deletions src/main/java/com/example/backend/security/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.example.backend.security;

import com.example.backend.security.exception.AccessDeniedHandlerJwt;
import com.example.backend.security.exception.AuthenticationEntryPointJwt;
import com.example.backend.security.jwt.JwtAuthFilter;
import com.example.backend.security.oauth.AuthGoogle;
import com.example.backend.security.utils.CorsConfig;
Expand All @@ -22,6 +24,8 @@
@RequiredArgsConstructor
public class SecurityConfig {

private final AuthenticationEntryPointJwt authenticationEntryPointJwt;
private final AccessDeniedHandlerJwt accessDeniedHandlerJwt;
private final AuthenticationProvider authProvider;
private final JwtAuthFilter jwtAuthFilter;
private final AuthGoogle authGoogle;
Expand All @@ -35,13 +39,18 @@ public SecurityFilterChain securityFilterChain(final HttpSecurity http) {
.cors(cors -> cors.configurationSource(corsConfig.corsConfigurationSource()))
.httpBasic(Customizer.withDefaults())
.authorizeHttpRequests(request -> request
.requestMatchers("/api/auth/info/**").authenticated()
.requestMatchers("/api/auth/accouth/**").authenticated()
.requestMatchers("/graphiql").permitAll()
.anyRequest()
.permitAll()
)
.exceptionHandling(ex -> ex
.accessDeniedHandler(accessDeniedHandlerJwt)
.authenticationEntryPoint(authenticationEntryPointJwt)
)
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.authenticationProvider(authProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.oauth2Login(oauth -> oauth
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package com.example.backend.security.controllers;

import com.example.backend.security.models.response.ErrorResponse;
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 io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
Expand All @@ -17,26 +20,26 @@
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@RestController
@RequestMapping("/api/auth")
@AllArgsConstructor
@Tag(name = "Authentication", description = "Authentication User and Update Password, personal office users")
public class AuthController {

private final AuthService authService;

private static final String SIGNUP_URI = "/signup";
private static final String LOGIN_URI = "/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 INFO = "/info";
private static final String SIGNUP_URI = "/api/auth/signup";
private static final String LOGIN_URI = "/api/auth/login";
private static final String FORM_CHANGE_PASSWORD_URI = "/api/auth/change-password";
private static final String REQUEST_EMAIL_UPDATE_PASSWORD = "/api/auth/request/email";
private static final String INFO = "/api/auth/accouth";

@PostMapping(SIGNUP_URI)
@SecurityRequirement(name = "Bearer Authentication")
@Operation(summary = "Register user")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Ok"),
@ApiResponse(responseCode = "400", description = "Bad Request"),
@ApiResponse(responseCode = "500", description = "This email has already been used")
}
)
Expand All @@ -49,8 +52,12 @@ public void signup(@RequestBody @Validated final RegisterRequest registerRequest
@Operation(summary = "Login user")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Ok"),
@ApiResponse(responseCode = "400", description = "Bad Request"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
@ApiResponse(responseCode = "401", description = "Unauthorized",
content = {
@Content(mediaType = APPLICATION_JSON_VALUE, schema =
@Schema(implementation = ErrorResponse.class))
}
)
}
)
public AuthResponse login(@RequestBody @Validated final AuthRequest authRequest) {
Expand All @@ -61,7 +68,6 @@ public AuthResponse login(@RequestBody @Validated final AuthRequest authRequest)
@Operation(summary = "Update Password User")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Ok"),
@ApiResponse(responseCode = "400", description = "Bad Request")
}
)
public void updatePassword(@RequestParam final String jwt,
Expand All @@ -73,7 +79,12 @@ public void updatePassword(@RequestParam final String jwt,
@Operation(summary = "Information about the user who is authorized and logged into the system")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Ok"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
@ApiResponse(responseCode = "401", description = "Unauthorized",
content = {
@Content(mediaType = APPLICATION_JSON_VALUE, schema =
@Schema(implementation = ErrorResponse.class))
}
)
}
)
public String info(@AuthenticationPrincipal final UserDetails userDetails) {
Expand All @@ -90,4 +101,21 @@ public String info(@AuthenticationPrincipal final UserDetails userDetails) {
public void requestEmailUpdatePassword(@RequestBody @Validated final EmailRequest emailRequest) {
authService.requestEmailUpdatePassword(emailRequest);
}

@PostMapping()
@Operation(summary = "Active User, JWT Token")
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "Ok",
content =
@Content(mediaType = APPLICATION_JSON_VALUE, schema =
@Schema(implementation = AuthRequest.class)
)
),
}
)
public void activeUser(@RequestParam final String jwt) {
authService.activeUser(jwt);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.example.backend.security.exception;

import com.example.backend.security.models.response.ErrorResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

@Component
public class AccessDeniedHandlerJwt implements AccessDeniedHandler {
@Override
@SneakyThrows
public void handle(final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse,
final AccessDeniedException e) {

httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);

ErrorResponse response = new ErrorResponse(
HttpServletResponse.SC_FORBIDDEN,
"You don't have required role to perform this action."
);

final ObjectMapper mapper = new ObjectMapper();

mapper.writeValue(httpServletResponse.getOutputStream(), response);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.example.backend.security.exception;

import com.example.backend.security.models.response.ErrorResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

@Component
public class AuthenticationEntryPointJwt implements AuthenticationEntryPoint {
@Override
@SneakyThrows
public void commence(final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse,
final AuthenticationException authenticationException) {

httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

ErrorResponse response = new ErrorResponse(
HttpServletResponse.SC_UNAUTHORIZED,
"You need to login first in order to perform this action."
);

final ObjectMapper mapper = new ObjectMapper();

mapper.writeValue(httpServletResponse.getOutputStream(), response);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.example.backend.security.models.response;

import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Builder
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ErrorResponse {
@Schema(example = "404", description = "Статус помилки")
private int status;
@Schema(example = "Error message", description = "Опис помилки")
private String message;
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,47 @@
import com.example.backend.security.models.response.AuthResponse;

public interface AuthService {
/**
* Method for user registration in the system.
*
* @param registerRequest The object containing the data for user registration
* @throws RuntimeException Custom exception thrown if the provided data is invalid or if a
* user with the same email already exists
* @Returns void
*/
void signup(RegisterRequest registerRequest);
/**
* Method for user login authentication and generating access and refresh tokens.
*
* @param authRequest The object containing the user's email and password for authentication
* @throws RuntimeException if user with the provided email is not found
* @Returns AuthResponse containing the generated access and refresh tokens
*/
AuthResponse login(AuthRequest authRequest);
/**
* Method for updating user password.
*
* @param jwt The JWT token used for authentication and authorization
* @param passwordRequest The object containing the new password
* @throws RuntimeException if user with the provided ID is not found
* @Returns void
*/
void formUpdatePassword(String jwt, PasswordRequest passwordRequest);
/**
* Method for requesting email update for password reset.
*
*
* @param emailRequest The object containing the email for which password reset is requested
* @throws RuntimeException if the email does not exist in the system
* @Returns void
*/
void requestEmailUpdatePassword(EmailRequest emailRequest);
/**
* Method for activating a user in the system.
*
* @param jwt The JWT token used for authentication and authorization
* @throws RuntimeException if user with the provided ID is not found
* @Returns void
*/
void activeUser(String jwt);
}
Loading

0 comments on commit 7769c58

Please sign in to comment.