Skip to content

Commit

Permalink
Merge pull request #95 from Tech-Harbor/bezsmertnyi/Google
Browse files Browse the repository at this point in the history
Bezsmertnyi
  • Loading branch information
Vladik-gif authored Apr 3, 2024
2 parents 2067f69 + 28944d8 commit 09a2b1d
Show file tree
Hide file tree
Showing 15 changed files with 130 additions and 15 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
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
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 @@ -29,7 +31,8 @@ public class AuthController {
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 REQUEST_ACTIVE_USER = "/acvite/accouth";
private static final String INFO = "/accouth";

@PostMapping(SIGNUP_URI)
@SecurityRequirement(name = "Bearer Authentication")
Expand Down Expand Up @@ -90,4 +93,20 @@ public String info(@AuthenticationPrincipal final UserDetails userDetails) {
public void requestEmailUpdatePassword(@RequestBody @Validated final EmailRequest emailRequest) {
authService.requestEmailUpdatePassword(emailRequest);
}

@PostMapping(REQUEST_ACTIVE_USER)
@Operation(summary = "Active User, JWT Token")
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "Ok",
content = @Content(schema = @Schema(implementation = AuthRequest.class))
),
@ApiResponse(responseCode = "400", description = "Bad Request"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
}
)
public void activeUser(@RequestParam final String jwt){
authService.activeUser(jwt);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,46 @@
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 badRequestException 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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ public interface JwtService {
<T> T extractClaim(String token, Function<Claims, T> claimsResolver);
String generateAccessToken(Authentication authentication);
String generateRefreshToken(Authentication authentication);
String generateNewPasswordToken(String email);
String generateNewPasswordTokenAndActiveUser(String email);
boolean isTokenValid(String token, MyUserDetails userDetails);
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public boolean isCredentialsNonExpired() {

@Override
public boolean isEnabled() {
return true;
return user.getEnabled();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public MyUserDetails build(final UserEntity userEntity) {
.phone(userEntity.getPhone())
.role(userEntity.getRole())
.registerAuthStatus(userEntity.getRegisterAuthStatus())
.enabled(userEntity.getEnabled())
.build())
.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public void signup(final RegisterRequest registerRequest) {
.password(myPasswordEncoder.passwordEncoder().encode(registerRequest.password()))
.phone(registerRequest.phone())
.registerAuthStatus(RegisterAuthStatus.JWT)
.enabled(false)
.role(Role.USER)
.build();

Expand Down Expand Up @@ -102,4 +103,15 @@ public void requestEmailUpdatePassword(final EmailRequest emailRequest) {

mailService.sendEmail(emailUser, MailType.NEW_PASSWORD, new Properties());
}

@Override
public void activeUser(final String jwt) {
final var id = 1L;

final UserEntity activeUserTrue = userService.getById(id);

activeUserTrue.setEnabled(true);

userService.mySave(activeUserTrue);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,11 @@ public String generateRefreshToken(final Authentication authentication) {
}

@Override
public String generateNewPasswordToken(final String email) {
return generateJwtNewPasswordToken(email);
public String generateNewPasswordTokenAndActiveUser(final String email) {
return generateJwtNewPasswordTokenAndActiveUser(email);
}

private String generateJwtNewPasswordToken(final String email) {
private String generateJwtNewPasswordTokenAndActiveUser(final String email) {
return Jwts
.builder()
.subject(email)
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/com/example/backend/web/User/UserEntity.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,6 @@ public class UserEntity {
@Enumerated(value = EnumType.STRING)
@Column(name = "register_status")
private RegisterAuthStatus registerAuthStatus;

private Boolean enabled;
}
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,6 @@ public void deleteByIdUser(final Long id) {
public UserEntity mySave(final UserEntity user) {
return userRepository.save(user);
}


}
4 changes: 4 additions & 0 deletions src/main/java/com/example/backend/web/utils/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,8 @@ public class Constants {
public static final String DEPLOY_STORE = "https://oranger.store/";
public static final String BEARER = "Bearer ";
public static final String PATH = "com.example.backend.web.";
public static final String LOCAL_TIME_DATE = "LocalTimeDate";
public static final String LOCAL_TIME_DATE_SCALAR = "LocalTimeDate scalar";
public static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
public static final String UTF_8 = "UTF-8";
}
4 changes: 3 additions & 1 deletion src/main/resources/templates/register.ftlh
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@
<h1 style="text-align: center">Registration</h1>
<p>Hello, ${username}!</p>
<p>This is a registration form. You can log in and use the online store application.</p>
<a href="https://oranger.store">Oranger</a>
<p>To activate the shape cabinet, follow the link</p>
<a href="https://oranger.store/api/auth/acvite/accouth?jwt=${jwt}">Oranger</a>

</div>
</div>
</body>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@
import java.util.Optional;
import java.util.Properties;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

Expand Down Expand Up @@ -209,6 +208,33 @@ void requestEmailUpdatePasswordTest() {
verify(mailService).sendEmail(userEntity, MailType.NEW_PASSWORD, new Properties());
}

@Test
void activeUserTest() {
final Long userId = 1L;

final UserEntity userNotActive = UserEntity.builder()
.id(userId)
.enabled(false)
.build();

final UserEntity userActive = UserEntity.builder()
.id(userId)
.enabled(true)
.build();

when(userService.getById(userId)).thenReturn(userNotActive);
when(userService.mySave(any(UserEntity.class))).thenAnswer(invocation -> invocation.getArgument(0));

authService.activeUser("jwt");

assertTrue(userNotActive.getEnabled());
assertTrue(userActive.getEnabled());

assertEquals(userNotActive.getEnabled(), userActive.getEnabled());
}



private static final class PasswordEncoderTestUtils implements PasswordEncoder {
@Override
public String encode(final CharSequence rawPassword) {
Expand All @@ -220,4 +246,5 @@ public boolean matches(final CharSequence rawPassword, final String encodedPassw
return rawPassword.toString().equals(encodedPassword);
}
}

}

0 comments on commit 09a2b1d

Please sign in to comment.