Skip to content

Commit

Permalink
feat: prometheus
Browse files Browse the repository at this point in the history
  • Loading branch information
oproprioleonardo committed Oct 12, 2024
1 parent b9b8dc8 commit 0c15fc9
Show file tree
Hide file tree
Showing 8 changed files with 99 additions and 9 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package br.com.ifsp.tickets.app.enrollment.core.create;

import br.com.ifsp.tickets.domain.user.User;

import java.time.LocalDate;

public record CreateEnrollmentInput(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
@Getter
public enum PermissionType {

ADMIN("Acesso a recursos restritos"),
MANAGE_ANY_USER("Gerenciar usuários"),
MANAGE_ANY_COMPANY("Gerenciar companhias"),
MANAGE_ANY_TICKET("Gerenciar ingressos"),
Expand Down
4 changes: 3 additions & 1 deletion infrastructure/build.gradle
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.7'
id 'org.springframework.boot' version '3.2.10'
id 'io.spring.dependency-management' version '1.1.5'
}

Expand Down Expand Up @@ -40,6 +40,8 @@ dependencies {

implementation group: 'com.mercadopago', name: 'sdk-java', version: '2.1.29'

implementation 'io.micrometer:micrometer-registry-prometheus'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-mail'
implementation 'org.springframework.boot:spring-boot-starter-security'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package br.com.ifsp.tickets.infra.config.app;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import br.com.ifsp.tickets.app.auth.IAuthUtils;
import br.com.ifsp.tickets.infra.config.security.entrypoint.AuthEntryPointJwt;
import br.com.ifsp.tickets.infra.config.security.filter.BasicAuthFilter;
import br.com.ifsp.tickets.infra.config.security.filter.JwtAuthFilter;
import br.com.ifsp.tickets.infra.config.security.service.CustomUserDetailsService;
import br.com.ifsp.tickets.infra.contexts.user.AuthUtils;
Expand All @@ -26,6 +27,7 @@
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;

@EnableWebSecurity
Expand All @@ -40,11 +42,11 @@ public class SecurityConfig {
"/docs/swagger.html",
"/error",
"/error/**",
// Spring Actuator
"/actuator/**",
"/health/**",
// Api endpoints
"/v1/auth/**",
"/v1/auth/login",
"/v1/auth/register",
"/v1/auth/activate/*",
"/v1/auth/recovery/**",
"/v1/cep/**",
"/v1/event/*/ticketSale",
"/v1/enrollment/webhook"
Expand Down Expand Up @@ -91,13 +93,15 @@ public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity, IAuthU
cors.addAllowedMethod(HttpMethod.GET);
cors.addAllowedMethod(HttpMethod.DELETE);
return httpSecurity
.addFilterAfter(new BasicAuthFilter(customUserDetailsService), BasicAuthenticationFilter.class)
.addFilterAfter(new JwtAuthFilter(authService, customUserDetailsService), UsernamePasswordAuthenticationFilter.class)
.cors(crs -> crs.configurationSource(request -> cors))
.authorizeHttpRequests(authorize -> authorize
.requestMatchers(HttpMethod.GET, "/v1/event/*").permitAll()
.requestMatchers(HttpMethod.GET, "/v1/event/*/thumbnail").permitAll()
.requestMatchers(HttpMethod.POST, "/v1/event/search").permitAll()
.requestMatchers(AUTH_WHITELIST).permitAll()
.requestMatchers("/actuator/**").hasAuthority("ADMIN")
.anyRequest().authenticated())
.csrf(AbstractHttpConfigurer::disable)
.authenticationProvider(authenticationProvider)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package br.com.ifsp.tickets.infra.config.security.filter;

import br.com.ifsp.tickets.domain.user.User;
import br.com.ifsp.tickets.infra.config.security.service.CustomUserDetailsService;
import br.com.ifsp.tickets.infra.contexts.user.persistence.UserJpaEntity;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Base64;

@Slf4j
public class BasicAuthFilter extends OncePerRequestFilter {

private final CustomUserDetailsService userDetailsService;


public BasicAuthFilter(CustomUserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}

@Override
protected void doFilterInternal(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable FilterChain chain) throws IOException, ServletException {
assert request != null;
final String authHeader = request.getHeader("Authorization");

if (authHeader != null && authHeader.startsWith("Basic ")) {
try {
final String base64Credentials = authHeader.substring("Basic ".length()).trim();
final String credentials = new String(Base64.getDecoder().decode(base64Credentials));
// credentials = username:password
final String[] values = credentials.split(":", 2);

final User userDetails = this.userDetailsService.getByEmail(values[0]);
final UserJpaEntity userJpa = UserJpaEntity.from(userDetails);
if (!BCrypt.checkpw(values[1], userJpa.getPassword())) {
assert chain != null;
chain.doFilter(request, response);
return;
}

final UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userJpa,
null,
userJpa.getAuthorities()
);
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
} catch (final Exception e) {
log.info(e.getMessage());
SecurityContextHolder.clearContext();
}
}
assert chain != null;
chain.doFilter(request, response);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,8 @@ public class CustomUserDetailsService {
public User getByUUID(UUID uuid) {
return userRepository.findById(uuid).orElseThrow(() -> new UsernameNotFoundException("Token is not valid")).toAggregate();
}

public User getByEmail(String email) {
return userRepository.findByUsernameOrEmail(email).orElseThrow(() -> new UsernameNotFoundException("Credentials is not valid")).toAggregate();
}
}
15 changes: 15 additions & 0 deletions infrastructure/src/main/resources/application.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,21 @@ mercadopago:
access:
token: ${MERCADOPAGO_ACCESSTOKEN}

management:
endpoints:
web:
exposure:
include: [ "prometheus", "health" ]
endpoint:
metrics:
enabled: true
health:
show-details: always
prometheus:
metrics:
export:
enabled: true

spring:
mail:
host: ${MAIL_HOST}
Expand Down

0 comments on commit 0c15fc9

Please sign in to comment.