Skip to content

Commit

Permalink
Fix: Resolve Checkstyle warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
AhmedMohamedAbdelaty committed Oct 30, 2024
1 parent 892f342 commit 41a4aed
Show file tree
Hide file tree
Showing 11 changed files with 67 additions and 31 deletions.
9 changes: 3 additions & 6 deletions src/main/java/com/activecourses/upwork/UpworkApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,8 @@

@SpringBootApplication
@EnableJpaAuditing

public class UpworkApplication {

public static void main(String[] args) {
SpringApplication.run(UpworkApplication.class, args);
}

public static void main(String[] args) {
SpringApplication.run(UpworkApplication.class, args);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ public class AuthEntryPointJwt implements AuthenticationEntryPoint {
private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class);

@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException)
throws IOException, ServletException {
logger.error("Unauthorized error: {}", authException.getMessage());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ public class AuthTokenFilter extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);

@Override
protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
protected void doFilterInternal(@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain)
throws ServletException, IOException {

try {
String jwt = jwtService.getJwtFromCookies(request);
if (jwt != null && jwtService.validateJwtToken(jwt)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,11 @@ public ResponseCookie getCleanJwtCookie() {
}

public ResponseCookie getCleanJwtRefreshCookie() {
return ResponseCookie.from(jwtRefreshCookie, "").path("/api/auth/refresh-token").maxAge(0).httpOnly(true).build();
return ResponseCookie.from(jwtRefreshCookie, "")
.path("/api/auth/refresh-token")
.maxAge(0)
.httpOnly(true)
.build();
}

public String generateAccessToken(UserDetails userDetails) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,10 @@ public ResponseEntity<ResponseDto> assignRolesToUser(@PathVariable int id, @Requ
: buildResponseEntity(HttpStatus.NOT_FOUND, false, null, "User not found.");
}

private ResponseEntity<ResponseDto> buildResponseEntity(HttpStatus status, boolean success, Object data, Object error) {
private ResponseEntity<ResponseDto> buildResponseEntity(HttpStatus status,
boolean success,
Object data,
Object error) {
return ResponseEntity
.status(status)
.body(ResponseDto
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,18 @@ public class UserController {
@Operation(summary = "Get all users",
description = "Retrieve a paginated list of all users. Only accessible by users with the ROLE_ADMIN role.",
parameters = {
@Parameter(name = "pageNo", in = ParameterIn.QUERY, description = "Page number", schema = @Schema(type = "integer", defaultValue = "0")),
@Parameter(name = "pageSize", in = ParameterIn.QUERY, description = "Page size", schema = @Schema(type = "integer", defaultValue = "10")),
@Parameter(name = "sortBy", in = ParameterIn.QUERY, description = "Sort by", schema = @Schema(type = "string", defaultValue = "id")),
@Parameter(name = "sortDir", in = ParameterIn.QUERY, description = "Sort direction", schema = @Schema(type = "string", defaultValue = "asc"))
@Parameter(name = "pageNo", in = ParameterIn.QUERY,
description = "Page number",
schema = @Schema(type = "integer", defaultValue = "0")),
@Parameter(name = "pageSize", in = ParameterIn.QUERY,
description = "Page size",
schema = @Schema(type = "integer", defaultValue = "10")),
@Parameter(name = "sortBy", in = ParameterIn.QUERY,
description = "Sort by",
schema = @Schema(type = "string", defaultValue = "id")),
@Parameter(name = "sortDir", in = ParameterIn.QUERY,
description = "Sort direction",
schema = @Schema(type = "string", defaultValue = "asc"))
}
)
@PreAuthorize("hasRole('ROLE_ADMIN')")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,12 @@ public class LoginRequestDto {
@Size(min = 6, message = "Password must be at least 6 characters long")
private String password;

public LoginRequestDto(@Email(message = "Email is not valid") @NotEmpty(message = "Email is required") @NotNull(message = "Email is required") String email,
@NotEmpty(message = "Password is required") @NotNull(message = "Password is required") @Size(min = 6, message = "Password must be at least 6 characters long") String password) {
public LoginRequestDto(@Email(message = "Email is not valid")
@NotEmpty(message = "Email is required")
@NotNull(message = "Email is required") String email,
@NotEmpty(message = "Password is required")
@NotNull(message = "Password is required")
@Size(min = 6, message = "Password must be at least 6 characters long") String password) {
this.email = email;
this.password = password;
}
Expand Down
10 changes: 5 additions & 5 deletions src/main/java/com/activecourses/upwork/model/RefreshToken.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ public class RefreshToken {

@Override
public String toString() {
return "RefreshToken{" +
"id=" + id +
", token='" + token + '\'' +
", expiryDate=" + expiryDate +
'}';
return "RefreshToken{"
+ "id=" + id
+ ", token='" + token + '\''
+ ", expiryDate=" + expiryDate
+ '}';
}
}
2 changes: 1 addition & 1 deletion src/main/java/com/activecourses/upwork/model/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public class User implements UserDetails, Principal {

@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, optional = true)
private RefreshToken refreshToken;
@OneToOne(mappedBy = "user",cascade = CascadeType.ALL)
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
private UserProfile userProfile;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ public class RefreshTokenService {
private final UserRepository userRepository;
private final JwtService jwtService;

public RefreshTokenService(RefreshTokenRepository refreshTokenRepository, UserRepository userRepository, JwtService jwtService) {
public RefreshTokenService(RefreshTokenRepository refreshTokenRepository,
UserRepository userRepository,
JwtService jwtService) {
this.refreshTokenRepository = refreshTokenRepository;
this.userRepository = userRepository;
this.jwtService = jwtService;
Expand Down Expand Up @@ -119,7 +121,9 @@ public RefreshToken createRefreshToken(int userId) {
public void verifyExpiration(RefreshToken token) {
if (token.getExpiryDate().compareTo(Instant.now()) < 0) {
refreshTokenRepository.delete(token);
throw new TokenRefreshException(token.getToken(), "Refresh token was expired. Please sign in again to obtain a new refresh token.");
throw new TokenRefreshException(token.getToken(),
"Refresh token was expired. "
+ "Please sign in again to obtain a new refresh token.");
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,19 +92,24 @@ public ResponseDto login(LoginRequestDto loginRequestDto) {
}

Authentication authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(loginRequestDto.getEmail(), loginRequestDto.getPassword()));
.authenticate(new UsernamePasswordAuthenticationToken(
loginRequestDto.getEmail(),
loginRequestDto.getPassword()
));

SecurityContextHolder.getContext().setAuthentication(authentication);

UserDetails userDetails = customUserDetailsService.loadUserByUsername(loginRequestDto.getEmail());
UserDetails userDetails = customUserDetailsService
.loadUserByUsername(loginRequestDto.getEmail());

ResponseCookie jwtCookie = jwtService.generateJwtCookie(userDetails);

int userId = ((User) userDetails).getId();

RefreshToken refreshToken = refreshTokenService.createRefreshToken(userId);

ResponseCookie refreshJwtCookie = jwtService.generateRefreshJwtCookie(refreshToken.getToken());
ResponseCookie refreshJwtCookie = jwtService
.generateRefreshJwtCookie(refreshToken.getToken());

return ResponseDto
.builder()
Expand All @@ -117,7 +122,8 @@ public ResponseDto login(LoginRequestDto loginRequestDto) {
@Override
public ResponseEntity<ResponseDto> logout() {
logger.info("User logout attempt");
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Object principal = SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
if (!principal.toString().equals("anonymousUser")) {
int userId = ((User) principal).getId();
refreshTokenService.deleteByUserId(userId);
Expand Down Expand Up @@ -166,7 +172,8 @@ public User findByEmail(String email) {
@Override
public void sendVerificationEmail(User user) {
logger.info("Sending verification email to: {}", user.getEmail());
String verificationLink = "http://localhost:8080/api/users/verify?token=" + user.getVerificationToken();
String verificationLink = "http://localhost:8080/api/users/verify?token="
+ user.getVerificationToken();

SimpleMailMessage message = new SimpleMailMessage();
message.setTo(user.getEmail());
Expand Down Expand Up @@ -196,7 +203,10 @@ public boolean reactivateUser(int userId) {
}

static User unwrapUser(Optional<User> entity) {
if (entity.isPresent()) return entity.get();
else throw new UnsupportedOperationException("Unimplemented method 'unwrapUser'");
if (entity.isPresent()) {
return entity.get();
} else {
throw new UnsupportedOperationException("Unimplemented method 'unwrapUser'");
}
}
}

0 comments on commit 41a4aed

Please sign in to comment.