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

test code #6

Merged
merged 16 commits into from
Oct 31, 2023
Merged

test code #6

merged 16 commits into from
Oct 31, 2023

Conversation

don-bigdad
Copy link
Owner

No description provided.

private String lastName;
private String shippingAddress;

@ManyToMany(fetch = FetchType.EAGER)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can delete FetchType.Eager and use @entitygraph(attributePaths = "roles") in UsersRepository on findByEmail() method, it will initialize roles when the method is called

Copy link

@Elena-Bruyako Elena-Bruyako left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good job! Let's improve your code)

Wrong link to HW

@RestController
@Validated
@RequestMapping(value = "/auth")
public class AuthenticationController {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to add Tag annotation here?

@@ -41,6 +42,7 @@ public List<BookDto> getAll(@PageableDefault(size = 5, page = 0)
}

@DeleteMapping(value = "/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to add ROLE_USER for some endpoint?

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;

public record UserLoginRequestDto(@NotNull @Email String email,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@NotBlank will be better

import jakarta.validation.constraints.NotNull;

public record UserLoginRequestDto(@NotNull @Email String email,
@NotNull String password) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the same

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;

@FieldMatch

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
@FieldMatch
@FieldMatch(fields = {"password", "repeatPassword"})


@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove empty line


@Repository
public interface UserRepository extends JpaRepository<User, Long> {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the same

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

Optional<User> findByEmail(String email);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can add @EntityGraph(attributePaths = "roles") to avoid declare Eager fetch type in your entity

}

private static String getToken(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

authorizationHeader will be more correct by meaning

}
User user = userMapper.toUserModel(requestDto);
user.setPassword(passwordEncoder.encode(requestDto.password()));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove empty line

Copy link

@Elena-Bruyako Elena-Bruyako left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good job! Let's improve your solution!

pom.xml Outdated
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>${liquibase.version}</version>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove version, spring already provides it

pom.xml Outdated
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-maven-plugin</artifactId>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

replace to plugin section

@Data
@Entity
@Table(name = "roles")
@RequiredArgsConstructor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove RequiredArgsConstructor

public interface UserMapper {
UserDto toDto(User user);

User toUserModel(UserRegistrationRequestDto userDto);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not fixed

nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS,
implementationPackage = "<PACKAGE_NAME>.impl")
public interface UserMapper {
UserDto toDto(User user);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
UserDto toDto(User user);
UserDto toUserDto(User user);

}

private static String getToken(HttpServletRequest request) {
String authorizationHeader = request.getHeader("Authorization");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional
there is an existing constant: org.springframework.http.HttpHeaders.AUTHORIZATION

name = "users_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove empty line

Copy link

@liliia-ponomarenko liliia-ponomarenko left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good job! Let’s fix a few mistakes ;)

Comment on lines 14 to 16
String message() default "Passwords do not match";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
String message() default "Passwords do not match";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
String message() default "Passwords do not match";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };

UserRegistrationRequestDto> {

@Override
public boolean isValid(UserRegistrationRequestDto dto,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can add not null validation here

.anyRequest()
.authenticated()
)
.httpBasic(Customizer.withDefaults())

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do you need basic auth if we're using JWT?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I need just remove it?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, you don't need it here


@RequiredArgsConstructor
@RestController
@Validated

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you really need this annotation here?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes,how it works without it?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In such case you don't need Validated annotation.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not fixed

import jakarta.validation.constraints.Positive;
import java.math.BigDecimal;

public record CreateBookRequestDto(@NotBlank String title,
@NotBlank String author,
@NotBlank String isbn,
@NotNull @Positive BigDecimal price,
@NotBlank @Positive BigDecimal price,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NotNull correct here and better use PositiveOrZero

public UserDto register(UserRegistrationRequestDto requestDto)
throws RegistrationException {
if (userRepository.findByEmail(requestDto.email()).isPresent()) {
throw new RegistrationException("User with email: " + requestDto.email()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should you handle this exception? Maybe something else?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Create another exception?what`s wrong with this one?

@Override
public UserDto register(UserRegistrationRequestDto requestDto)
throws RegistrationException {
if (userRepository.findByEmail(requestDto.email()).isPresent()) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can use existByEmail from JPA

nullable: false
- column:
name: shipping_address
type: VARCHAR(255)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you must have the same maximum size in the query, as it may cause a SQL exception, or use a different type (check it everywhere)

type: boolean
defaultValueBoolean: false
constraints:
nullable: false

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add one empty line (check it in other files)

- include:
file: db\changelog\changes\03-create-roles-table.yaml
- include:
file: db/changelog/changes/04-create-users-roles.yaml

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why different slashs? looks weird

Copy link

@Elena-Bruyako Elena-Bruyako left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good job! Pay attention to comments that are not fixed

.anyRequest()
.authenticated()
)
.httpBasic(Customizer.withDefaults())

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, you don't need it here


@RequiredArgsConstructor
@RestController
@Validated

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In such case you don't need Validated annotation.

@@ -0,0 +1,8 @@
package com.example.springbootbookshop.dto.user;

public record UserDto(Long id,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can remove this class and use UserRegisterResponseDto instead

public String getAuthority() {
return "ROLE_" + name.name();
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not fixed


public enum RoleName {
ADMIN,
MANAGER,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not fixed

@Column(nullable = false)
private String lastName;
private String shippingAddress;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not fixed


@Override
public boolean isEnabled() {
return true;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not fixed

import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not fixed

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return userRepository.findByEmail(username).orElseThrow(() ->
new EntityNotFoundException("User doesn`t exist"));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not fixed

Copy link

@Elena-Bruyako Elena-Bruyako left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to fix some comments


@RequiredArgsConstructor
@RestController
@Validated

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not fixed

import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not fixed

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return userRepository.findByEmail(username).orElseThrow(() ->
new EntityNotFoundException("User doesn`t exist"));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method throw UsernameNotFoundException so you need to
userRepository.findByEmail(username).orElseThrow(() ->
new UsernameNotFoundException("User doesn`t exist"))

@@ -0,0 +1,11 @@
package com.example.springbootbookshop.exception;

public class RegistrationException extends RuntimeException {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you handle this exception ?

@@ -0,0 +1,8 @@
package com.example.springbootbookshop.dto.user;

public record UserDto(Long id,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
public record UserDto(Long id,
public record UserResponseDto(Long id,

Copy link

@liliia-ponomarenko liliia-ponomarenko left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good job!

public interface UserMapper {
UserResponseDto toUserDto(User user);

User toUserModel(UserRegistrationRequestDto userDto);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
User toUserModel(UserRegistrationRequestDto userDto);
User toUser(UserRegistrationRequestDto userDto);

@don-bigdad don-bigdad merged commit 4fe75e9 into master Oct 31, 2023
3 checks passed
@don-bigdad don-bigdad deleted the security-dev branch October 31, 2023 20:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants