Skip to content

Commit

Permalink
simplified some code
Browse files Browse the repository at this point in the history
  • Loading branch information
M4urici0GM committed Oct 15, 2023
1 parent e8cf0ee commit ef7f798
Show file tree
Hide file tree
Showing 10 changed files with 72 additions and 97 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@
import dev.mgbarbosa.urlshortner.security.AuthenticatedUserDetails;
import dev.mgbarbosa.urlshortner.services.interfaces.AuthenticationService;
import jakarta.validation.Valid;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.AccessDeniedException;
import javax.management.InvalidApplicationException;

import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
Expand All @@ -19,38 +22,28 @@
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping(path = "/api/v1/auth")
public class AuthenticationController {
private final AuthenticationService authenticationService;

public AuthenticationController(AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
private final AuthenticationService authenticationService;

/**
* Tries to authenticate user with username and password.
*
* @param request Request containing username and password
* @return returns object containing userDetails + jwtToken
*/
@PostMapping
public ResponseEntity<AuthenticateResponseDto> authenticateUser(@Valid @RequestBody AuthenticateRequestDto request)
throws URISyntaxException, InvalidApplicationException, InvalidOperationException {
final var result = authenticationService.authenticateUser(request);
return ResponseEntity
.created(new URI(""))
.body(result);
}
/**
* Tries to authenticate user with username and password.
*
* @param request Request containing username and password
* @return returns object containing userDetails + jwtToken
*/
@PostMapping
public AuthenticateResponseDto authenticateUser(@Valid @RequestBody AuthenticateRequestDto request) throws InvalidApplicationException, InvalidOperationException {
return authenticationService.authenticateUser(request);
}

/**
* Get user profile, containing user details + profile info, such as roles.
*/
@GetMapping("/profile")
@PreAuthorize("isAuthenticated()")
ResponseEntity<AuthenticatedUserDetails> getProfile() throws AccessDeniedException {
var user = authenticationService.getAuthenticatedUser();
return ResponseEntity
.ok()
.body(user);
}
/**
* Get user profile, containing user details + profile info, such as roles.
*/
@GetMapping("/profile")
@PreAuthorize("isAuthenticated()")
AuthenticatedUserDetails getProfile() throws AccessDeniedException {
return authenticationService.getAuthenticatedUser();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,12 @@ public class ControllerAdvice extends ResponseEntityExceptionHandler {
* Responsible for handling Validation errors.
*/
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
protected ResponseEntity<Object> handleMethodArgumentNotValid(
final MethodArgumentNotValidException ex,
final HttpHeaders headers,
final HttpStatusCode status,
final WebRequest request
) {
var errors = new HashMap<String, String>();
ex.getBindingResult()
.getAllErrors()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
@Controller
public class DefaultErrorController implements ErrorController {

@GetMapping(path = "/error")
public ResponseEntity<ApiError<Object>> notFound() {
final var apiError = new ApiError<>(HttpStatus.NOT_FOUND, "The requested path was not found.");
return new ResponseEntity<>(apiError, apiError.getHttpStatus());
}
@GetMapping(path = "/error")
public ResponseEntity<ApiError<Object>> notFound() {
final var apiError = new ApiError<>(HttpStatus.NOT_FOUND, "The requested path was not found.");
return new ResponseEntity<>(apiError, apiError.getHttpStatus());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,10 @@
public class PingController {

@GetMapping
public ResponseEntity<HealthCheckResponseDto> healthCheck() {
return ResponseEntity.ok()
.body(HealthCheckResponseDto
public HealthCheckResponseDto healthCheck() {
return HealthCheckResponseDto
.builder()
.message("Im alive and well!")
.build());
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import dev.mgbarbosa.urlshortner.services.interfaces.ShortenerService;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
Expand All @@ -12,15 +14,15 @@
@RequestMapping(path = "/api/v1/redirect")
public class RedirectController {

private final ShortenerService shortenerService;
private final ShortenerService shortenerService;

public RedirectController(ShortenerService shortenerService) {
this.shortenerService = shortenerService;
}
public RedirectController(ShortenerService shortenerService) {
this.shortenerService = shortenerService;
}

@GetMapping("/{shortVersion}")
public void redirect(@PathVariable String shortVersion, HttpServletResponse httpResponse) throws IOException {
var result = shortenerService.findShortUrlBy(shortVersion);
httpResponse.sendRedirect(result.getOriginalUrl());
}
@GetMapping("/{shortVersion}")
public void redirect(@PathVariable String shortVersion, HttpServletResponse httpResponse) throws IOException {
var result = shortenerService.findShortUrlBy(shortVersion);
httpResponse.sendRedirect(result.getOriginalUrl());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,44 +4,32 @@
import dev.mgbarbosa.urlshortner.dtos.requests.CreateShortUrlRequest;
import dev.mgbarbosa.urlshortner.services.interfaces.ShortenerService;
import jakarta.validation.Valid;

import java.net.URI;
import java.net.URISyntaxException;

import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
@RequestMapping(path = "/api/v1/shortener")
@PreAuthorize("permitAll()")
public class ShortenerController {
private final ShortenerService shortenerService;

public ShortenerController(ShortenerService shortenerService) {
this.shortenerService = shortenerService;
}

@PostMapping
@ResponseBody
public ResponseEntity<ShortenedUrlDto> shortUrl(@Valid @RequestBody CreateShortUrlRequest request)
throws
AccessDeniedException,
URISyntaxException {

return ResponseEntity
.created(new URI(""))
.body(shortenerService.createShortUrl(request));
@ResponseStatus(HttpStatus.CREATED)
public ShortenedUrlDto shortUrl(@Valid @RequestBody CreateShortUrlRequest request) throws AccessDeniedException {
return shortenerService.createShortUrl(request);
}

@GetMapping("/{shortVersion}")
public ResponseEntity<ShortenedUrlDto> findUrl(@PathVariable String shortVersion) {
var result = shortenerService.findShortUrlBy(shortVersion);
return ResponseEntity.ok().body(result);
public ShortenedUrlDto findUrl(@PathVariable String shortVersion) {
return shortenerService.findShortUrlBy(shortVersion);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,11 @@
import jakarta.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(path = "/api/v1/user")
Expand All @@ -26,15 +24,14 @@ public UserController(UserService userService) {
}

@PostMapping
ResponseEntity<UserDto> createUser(@Valid @RequestBody UserDto request) throws EntityExists, URISyntaxException {
var user = userService.createUser(request);
return ResponseEntity.created(new URI("")).body(user);
@ResponseStatus(HttpStatus.CREATED)
UserDto createUser(@Valid @RequestBody UserDto request) throws EntityExists {
return userService.createUser(request);
}

@GetMapping
@PreAuthorize("isAuthenticated()")
ResponseEntity<PaginatedResponse<UserDto>> findAll(@Valid PaginatedRequest request) {
var users = userService.getUsers(request);
return ResponseEntity.ok().body(users);
PaginatedResponse<UserDto> findAll(@Valid PaginatedRequest request) {
return userService.getUsers(request);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import org.springframework.data.repository.PagingAndSortingRepository;

public interface UserRepository extends PagingAndSortingRepository<User, UUID>, CrudRepository<User, UUID> {
Optional<User> findByEmail(String email);
Optional<User> findByUsername(String username);
boolean existsByEmail(String email);
boolean existsByUsername(String username);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import lombok.RequiredArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
Expand All @@ -15,16 +17,11 @@
* Responsible for reading, and validating token sent in Authorization Header.
*/
@Component
@RequiredArgsConstructor
public class JwtSecurityFilter extends OncePerRequestFilter {
private final SecurityService securityService;
private final CustomUserDetailsService userDetailService;

public JwtSecurityFilter(SecurityService jwtUtils, CustomUserDetailsService userDetailService) {
this.securityService = jwtUtils;
this.userDetailService = userDetailService;
}


/**
* Responsible for filtering and/or denying unauthorized http requests.
* @param request HttpRequest
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,13 @@
public class PasswordAuthenticationStrategy implements AuthenticationStrategy {
private final UserRepository userRepository;
private final SecurityService securityService;
private final SecurityCachingRepository _securityCache;

public PasswordAuthenticationStrategy(
UserRepository userRepository,
SecurityService securityService,
SecurityCachingRepository securityCache) {
SecurityService securityService
) {
this.userRepository = userRepository;
this.securityService = securityService;
_securityCache = securityCache;
}

@Override
Expand All @@ -39,8 +37,6 @@ public AuthenticateResponseDto execute(AuthenticateRequestDto request) throws In
var generatedJwt = securityService.generateToken(user);
var refreshToken = securityService.generateRefreshToken(user);

_securityCache.storeRefreshToken(refreshToken, user);

return new AuthenticateResponseDto(
new UserDto(user),
generatedJwt,
Expand Down

0 comments on commit ef7f798

Please sign in to comment.