Voltar ao blog
Publicado em por Caio Prado inglês

Code Log - Day 12

Using Spring Security's Authentication object to check product ownership before running product operations on Ixtore.

challengedaily-codingjava

Log

Today i worked on a side project.

Side Project

On the Ixtore project, i needed to check if the id of the user trying to call some product-related operation was the same as the user id referenced by the product. Since i'm using Spring Security, in every controller route handler method, i have access to an object of type "Authentication" as a parameter, in which i can retrieve the current logged user's id, and pass it to the service layer method, so it can perform the verification.

@RestController
@RequestMapping("/api/products")
public class ProductsController {

    @Autowired
    final private ProductsService productsService;

    public ProductsController(ProductsService productsService){
        this.productsService = productsService;
    }

    @GetMapping("{code}")
    @ResponseStatus(HttpStatus.OK)
    public ProductEntity getProductsByCode(@PathVariable("code") String code, Authentication currentUser) throws ProductNotFoundException{
        UserEntity currentUserPrincipal = (UserEntity) currentUser.getPrincipal();

        return productsService.getByCode(code,currentUserPrincipal.getUser_uuid());
    }