Skip to content

Commit

Permalink
Merge pull request #345 from tallyto/23.17
Browse files Browse the repository at this point in the history
Obtendo usuário autenticado no Resource Server
  • Loading branch information
tallyto authored Jan 11, 2024
2 parents 4992876 + f8a3b4a commit e8ba168
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import com.tallyto.algafood.api.v1.openapi.controller.PedidoControllerOpenApi;
import com.tallyto.algafood.core.data.PageWrapper;
import com.tallyto.algafood.core.data.PageableTranslator;
import com.tallyto.algafood.core.security.AlgaSecurity;
import com.tallyto.algafood.domain.exception.EntidadeNaoEncontradaException;
import com.tallyto.algafood.domain.exception.NegocioException;
import com.tallyto.algafood.domain.model.Pedido;
Expand Down Expand Up @@ -48,6 +49,9 @@ public class PedidoController implements PedidoControllerOpenApi {
@Autowired
private PagedResourcesAssembler<Pedido> pagedResourcesAssembler;

@Autowired
private AlgaSecurity algaSecurity;

@GetMapping
public PagedModel<PedidoResumoModel> pesquisar(PedidoFilter filtro,
@PageableDefault(size = 10) Pageable pageable) {
Expand All @@ -68,9 +72,8 @@ public PedidoModel adicionar(@Valid @RequestBody PedidoInput pedidoInput) {
try {
Pedido novoPedido = assembler.toEntity(pedidoInput);

// TODO pegar usuário autenticado
novoPedido.setCliente(new Usuario());
novoPedido.getCliente().setId(1L);
novoPedido.getCliente().setId(algaSecurity.getUsuarioId());

novoPedido = emissaoPedido.emitir(novoPedido);

Expand Down
19 changes: 19 additions & 0 deletions src/main/java/com/tallyto/algafood/core/security/AlgaSecurity.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.tallyto.algafood.core.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Component;

@Component
public class AlgaSecurity {

public Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
public Long getUsuarioId() {
Jwt jwt = (Jwt) getAuthentication().getPrincipal();

return jwt.getClaim("usuario_id");
}
}

0 comments on commit e8ba168

Please sign in to comment.